jpx-core 0.3.0

Complete JMESPath implementation with 490+ extension functions
Documentation
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! Interprets JMESPath expressions.

#[cfg(feature = "let-expr")]
use std::collections::HashMap;

use serde_json::Value;

use crate::Context;
use crate::ast::Ast;
use crate::value_ext::ValueExt;
use crate::{ErrorReason, JmespathError, RuntimeError, make_expref_sentinel};

/// Result of searching data using a JMESPath Expression.
pub type SearchResult = Result<Value, JmespathError>;

/// Maximum interpreter recursion depth.
///
/// Bounds evaluation nesting so that a deeply nested AST (e.g. a long
/// left-associative `a.a.a...` chain, which the parser builds without deep
/// recursion of its own) cannot overflow the stack and abort the process.
///
/// Chosen to stay safe even when the interpreter runs on a ~2 MiB stack (the
/// default for tokio worker threads and the Rust test harness), where each
/// recursive frame is large in debug builds. Still far above any realistic
/// expression, whose AST nesting is in the low tens.
const MAX_EVAL_DEPTH: usize = 128;

/// Interprets the given data using an AST node.
///
/// Thin wrapper that bounds recursion depth via `Context::eval_depth`;
/// the actual interpretation happens in `interpret_inner`.
pub fn interpret(data: &Value, node: &Ast, ctx: &mut Context<'_>) -> SearchResult {
    ctx.eval_depth += 1;
    if ctx.eval_depth > MAX_EVAL_DEPTH {
        ctx.eval_depth -= 1;
        let reason = ErrorReason::Runtime(RuntimeError::RecursionLimitExceeded {
            limit: MAX_EVAL_DEPTH,
        });
        return Err(JmespathError::from_ctx(ctx, reason));
    }
    let result = interpret_inner(data, node, ctx);
    ctx.eval_depth -= 1;
    result
}

