Skip to main content

predicator_rs/
compiler.rs

1//! The compiler: a source in, an instruction list out. The lexer scans the
2//! source, the parser reads the tokens into a tree, and the emitter
3//! ([`emitter`]) walks the tree into the instructions the evaluator runs,
4//! the same list the reference's compiler emits for the same source.
5
6mod emitter;
7
8use crate::lexer::{self, Refusal};
9use crate::{Error, Instructions, parser};
10
11/// Compiles an expression's source to the instruction list it runs as.
12///
13/// The instructions are the reference's for the same source: what
14/// [`evaluate`](crate::evaluate) runs, and what
15/// [`Instructions::to_json`] writes in the conformance corpus's tagged
16/// encoding.
17///
18/// A source that does not scan or parse is refused with an
19/// [`Error::Parse`] carrying the reference's message, the position of the
20/// token it names, and a reason naming the refusal (`unexpected_character`,
21/// `trailing_token`, `nesting_depth_exceeded` and others). A statement is
22/// not an expression: `x = 1` is refused here and compiled by
23/// [`compile_program`].
24///
25/// ```
26/// use predicator_rs::{Context, Options, Position, Value, compile, evaluate};
27///
28/// let instructions = compile("score > 85")?;
29/// assert_eq!(
30///     instructions.to_json()?,
31///     r#"[["load","score"],["lit",85],["compare","GT"]]"#
32/// );
33/// let mut context = Context::new();
34/// context.insert("score", Value::from(90));
35/// assert_eq!(evaluate(&instructions, &context, &Options::new())?, Value::from(true));
36///
37/// let refused = compile("score >").unwrap_err();
38/// assert_eq!(refused.type_name(), "ParseError");
39/// assert_eq!(refused.position(), Some(Position { line: 1, column: 8 }));
40/// # Ok::<(), predicator_rs::Error>(())
41/// ```
42pub fn compile(source: &str) -> Result<Instructions, Error> {
43    let tokens = lexer::tokenize(source).map_err(refused)?;
44    let node = parser::parse(&tokens).map_err(refused)?;
45    Ok(Instructions {
46        list: emitter::expression(&node),
47    })
48}
49
50/// Compiles a statement program's source, one statement or more, to the
51/// instruction list it runs as.
52///
53/// A statement is an assignment (`location = value`, the location a
54/// variable under any run of `.name` and `[key]` steps), an `if` with an
55/// optional `else` or `else if`, a `while`, or an expression. Statements
56/// are separated by `;`, and a statement ending in a closing brace needs
57/// none before the next. Each compiles as the reference compiles it: an
58/// assignment to its location's segments, its value and a `store`; an
59/// expression to its instructions and a `pop`; an `if` and a `while` to
60/// their condition, a jump over their blocks, and a back edge for the
61/// `while`. [`execute`](crate::execute) and
62/// [`execute_value`](crate::execute_value) run the list.
63///
64/// A source that does not scan or parse is refused as [`compile`] refuses
65/// one, with an [`Error::Parse`].
66///
67/// ```
68/// use predicator_rs::{Context, Key, Options, Value, compile_program, execute};
69///
70/// let program = compile_program("x = 1; if x > 0 { y = x + 1 }")?;
71/// let execution = execute(&program, &Context::new(), &Options::new())?;
72/// assert_eq!(execution.context().get(&Key::from("y")), Some(&Value::from(2)));
73///
74/// let refused = compile_program("x =").unwrap_err();
75/// assert_eq!(refused.type_name(), "ParseError");
76/// # Ok::<(), predicator_rs::Error>(())
77/// ```
78pub fn compile_program(source: &str) -> Result<Instructions, Error> {
79    let tokens = lexer::tokenize(source).map_err(refused)?;
80    let program = parser::parse_program(&tokens).map_err(refused)?;
81    Ok(Instructions {
82        list: emitter::program(&program),
83    })
84}
85
86/// The error a refusal answers: its parse error, at the start of its span.
87fn refused(refusal: Refusal) -> Error {
88    Error::Parse(*refusal.error)
89}