Skip to main content

evaluate

Function evaluate 

Source
pub fn evaluate<P: Program>(
    program: P,
    context: &Context,
    options: &Options<'_>,
) -> Result<Value, Error>
Expand description

Evaluates program over context and answers the value it leaves on top of the stack.

The program is an &Instructions, or a &str source compiled as an expression (compile); a source that does not compile is refused with its Error::Parse. It runs in expression mode, as the reference’s instruction-set text states it: from its first instruction to its end, and its answer is the top of the stack (a run that ends with nothing on it fails with the reason empty_stack).

A variable the context does not bind is read as options says (OnUnbound). Under the default, a run whose answer is undefined, or that fails because an instruction refused an undefined operand, fails instead with an UndefinedVariableError (reason unbound_variable) naming the first unbound variable it loaded, when it loaded one.

The run may take as many back edges (the jump_backward instruction) as Options::loop_budget says, and fails with the reason loop_budget_exceeded at one past that. A store writes a copy of the context that later instructions in the run read; the context passed in is never changed, and Options::protected_roots is not read.

Before anything runs, every value the context binds is checked against the value domain (Context).

use predicator_rs::{Context, Instructions, OnUnbound, Options, Value, evaluate};

let program = Instructions::from_json(r#"[["load","score"],["lit",85],["compare","GT"]]"#)?;
let mut context = Context::new();
context.insert("score", Value::from(90));
assert_eq!(evaluate(&program, &context, &Options::new())?, Value::from(true));

let unbound = evaluate(&program, &Context::new(), &Options::new()).unwrap_err();
assert_eq!(unbound.type_name(), "UndefinedVariableError");
assert_eq!(unbound.reason(), "unbound_variable");

let strict = Options::new().on_unbound(OnUnbound::Error);
assert_eq!(evaluate(&program, &Context::new(), &strict).unwrap_err().reason(), "unbound_variable");