fn interpret_inner(data: &Value, node: &Ast, ctx: &mut Context<'_>) -> SearchResult {
    match node {
        Ast::Field { name, .. } => Ok(data.get_field(name)),
        Ast::Subexpr { lhs, rhs, .. } => {
            let left_result = interpret(data, lhs, ctx)?;
            interpret(&left_result, rhs, ctx)
        }
        Ast::Identity { .. } => Ok(data.clone()),
        Ast::Literal { value, .. } => Ok(value.clone()),
        Ast::Index { idx, .. } => {
            if *idx >= 0 {
                Ok(data.get_index(*idx as usize))
            } else {
                Ok(data.get_negative_index((-idx) as usize))
            }
        }
        Ast::Or { lhs, rhs, .. } => {
            let left = interpret(data, lhs, ctx)?;
            if left.is_truthy() {
                Ok(left)
            } else {
                interpret(data, rhs, ctx)
            }
        }
        Ast::And { lhs, rhs, .. } => {
            let left = interpret(data, lhs, ctx)?;
            if !left.is_truthy() {
                Ok(left)
            } else {
                interpret(data, rhs, ctx)
            }
        }
        Ast::Not { node, .. } => {
            let result = interpret(data, node, ctx)?;
            Ok(Value::Bool(!result.is_truthy()))
        }
        Ast::Condition {
            predicate, then, ..
        } => {
            let cond_result = interpret(data, predicate, ctx)?;
            if cond_result.is_truthy() {
                interpret(data, then, ctx)
            } else {
                Ok(Value::Null)
            }
        }
        Ast::Comparison {
            comparator,
            lhs,
            rhs,
            ..
        } => {
            let left = interpret(data, lhs, ctx)?;
            let right = interpret(data, rhs, ctx)?;
            Ok(left
                .compare(comparator, &right)
                .map_or(Value::Null, Value::Bool))
        }
        Ast::ObjectValues { node, .. } => {
            let subject = interpret(data, node, ctx)?;
            match subject {
                Value::Object(map) => Ok(Value::Array(map.into_values().collect())),
                _ => Ok(Value::Null),
            }
        }
        Ast::Projection { lhs, rhs, .. } => {
            let left = interpret(data, lhs, ctx)?;
            match left.as_array() {
                None => Ok(Value::Null),
                Some(arr) => {
                    let mut collected = vec![];
                    for element in arr {
                        let current = interpret(element, rhs, ctx)?;
                        if !current.is_null() {
                            collected.push(current);
                        }
                    }
                    Ok(Value::Array(collected))
                }
            }
        }
        Ast::Flatten { node, .. } => {
            let result = interpret(data, node, ctx)?;
            match result.as_array() {
                None => Ok(Value::Null),
                Some(arr) => {
                    let mut collected: Vec<Value> = vec![];
                    for element in arr {
                        match element.as_array() {
                            Some(inner) => collected.extend(inner.iter().cloned()),
                            _ => collected.push(element.clone()),
                        }
                    }
                    Ok(Value::Array(collected))
                }
            }
        }
        Ast::MultiList { elements, .. } => {
            if data.is_null() {
                Ok(Value::Null)
            } else {
                let mut collected = vec![];
                for node in elements {
                    collected.push(interpret(data, node, ctx)?);
                }
                Ok(Value::Array(collected))
            }
        }
        Ast::MultiHash { elements, .. } => {
            if data.is_null() {
                Ok(Value::Null)
            } else {
                let mut collected = serde_json::Map::new();
                for kvp in elements {
                    let value = interpret(data, &kvp.value, ctx)?;
                    collected.insert(kvp.key.clone(), value);
                }
                Ok(Value::Object(collected))
            }
        }
        Ast::Function { name, args, offset } => {
            let mut fn_args: Vec<Value> = vec![];
            for arg in args {
                fn_args.push(interpret(data, arg, ctx)?);
            }
            ctx.offset = *offset;
            match ctx.runtime.get_function(name) {
                Some(f) => f.evaluate(&fn_args, ctx),
                None => {
                    let reason =
                        ErrorReason::Runtime(RuntimeError::UnknownFunction(name.to_owned()));
                    Err(JmespathError::from_ctx(ctx, reason))
                }
            }
        }
        Ast::Expref { ast, .. } => {
            let id = ctx.store_expref(*ast.clone());
            Ok(make_expref_sentinel(id))
        }
        Ast::Slice {
            start,
            stop,
            step,
            offset,
        } => {
            if *step == 0 {
                ctx.offset = *offset;
                let reason = ErrorReason::Runtime(RuntimeError::InvalidSlice);
                Err(JmespathError::from_ctx(ctx, reason))
            } else {
                match data.slice(*start, *stop, *step) {
                    Some(array) => Ok(Value::Array(array)),
                    None => Ok(Value::Null),
                }
            }
        }
        #[cfg(feature = "let-expr")]
        Ast::VariableRef { name, offset } => match ctx.get_variable(name) {
            Some(value) => Ok(value),
            None => {
                ctx.offset = *offset;
                let reason = ErrorReason::Runtime(RuntimeError::UnknownFunction(format!(
                    "Undefined variable: ${name}"
                )));
                Err(JmespathError::from_ctx(ctx, reason))
            }
        },
        #[cfg(feature = "let-expr")]
        Ast::Let { bindings, expr, .. } => {
            let mut scope = HashMap::new();
            for (name, binding_expr) in bindings {
                let value = interpret(data, binding_expr, ctx)?;
                scope.insert(name.clone(), value);
            }
            ctx.push_scope(scope);
            let result = interpret(data, expr, ctx);
            ctx.pop_scope();
            result
        }
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use crate::Runtime;

    fn search(expr: &str, data: &serde_json::Value) -> serde_json::Value {
        let rt = Runtime::strict();
        let compiled = rt.compile(expr).unwrap();
        compiled.search(data).unwrap()
    }

    fn search_err(expr: &str, data: &serde_json::Value) -> crate::JmespathError {
        let rt = Runtime::strict();
        let compiled = rt.compile(expr).unwrap();
        compiled.search(data).unwrap_err()
    }

    #[test]
    fn null_propagation_field() {
        assert_eq!(search("foo", &json!(null)), json!(null));
        assert_eq!(search("foo.bar", &json!({"foo": null})), json!(null));
    }

    #[test]
    fn null_propagation_index() {
        assert_eq!(search("[0]", &json!(null)), json!(null));
    }

    #[test]
    fn null_propagation_projection() {
        assert_eq!(search("[*].foo", &json!(null)), json!(null));
    }

    #[test]
    fn projection_filters_null() {
        let data = json!([{"foo": "a"}, {"bar": "b"}, {"foo": "c"}]);
        assert_eq!(search("[*].foo", &data), json!(["a", "c"]));
    }

    #[test]
    fn wildcard_on_non_object() {
        assert_eq!(search("*", &json!("string")), json!(null));
        assert_eq!(search("*", &json!(42)), json!(null));
    }

    #[test]
    fn wildcard_on_object() {
        let result = search("*", &json!({"a": 1, "b": 2}));
        let arr = result.as_array().unwrap();
        assert_eq!(arr.len(), 2);
        assert!(arr.contains(&json!(1)));
        assert!(arr.contains(&json!(2)));
    }

    #[test]
    fn cross_type_equality_returns_false() {
        // jpx-core returns false for cross-type comparisons (not null)
        assert_eq!(search("`1` == `\"1\"`", &json!(null)), json!(false));
        assert_eq!(search("`1` == `true`", &json!(null)), json!(false));
    }

    #[test]
    fn same_type_equality() {
        assert_eq!(search("`1` == `1`", &json!(null)), json!(true));
        assert_eq!(search("`1` == `2`", &json!(null)), json!(false));
        assert_eq!(
            search("`\"hello\"` == `\"hello\"`", &json!(null)),
            json!(true)
        );
    }

    #[test]
    fn flatten_semantics() {
        let data = json!([[1, 2], [3, 4], [5]]);
        assert_eq!(search("[]", &data), json!([1, 2, 3, 4, 5]));
    }

    #[test]
    fn flatten_mixed() {
        let data = json!([[1, 2], 3, [4]]);
        assert_eq!(search("[]", &data), json!([1, 2, 3, 4]));
    }

    #[test]
    fn flatten_on_non_array() {
        assert_eq!(search("[]", &json!("string")), json!(null));
    }

    #[test]
    fn pipe_stops_projection() {
        let data = json!({
            "people": [
                {"name": "a", "age": 20},
                {"name": "b", "age": 25},
                {"name": "c", "age": 30}
            ]
        });
        assert_eq!(search("people[*].name | [0]", &data), json!("a"));
    }

    #[test]
    fn or_semantics() {
        assert_eq!(search("a || b", &json!({"a": 1, "b": 2})), json!(1));
        assert_eq!(search("a || b", &json!({"b": 2})), json!(2));
        assert_eq!(search("a || b", &json!({})), json!(null));
    }

    #[test]
    fn and_semantics() {
        assert_eq!(search("a && b", &json!({"a": 1, "b": 2})), json!(2));
        assert_eq!(search("a && b", &json!({"b": 2})), json!(null));
    }

    #[test]
    fn not_semantics() {
        assert_eq!(search("!`true`", &json!(null)), json!(false));
        assert_eq!(search("!`false`", &json!(null)), json!(true));
        assert_eq!(search("!`null`", &json!(null)), json!(true));
        assert_eq!(search("!`\"\"`", &json!(null)), json!(true));
        assert_eq!(search("!`\"hello\"`", &json!(null)), json!(false));
    }

    #[test]
    fn slice_step_zero_error() {
        let err = search_err("[::0]", &json!([1, 2, 3]));
        let display = format!("{err}");
        assert!(display.contains("Invalid slice"));
    }

    #[test]
    fn unknown_function_error() {
        let err = search_err("nonexistent(@)", &json!(null));
        let display = format!("{err}");
        assert!(display.contains("Unknown function"));
    }

    #[test]
    fn multilist_on_null() {
        assert_eq!(search("[a, b]", &json!(null)), json!(null));
    }

    #[test]
    fn multihash_on_null() {
        assert_eq!(search("{x: a, y: b}", &json!(null)), json!(null));
    }

    #[test]
    fn multilist_on_data() {
        assert_eq!(search("[a, b]", &json!({"a": 1, "b": 2})), json!([1, 2]));
    }

    #[test]
    fn multihash_on_data() {
        assert_eq!(
            search("{x: a, y: b}", &json!({"a": 1, "b": 2})),
            json!({"x": 1, "y": 2})
        );
    }

    #[test]
    fn comparison_operators() {
        assert_eq!(search("`5` > `3`", &json!(null)), json!(true));
        assert_eq!(search("`5` < `3`", &json!(null)), json!(false));
        assert_eq!(search("`5` >= `5`", &json!(null)), json!(true));
        assert_eq!(search("`5` <= `5`", &json!(null)), json!(true));
        assert_eq!(search("`5` != `3`", &json!(null)), json!(true));
    }

    #[test]
    fn literal_passthrough() {
        assert_eq!(search("`42`", &json!(null)), json!(42));
        assert_eq!(search("`\"hello\"`", &json!(null)), json!("hello"));
        assert_eq!(search("`true`", &json!(null)), json!(true));
        assert_eq!(search("`null`", &json!(null)), json!(null));
    }

    #[test]
    fn identity() {
        assert_eq!(search("@", &json!(42)), json!(42));
        assert_eq!(search("@", &json!("hello")), json!("hello"));
    }

    #[test]
    fn filter_expression() {
        let data = json!([1, 2, 3, 4, 5]);
        assert_eq!(search("[? @ > `3`]", &data), json!([4, 5]));
    }

    #[test]
    fn builtin_function_length() {
        assert_eq!(search("length(@)", &json!([1, 2, 3])), json!(3));
        assert_eq!(search("length(@)", &json!("hello")), json!(5));
    }

    #[test]
    fn builtin_function_sort() {
        assert_eq!(search("sort(@)", &json!([3, 1, 2])), json!([1, 2, 3]));
    }

    #[test]
    fn deep_ast_eval_errors_gracefully() {
        // The parser rejects deeply nested input, so build a deep AST directly
        // to exercise the interpreter's own defense-in-depth guard (which also
        // protects API callers that construct an AST themselves). Run on a
        // 2 MiB stack (a typical async worker-thread size): if the guard were
        // too lax this thread would abort the whole test process instead of
        // returning an error.
        use crate::Runtime;
        use crate::ast::Ast;
        let msg = std::thread::Builder::new()
            .stack_size(2 * 1024 * 1024)
            .spawn(|| {
                let mut ast = Ast::Identity { offset: 0 };
                for _ in 0..400 {
                    ast = Ast::Subexpr {
                        offset: 0,
                        lhs: Box::new(ast),
                        rhs: Box::new(Ast::Identity { offset: 0 }),
                    };
                }
                let rt = Runtime::strict();
                let expr = crate::Expression::new("<deep>", ast, &rt);
                format!("{}", expr.search(&json!({})).unwrap_err())
            })
            .unwrap()
            .join()
            .expect("deep evaluation must not overflow the stack");
        assert!(msg.contains("Recursion limit"), "unexpected message: {msg}");
    }

    #[test]
    fn moderate_ast_eval_ok() {
        // Well within the depth limit: evaluates normally (null on empty object).
        let expr = format!("a{}", ".a".repeat(50));
        assert_eq!(search(&expr, &json!({})), json!(null));
    }
}