Skip to main content

nomiscript/
eval.rs

1use crate::ast::{Expr, Program};
2use crate::compiler::expr::{eval_value, format_expr, format_form};
3use crate::error::{Error, Result};
4use crate::runtime::{SymbolTable, Value};
5
6pub fn eval_program(symbols: &mut SymbolTable, program: &Program) -> Result<Value> {
7    // Starts a fresh compile-time work budget (ADR-0034 / plan 0011 Phase
8    // 0) for THIS call. Without this, a caller that reuses one `SymbolTable`
9    // across many `eval_program` calls — e.g. the `nms` interpreter's REPL,
10    // which holds `self.symbols` for the whole session — would accumulate
11    // charges across every prior call and eventually reject a small,
12    // perfectly ordinary form once the historical total crossed
13    // `MAX_ELAB_WORK`, matching neither this call's own cost nor any
14    // reasonable per-call budget. `Compiler::compile_script` /
15    // `compile_eval` already reset per top-level compile for the same
16    // reason.
17    symbols.reset_budget();
18    crate::compiler::expr::reject_unindexable_literals(&program.exprs)?;
19    let Some((last, init)) = program.exprs.split_last() else {
20        return Ok(Value::Nil);
21    };
22    for expr in init {
23        eval_value(symbols, expr)?;
24    }
25    let value = eval_value(symbols, last)?;
26    expr_to_value(&value)
27}
28
29fn expr_to_value(expr: &Expr) -> Result<Value> {
30    match expr {
31        Expr::Nil => Ok(Value::Nil),
32        Expr::T => Ok(Value::T),
33        Expr::Number(n) => Ok(Value::Number(*n)),
34        Expr::String(s) => Ok(Value::String(s.clone())),
35        Expr::Symbol(s) => Ok(Value::Symbol(s.clone())),
36        Expr::Bytes(b) => Ok(Value::Bytes(b.clone())),
37        Expr::Datum(inner) => quoted_to_value(inner),
38        Expr::List(_) => Ok(Value::String(format_expr(expr))),
39        Expr::Lambda(_, _) => Ok(Value::String(format_expr(expr))),
40        Expr::RuntimeValue(val) => Ok(val.clone()),
41        _ => Err(Error::Compile(format!(
42            "unsupported expression: {}",
43            format_form(expr)
44        ))),
45    }
46}
47
48fn quoted_to_value(inner: &Expr) -> Result<Value> {
49    match inner {
50        Expr::Nil => Ok(Value::Nil),
51        Expr::T => Ok(Value::T),
52        Expr::Number(n) => Ok(Value::Number(*n)),
53        Expr::String(s) => Ok(Value::String(s.clone())),
54        Expr::Symbol(s) => Ok(Value::Symbol(s.clone())),
55        Expr::Bytes(b) => Ok(Value::Bytes(b.clone())),
56        Expr::List(_) | Expr::Cons(_, _) => Ok(Value::String(format_expr(inner))),
57        _ => Err(Error::Compile(format!(
58            "unsupported quoted expression: {}",
59            format_form(inner)
60        ))),
61    }
62}
63
64#[cfg(test)]
65#[path = "eval_tests.rs"]
66mod tests;