1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

//! A JEXL evaluator written in Rust
//! This crate depends on a JEXL parser crate that handles all the parsing
//! and is a part of the same workspace.
//! JEXL is an expression language used by Mozilla, you can find more information here: https://github.com/mozilla/mozjexl
//!
//! # How to use
//! The access point for this crate is the `eval` functions
//! You can use the `eval` function directly to evaluate standalone statements
//!
//! For example:
//! ```rust
//! use jexl_eval::eval;
//! assert_eq!(eval("'Hello ' + 'World'").unwrap(), "Hello World");
//! ```
//!
//! You can also run the statements against a context using the `eval_in_context` function
//! The context can be any type that implements the `serde::Serializable` trait
//! and the function will return errors if the statement doesn't match the context
//!
//! For example:
//! ```rust
//! use jexl_eval::eval_in_context;
//! use serde_json::json as value;
//! let context = value!({"a": {"b": 2.0}});
//! assert_eq!(eval_in_context("a.b", context).unwrap(), value!(2.0));
//! ```
//!

use jexl_parser::{
    ast::{Expression, OpCode},
    Parser,
};
use serde_json::{json as value, Value};

pub mod error;
use error::*;

const EPSILON: f64 = 0.000001f64;

trait Truthy {
    fn is_truthy(&self) -> bool;

    fn is_falsey(&self) -> bool {
        !self.is_truthy()
    }
}

impl Truthy for Value {
    fn is_truthy(&self) -> bool {
        match self {
            Value::Bool(b) => *b,
            Value::Null => true,
            Value::Number(f) => f.as_f64().unwrap() != 0.0,
            Value::String(s) => !s.is_empty(),
            // It would be better if these depended on the contents of the
            // object (empty array/object is falsey, non-empty is truthy, like
            // in Python) but this matches JS semantics. Is it worth changing?
            Value::Array(_) => true,
            Value::Object(_) => true,
        }
    }
}

type Context = Value;

pub fn eval(input: &str) -> Result<'_, Value> {
    let context = value!({});
    eval_in_context(input, &context)
}

pub fn eval_in_context<T: serde::Serialize>(input: &str, context: T) -> Result<'_, Value> {
    let tree = Parser::parse(input)?;
    let context = serde_json::to_value(context)?;
    if !context.is_object() {
        return Err(EvaluationError::InvalidContext);
    }
    eval_ast(tree, &context)
}

