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