pub enum Context<'a> {
Root {
functions: FunctionRegistry,
variables: HashMap<String, Value>,
},
Child {
parent: &'a Context<'a>,
variables: HashMap<String, Value>,
},
}
Expand description
Context is a collection of variables and functions that can be used by the interpreter to resolve expressions.
The context can be either a parent context, or a child context. A
parent context is created by default and contains all of the built-in
functions. A child context can be created by calling .clone()
. The
child context has it’s own variables (which can be added to), but it
will also reference the parent context. This allows for variables to
be overridden within the child context while still being able to
resolve variables in the child’s parents. You can have theoretically
have an infinite number of child contexts that reference each-other.
So why is this important? Well some CEL-macros such as the .map
macro
declare intermediate user-specified identifiers that should only be
available within the macro, and should not override variables in the
parent context. The .map
macro can clone the parent context, add the
intermediate identifier to the child context, and then evaluate the
map expression.
Intermediate variable stored in child context ↓ [1, 2, 3].map(x, x * 2) == [2, 4, 6] ↑ Only in scope for the duration of the map expression
Variants§
Implementations§
Source§impl Context<'_>
impl Context<'_>
pub fn add_variable<S, V>( &mut self, name: S, value: V, ) -> Result<(), <V as TryIntoValue>::Error>
pub fn add_variable_from_value<S, V>(&mut self, name: S, value: V)
pub fn get_variable<S>(&self, name: S) -> Result<Value, ExecutionError>
pub fn add_function<T: 'static, F>(&mut self, name: &str, value: F)
pub fn resolve(&self, expr: &Expression) -> Result<Value, ExecutionError>
pub fn resolve_all(&self, exprs: &[Expression]) -> Result<Value, ExecutionError>
pub fn new_inner_scope(&self) -> Context<'_>
Sourcepub fn empty() -> Self
pub fn empty() -> Self
Constructs a new empty context with no variables or functions.
If you’re looking for a context that has all the standard methods, functions
and macros already added to the context, use Context::default
instead.
§Example
use cel_interpreter::Context;
let mut context = Context::empty();
context.add_function("add", |a: i64, b: i64| a + b);