fn eval_ast<'a>(ast: Expression, context: &Context) -> Result<'a, Value> {
    match ast {
        Expression::Number(n) => Ok(value!(n)),
        Expression::Boolean(b) => Ok(value!(b)),
        Expression::String(s) => Ok(value!(s)),
        Expression::Array(xs) => xs.into_iter().map(|x| eval_ast(*x, context)).collect(),

        Expression::Object(items) => {
            let mut map = serde_json::Map::with_capacity(items.len());
            for (key, expr) in items.into_iter() {
                if map.contains_key(&key) {
                    return Err(EvaluationError::DuplicateObjectKey(key));
                }
                let value = eval_ast(*expr, context)?;
                map.insert(key, value);
            }
            Ok(Value::Object(map))
        }

        Expression::IdentifierSequence(exprs) => {
            assert!(!exprs.is_empty());
            let mut rv: Option<&Value> = Some(context);
            for expr in exprs.into_iter() {
                let key = eval_ast(*expr, context)?;
                if let Some(value) = rv {
                    rv = match key {
                        Value::String(s) => value.get(&s),
                        Value::Number(f) => value.get(f.as_f64().unwrap().floor() as usize),
                        _ => return Err(EvaluationError::InvalidIndexType),
                    };
                } else {
                    break;
                }
            }

            Ok(rv.unwrap_or(&value!(null)).clone())
        }

        Expression::BinaryOperation {
            left,
            right,
            operation,
        } => {
            let left = eval_ast(*left, context)?;
            let right = eval_ast(*right, context)?;
            match (operation, left, right) {
                (OpCode::And, a, b) => Ok(if a.is_truthy() { b } else { a }),
                (OpCode::Or, a, b) => Ok(if a.is_truthy() { a } else { b }),

                (op, Value::Number(a), Value::Number(b)) => {
                    let left = a.as_f64().unwrap();
                    let right = b.as_f64().unwrap();
                    Ok(match op {
                        OpCode::Add => value!(left + right),
                        OpCode::Subtract => value!(left - right),
                        OpCode::Multiply => value!(left * right),
                        OpCode::Divide => value!(left / right),
                        OpCode::FloorDivide => value!((left / right).floor()),
                        OpCode::Modulus => value!(left % right),
                        OpCode::Exponent => value!(left.powf(right)),
                        OpCode::Less => value!(left < right),
                        OpCode::Greater => value!(left > right),
                        OpCode::LessEqual => value!(left <= right),
                        OpCode::GreaterEqual => value!(left >= right),
                        OpCode::Equal => value!((left - right).abs() < EPSILON),
                        OpCode::NotEqual => value!((left - right).abs() > EPSILON),
                        OpCode::In => value!(false),
                        OpCode::And | OpCode::Or => {
                            unreachable!("Covered by previous case in parent match")
                        }
                    })
                }

                (OpCode::Add, Value::String(a), Value::String(b)) => {
                    Ok(value!(format!("{}{}", a, b)))
                }
                (OpCode::In, Value::String(a), Value::String(b)) => Ok(value!(b.contains(&a))),
                (OpCode::Equal, Value::String(a), Value::String(b)) => Ok(value!(a == b)),
                (operation, left, right) => Err(EvaluationError::InvalidBinaryOp {
                    operation,
                    left,
                    right,
                }),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json as value;

    #[test]
    fn test_literal() {
        assert_eq!(eval("1").unwrap(), value!(1.0));
    }

    #[test]
    fn test_binary_expression_addition() {
        assert_eq!(eval("1 + 2").unwrap(), value!(3.0));
    }

    #[test]
    fn test_binary_expression_multiplication() {
        assert_eq!(eval("2 * 3").unwrap(), value!(6.0));
    }

    #[test]
    fn test_precedence() {
        assert_eq!(eval("2 + 3 * 4").unwrap(), value!(14.0));
    }

    #[test]
    fn test_parenthesis() {
        assert_eq!(eval("(2 + 3) * 4").unwrap(), value!(20.0));
    }

    #[test]
    fn test_string_concat() {
        assert_eq!(eval("'Hello ' + 'World'").unwrap(), value!("Hello World"));
    }

    #[test]
    fn test_true_comparison() {
        assert_eq!(eval("2 > 1").unwrap(), value!(true));
    }

    #[test]
    fn test_false_comparison() {
        assert_eq!(eval("2 <= 1").unwrap(), value!(false));
    }

    #[test]
    fn test_boolean_logic() {
        assert_eq!(
            eval("'foo' && 6 >= 6 && 0 + 1 && true").unwrap(),
            value!(true)
        );
    }

    #[test]
    fn test_identifier() {
        let context = value!({"a": 1.0});
        assert_eq!(eval_in_context("a", context).unwrap(), value!(1.0));
    }

    #[test]
    fn test_identifier_chain() {
        let context = value!({"a": {"b": 2.0}});
        assert_eq!(eval_in_context("a.b", context).unwrap(), value!(2.0));
    }

    #[test]
    #[should_panic]
    fn test_context_filter_arrays() {
        let context = value!({
            "foo": {
                "bar": [
                    {"tek": "hello"},
                    {"tek": "baz"},
                    {"tok": "baz"},
                ]
            }
        });
        assert_eq!(
            eval_in_context("foo.bar[.tek == 'baz']", &context).unwrap(),
            value!([{"tek": "baz"}])
        );
    }

    #[test]
    fn test_context_array_index() {
        let context = value!({
            "foo": {
                "bar": [
                    {"tek": "hello"},
                    {"tek": "baz"},
                    {"tok": "baz"},
                ]
            }
        });
        assert_eq!(
            eval_in_context("foo.bar[1].tek", context).unwrap(),
            value!("baz")
        );
    }

    #[test]
    #[should_panic]
    fn test_object_expression_properties() {
        let context = value!({"foo": {"baz": {"bar": "tek"}}});
        assert_eq!(
            eval_in_context("foo['ba' + 'z']", &context).unwrap(),
            value!("tek")
        );
    }

    #[test]
    #[should_panic]
    fn test_missing_transform_exception() {
        let err = eval("'hello'|world").unwrap_err();
        if let EvaluationError::UnknownTransform(transform) = err {
            assert_eq!(transform, "world")
        } else {
            panic!("Should have thrown an unknown transform error")
        }
    }

    #[test]
    fn test_divfloor() {
        assert_eq!(eval("7 // 2").unwrap(), value!(3.0));
    }

    #[test]
    fn test_empty_object_literal() {
        assert_eq!(eval("{}").unwrap(), value!({}));
    }

    #[test]
    fn test_object_literal_strings() {
        assert_eq!(
            eval("{'foo': {'bar': 'tek'}}").unwrap(),
            value!({"foo": {"bar": "tek"}})
        );
    }

    #[test]
    #[should_panic]
    fn test_object_literal_identifiers() {
        assert_eq!(
            eval("{foo: {bar: 'tek'}}").unwrap(),
            value!({"foo": {"bar": "tek"}})
        );
    }

    /*
    // TODO needs transforms

    def test_transforms():
        config = JEXLConfig(
            {'half': lambda x: x / 2},
            default_binary_operators,
            default_unary_operators
        )
        evaluator = Evaluator(config)
        result = evaluate(tree('foo|half + 3'), {'foo': 10})
        assert result == 8

    def test_transforms_multiple_arguments():
        config = JEXLConfig(
            binary_operators=default_binary_operators,
            unary_operators=default_unary_operators,
            transforms={
                'concat': lambda val, a1, a2, a3: val + ': ' + a1 + a2 + a3,
            }
        )
        evaluator = Evaluator(config)
        result = evaluate(tree('"foo"|concat("baz", "bar", "tek")'))
        assert result == 'foo: bazbartek'

    */

    #[test]
    #[should_panic]
    fn test_object_literal_properties() {
        assert_eq!(eval("{foo: 'bar'}.foo").unwrap(), value!("bar"));
    }

    #[test]
    fn test_array_literal() {
        assert_eq!(eval("['foo', 1+2]").unwrap(), value!(["foo", 3.0]));
    }

    #[test]
    #[should_panic]
    fn test_array_literal_indexing() {
        assert_eq!(eval("[1, 2, 3][1]").unwrap(), value!(2.0));
    }

    #[test]
    fn test_in_operator_string() {
        assert_eq!(eval("'bar' in 'foobartek'").unwrap(), value!(true));
        assert_eq!(eval("'baz' in 'foobartek'").unwrap(), value!(false));
    }

    #[test]
    #[should_panic]
    fn test_in_operator_array() {
        assert_eq!(
            eval("'bar' in ['foo', 'bar', 'tek']").unwrap(),
            value!(true)
        );
        assert_eq!(
            eval("'baz' in ['foo', 'bar', 'tek']").unwrap(),
            value!(false)
        );
    }

    #[test]
    #[should_panic]
    fn test_conditional_expression() {
        assert_eq!(eval("'foo' ? 1 : 2").unwrap(), value!(1));
        assert_eq!(eval("'' ? 1 : 2").unwrap(), value!(2));
    }

    #[test]
    fn test_arbitrary_whitespace() {
        assert_eq!(eval("(\t2\n+\n3) *\n4\n\r\n").unwrap(), value!(20.0));
    }

    #[test]
    fn test_non_integer() {
        assert_eq!(eval("1.5 * 3.0").unwrap(), value!(4.5));
    }

    #[test]
    fn test_string_literal() {
        assert_eq!(eval("'hello world'").unwrap(), value!("hello world"));
        assert_eq!(eval("\"hello world\"").unwrap(), value!("hello world"));
    }

    #[test]
    fn test_string_escapes() {
        assert_eq!(eval("'a\\'b'").unwrap(), value!("a'b"));
        assert_eq!(eval("\"a\\\"b\"").unwrap(), value!("a\"b"));
    }
}