Skip to main content

compile

Function compile 

Source
pub fn compile(source: &str) -> Result<Instructions, Error>
Expand description

Compiles an expression’s source to the instruction list it runs as.

The instructions are the reference’s for the same source: what evaluate runs, and what Instructions::to_json writes in the conformance corpus’s tagged encoding.

A source that does not scan or parse is refused with an Error::Parse carrying the reference’s message, the position of the token it names, and a reason naming the refusal (unexpected_character, trailing_token, nesting_depth_exceeded and others). A statement is not an expression: x = 1 is refused here and compiled by compile_program.

use predicator_rs::{Context, Options, Position, Value, compile, evaluate};

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

let refused = compile("score >").unwrap_err();
assert_eq!(refused.type_name(), "ParseError");
assert_eq!(refused.position(), Some(Position { line: 1, column: 8 }));