use crate::{
ast::{AssignOp, BinaryOp, Expr, ExprKind, Stmt, StmtKind},
error::Result,
library::{boolean, fault, integer, key},
value::{Object, Value, expansion_error},
};
use super::{CodeFlow, Evaluator, at, binary, lookup_index};
impl<'a> Evaluator<'a> {
pub fn execute(&mut self, statements: &[Stmt]) -> Result<()> {
self.statements(statements)?;
if self.flow != CodeFlow::Normal {
self.flow = CodeFlow::Normal;
let error = fault("code break or continue requires a code loop");
return Err(statements
.last()
.map_or_else(|| error.clone(), |stmt| at(error.clone(), stmt.span)));
}
Ok(())
}
pub(super) fn statements(&mut self, statements: &[Stmt]) -> Result<()> {
for statement in statements {
self.statement(statement)
.map_err(|error| at(error, statement.span))?;
if self.flow != CodeFlow::Normal {
break;
}
}
Ok(())
}
fn statement(&mut self, statement: &Stmt) -> Result<()> {
match &statement.kind {
StmtKind::Let {
pattern,
mutable,
value,
..
} => {
let value = self.eval(value)?;
self.bind_pattern(pattern, &value, *mutable)?;
}
StmtKind::Assign { target, op, value } => {
let (name, keys) = self.place(target)?;
let value = self.eval(value)?;
self.update(&name, &keys, |old| {
let op = match op {
AssignOp::Set => return Ok(value),
AssignOp::Add => BinaryOp::Add,
AssignOp::Sub => BinaryOp::Sub,
AssignOp::Mul => BinaryOp::Mul,
AssignOp::Div => BinaryOp::Div,
AssignOp::Rem => BinaryOp::Rem,
AssignOp::Xor => BinaryOp::Xor,
};
let old = old.ok_or_else(|| fault("assignment target does not exist"))?;
binary(&op, old, &value)
})?;
}
StmtKind::Expr(expr) => {
self.eval(expr)?;
}
StmtKind::For {
pattern,
iterable,
body,
} => {
let value = self.eval(iterable)?;
for (key, value) in self.entries(&value)? {
self.charge_iteration()?;
self.scoped(|this| {
this.loop_binding(pattern, key, value, true)?;
this.block(body)
})?;
if std::mem::take(&mut self.flow) == CodeFlow::Break {
break;
}
}
}
StmtKind::While { test, body } => {
while boolean(&self.eval(test)?)? {
self.charge_iteration()?;
self.block(body)?;
if std::mem::take(&mut self.flow) == CodeFlow::Break {
break;
}
}
}
StmtKind::Break => self.flow = CodeFlow::Break,
StmtKind::Continue => self.flow = CodeFlow::Continue,
}
Ok(())
}
pub(super) fn mutate(
&mut self,
receiver: &Expr,
method: &str,
args: &[Expr],
) -> Result<Value<'a>> {
let (name, keys) = self.place(receiver)?;
let args = self.arguments(args)?;
let limit = self.expansion;
let call_limits = self.call_limits();
let mut result = Value::Null;
self.update(&name, &keys, |old| {
let old = old.ok_or_else(|| fault("mutation target does not exist"))?;
if !matches!(method, "insert" | "retain") {
let operands = super::Operands(args.clone());
let mut callbacks = operands.closures();
let args = operands.borrow(&mut callbacks);
if let Some(updated) =
crate::collections::method_with_limits(method, old, args, call_limits)
{
let updated = updated?;
if matches!(updated.type_name(), "list" | "map") {
updated.entries(limit)?;
}
return Ok(updated);
}
}
match (old.type_name(), method, args.as_slice()) {
("list", "push" | "prepend", [item]) => {
let mut list = old
.entries(limit)?
.into_iter()
.map(|(_, item)| item)
.collect::<Vec<_>>();
if list.len() >= limit {
return Err(expansion_error());
}
if method == "push" {
list.push(item.clone());
} else {
list.insert(0, item.clone());
}
Ok(Value::List(list))
}
("list", "insert", [index, item]) => {
let mut list = old
.entries(limit)?
.into_iter()
.map(|(_, item)| item)
.collect::<Vec<_>>();
if list.len() >= limit {
return Err(expansion_error());
}
let index = usize::try_from(integer(index)?)
.ok()
.filter(|index| *index <= list.len())
.ok_or_else(|| fault("list insertion index is out of range"))?;
list.insert(index, item.clone());
Ok(Value::List(list))
}
("list", "pop", []) => {
let mut list = old
.entries(limit)?
.into_iter()
.map(|(_, item)| item)
.collect::<Vec<_>>();
result = list.pop().unwrap_or(Value::Null);
Ok(Value::List(list))
}
("list", "retain", [Value::Object(callback)]) => {
let mut list = Vec::new();
for (_, item) in old.entries(limit)? {
if retain(callback.as_ref(), std::slice::from_ref(&item))? {
list.push(item);
}
}
Ok(Value::List(list))
}
("map", "insert", [field, value]) => {
let mut map = as_map(old, limit)?;
result = map
.insert(key(field)?, value.clone())
.unwrap_or(Value::Null);
if map.len() > limit {
return Err(expansion_error());
}
Ok(Value::Map(map))
}
("map", "retain", [Value::Object(callback)]) => {
let mut map = indexmap::IndexMap::new();
for (field, item) in old.entries(limit)? {
if retain(callback.as_ref(), &[field.clone(), item.clone()])? {
map.insert(key(&field)?, item);
}
}
Ok(Value::Map(map))
}
_ => Err(fault(format!(
"invalid arguments for {method} on {}",
old.type_name()
))),
}
})?;
Ok(result)
}
fn place(&mut self, expr: &Expr) -> Result<(String, Vec<Value<'a>>)> {
let mut keys = Vec::new();
let name = self.place_keys(expr, &mut keys)?;
Ok((name, keys))
}
fn place_keys(&mut self, expr: &Expr, keys: &mut Vec<Value<'a>>) -> Result<String> {
match &expr.kind {
ExprKind::Path(path) if path.len() == 1 => Ok(path[0].clone()),
ExprKind::Field {
receiver,
name,
optional: false,
} => {
let root = self.place_keys(receiver, keys)?;
keys.push(Value::string(name.clone()));
Ok(root)
}
ExprKind::Index {
receiver,
index,
optional: false,
} => {
let root = self.place_keys(receiver, keys)?;
keys.push(self.eval(index)?);
Ok(root)
}
_ => Err(at(
fault("mutation requires a mutable local binding"),
expr.span,
)),
}
}
fn update(
&mut self,
name: &str,
keys: &[Value<'a>],
change: impl FnOnce(Option<&Value<'a>>) -> Result<Value<'a>>,
) -> Result<()> {
let missing = || fault(format!("`{name}` is not a mutable local binding"));
let (scope, index) = self
.scopes
.iter()
.enumerate()
.skip(self.scope_start)
.rev()
.find_map(|(index, scope)| {
let binding = scope.bindings.get_index_of(name);
let binding = binding.or_else(|| {
(scope.view_value(name).is_some()
|| name == "loop" && scope.loop_state.is_some())
.then_some(usize::MAX)
});
binding.map(|binding| (index, binding))
})
.ok_or_else(missing)?;
let (_, binding) = self.scopes[scope]
.bindings
.get_index_mut(index)
.ok_or_else(missing)?;
let binding = binding
.as_mut()
.filter(|binding| binding.mutable)
.ok_or_else(missing)?;
let updated = replace(Some(&binding.value), keys, self.expansion, change)?;
let previous = std::mem::replace(&mut binding.value, updated);
if scope < self.view_start
&& !self.undo[self.undo_start..]
.iter()
.any(|entry| entry.scope == scope && entry.binding == index)
{
self.undo.push(super::Undo {
scope,
binding: index,
value: previous,
});
}
Ok(())
}
}
fn retain<'a>(object: &dyn Object<'a>, args: &[Value<'a>]) -> Result<bool> {
boolean(
&object
.call(args)
.ok_or_else(|| fault("retain requires a closure"))??,
)
}
fn as_map<'a>(value: &Value<'a>, limit: usize) -> Result<crate::value::ValueMap<'a>> {
value
.entries(limit)?
.into_iter()
.map(|(field, item)| Ok((key(&field)?, item)))
.collect()
}
fn replace<'a>(
value: Option<&Value<'a>>,
keys: &[Value<'a>],
limit: usize,
change: impl FnOnce(Option<&Value<'a>>) -> Result<Value<'a>>,
) -> Result<Value<'a>> {
let Some((index, rest)) = keys.split_first() else {
return change(value);
};
let value = value.ok_or_else(|| fault("assignment target does not exist"))?;
let old = lookup_index(value, index)?;
let next = replace(old.as_ref(), rest, limit, change)?;
match value.type_name() {
"list" => {
let mut list = value
.entries(limit)?
.into_iter()
.map(|(_, item)| item)
.collect::<Vec<_>>();
let index = usize::try_from(integer(index)?)
.ok()
.and_then(|index| list.get_mut(index))
.ok_or_else(|| fault("list assignment index is out of range"))?;
*index = next;
Ok(Value::List(list))
}
"map" => {
let mut map = as_map(value, limit)?;
map.insert(key(index)?, next);
if map.len() > limit {
return Err(expansion_error());
}
Ok(Value::Map(map))
}
_ => Err(fault("assignment requires a list or map")),
}
}
pub(super) fn is_mutator(name: &str) -> bool {
matches!(
name,
"push"
| "prepend"
| "insert"
| "retain"
| "pop"
| "add"
| "unshift"
| "shift"
| "splice"
| "put"
| "set"
| "get_or_put"
| "forget"
| "pull"
| "transform"
| "offset_set"
| "offset_unset"
)
}