Expand description
Transformation of the AST into Blocks that can be evaluated into strings.
ASTs can’t be directly evaluated because the trees they build describe the order of operations of expressions, not control flow. They have no notion of scoping and branching. The Control flow is described by a tree of Blocks
§Block
A Block can either hold a sequence of [super::parser::Node] are evaluated in order, or a sequence of Blocks which are used for branching.
§EvaluationContext
Anything data that expressions reference that is not literals is stored in a context. This includes variables, functions, and builders.
§evaluator::Evaluator And evaluator::EvaluatorBuilder
An evaluator::Evaluator holds a sequence of Blocks. The evaluator::EvaluatorBuilder takes a sequence of [crate::parser::Node]s and constructs an evaluator::Evaluator.
§contained_evaluator::ContainedEvaluator
evaluator::Evaluator has two lifetime bounds which is inconvenient in some cases. contained_evaluator::ContainedEvaluator is a self referential struct that eliminates these lifetime bounds and can be much more easily used.
§Dependencies
This struct holds all the items the evaluator references such as variables, functions, and builders. This information is used by some of the components of crate::builder
§Example
let source = "is a greater than b? {{ a > b ? 'yes' : 'no' }}";
// tokenize, parse, and build the evaluator
let tokens = Tokenizer::new(source, TokenizerOptions::default())
.tokenize()
.unwrap();
let nodes = Parser::new(tokens.as_slice()).parse().unwrap();
let mut evaluator_builder = EvaluatorBuilder::new(nodes.as_slice());
let evaluator = evaluator_builder.build_evaluator().unwrap();
// prepare the variables
let global_variables = HashMap::new();
let local_variables = vec![HashMap::from_iter(
[
("a".to_string(), Value::Number(2.0)),
("b".to_string(), Value::Number(1.0)),
]
.into_iter(),
)];
let functions = HashMap::new();
let builders = HashMap::<String, Evaluator>::new();
// create the context and evaluate
let mut context = EvaluationContext::new(
&global_variables,
local_variables,
&builders,
&functions,
Default::default(),
);
println!("{}", evaluator.evaluate(&mut context));
// the output will be: `is a greater than b? yes`Modules§
Traits§
- Evaluate
- Every evaluator should have function to evaluate itself with a context, a dependencies getter.
Functions§
- evaluate_
block - Evaluates a block in a context and returns the evaluated text.
- evaluate_
blocks - Calls evaluate_block in order and concatenates the output
- evaluate_
expression - Evaluates an expression in a context and returns its value.
- list_
dependencies_ block - Helper function to list all the dependencies a block references and add them to the dependencies.
- list_
dependencies_ expression - Helper function to list all the dependencies an expression references and add them to the dependencies.