zen_expression/
exports.rs

1use crate::expression::{Standard, Unary};
2use crate::variable::Variable;
3use crate::{Expression, Isolate, IsolateError};
4
5/// Evaluates a standard expression
6pub fn evaluate_expression(expression: &str, context: Variable) -> Result<Variable, IsolateError> {
7    Isolate::with_environment(context).run_standard(expression)
8}
9
10/// Evaluates a unary expression; Required: context must be an object with "$" key.
11pub fn evaluate_unary_expression(
12    expression: &str,
13    context: Variable,
14) -> Result<bool, IsolateError> {
15    let Some(context_object_ref) = context.as_object() else {
16        return Err(IsolateError::MissingContextReference);
17    };
18
19    let context_object = context_object_ref.borrow();
20    if !context_object.contains_key("$") {
21        return Err(IsolateError::MissingContextReference);
22    }
23
24    Isolate::with_environment(context).run_unary(expression)
25}
26
27/// Compiles a standard expression
28pub fn compile_expression(expression: &str) -> Result<Expression<Standard>, IsolateError> {
29    Isolate::new().compile_standard(expression)
30}
31
32/// Compiles an unary expression
33pub fn compile_unary_expression(expression: &str) -> Result<Expression<Unary>, IsolateError> {
34    Isolate::new().compile_unary(expression)
35}
36
37#[cfg(test)]
38mod test {
39    use crate::evaluate_expression;
40    use serde_json::json;
41
42    #[test]
43    fn example() {
44        let context = json!({ "tax": { "percentage": 10 } });
45        let tax_amount = evaluate_expression("50 * tax.percentage / 100", context.into()).unwrap();
46
47        assert_eq!(tax_amount, json!(5).into());
48    }
49}