jetro-core 0.5.8

jetro-core: parser, compiler, and VM for the Jetro JSON query language
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
//! Shared planning helpers for functional batched updates.
//!
//! The parser owns syntax recognition. This module owns update-specific
//! semantic adapters that planner/compiler/executor code can share while the
//! first-class `UpdateBatch` path is being brought online.

use crate::parse::ast::{Expr, PatchOp, PathStep, Step};

/// Synthetic binding used to evaluate relative update expressions against the
/// selected value snapshot.
pub(crate) const UPDATE_FOCUS_BINDING: &str = "__update_focus";

/// Lightweight dependency summary for a functional update batch.
#[derive(Debug, Clone, Copy, Default, Eq, PartialEq)]
pub(crate) struct UpdateDependencySummary {
    /// At least one selector, guard, dynamic index, or RHS reads `$`.
    pub(crate) reads_root: bool,
    /// At least one selected-object RHS or guard reads the original selected
    /// value snapshot through the synthetic update focus binding.
    pub(crate) reads_focus: bool,
    /// At least one guard, dynamic index, or RHS reads `@`.
    pub(crate) reads_current: bool,
    /// At least one expression depends on a runtime path step.
    pub(crate) has_dynamic_path: bool,
    /// At least one op has a guard.
    pub(crate) has_guards: bool,
}

/// Planner-visible trie for static update paths.
#[derive(Debug, Clone, Default, Eq, PartialEq)]
pub(crate) struct UpdateTriePlan {
    pub(crate) root: UpdateTrieNode,
    pub(crate) op_count: usize,
    pub(crate) static_prefixes_only: bool,
    pub(crate) has_prefix_overlap: bool,
}

/// A node in the planner update trie.
#[derive(Debug, Clone, Default, Eq, PartialEq)]
pub(crate) struct UpdateTrieNode {
    pub(crate) ops_here: Vec<usize>,
    pub(crate) fields: Vec<(String, UpdateTrieNode)>,
    pub(crate) indices: Vec<(i64, UpdateTrieNode)>,
}

/// Collects coarse dependencies used by update planning and safety tests.
pub(crate) fn analyze_update_batch(
    root: &Expr,
    selector: &[PathStep],
    ops: &[PatchOp],
) -> UpdateDependencySummary {
    let mut out = UpdateDependencySummary::default();
    collect_update_root(root, &mut out);
    collect_path(selector, &mut out);
    for op in ops {
        collect_path(&op.path, &mut out);
        collect_expr(&op.val, &mut out);
        if let Some(cond) = &op.cond {
            out.has_guards = true;
            collect_expr(cond, &mut out);
        }
    }
    out
}

/// Builds a source-order trie for relative update ops. Dynamic, wildcard, and
/// descendant steps stay executor-correct but are marked non-static so the
/// planner does not assume a single deterministic child prefix.
pub(crate) fn build_update_trie_plan(ops: &[PatchOp]) -> UpdateTriePlan {
    let mut out = UpdateTriePlan {
        root: UpdateTrieNode::default(),
        op_count: ops.len(),
        static_prefixes_only: true,
        has_prefix_overlap: false,
    };
    for (op_idx, op) in ops.iter().enumerate() {
        if !insert_static_path(&mut out.root, &op.path, 0, op_idx) {
            out.static_prefixes_only = false;
        }
    }
    out.has_prefix_overlap = !out.static_prefixes_only || trie_has_prefix_overlap(&out.root, false);
    out
}

fn insert_static_path(
    node: &mut UpdateTrieNode,
    path: &[PathStep],
    i: usize,
    op_idx: usize,
) -> bool {
    if i == path.len() {
        node.ops_here.push(op_idx);
        return true;
    }
    match &path[i] {
        PathStep::Field(name) => {
            let child = trie_field_child(node, name);
            insert_static_path(child, path, i + 1, op_idx)
        }
        PathStep::Index(idx) => {
            let child = trie_index_child(node, *idx);
            insert_static_path(child, path, i + 1, op_idx)
        }
        PathStep::DynIndex(_)
        | PathStep::Wildcard
        | PathStep::WildcardFilter(_)
        | PathStep::Descendant(_) => {
            node.ops_here.push(op_idx);
            false
        }
    }
}

fn trie_field_child<'a>(node: &'a mut UpdateTrieNode, name: &str) -> &'a mut UpdateTrieNode {
    if let Some(pos) = node.fields.iter().position(|(field, _)| field == name) {
        return &mut node.fields[pos].1;
    }
    node.fields
        .push((name.to_string(), UpdateTrieNode::default()));
    &mut node.fields.last_mut().unwrap().1
}

fn trie_index_child(node: &mut UpdateTrieNode, idx: i64) -> &mut UpdateTrieNode {
    if let Some(pos) = node.indices.iter().position(|(index, _)| *index == idx) {
        return &mut node.indices[pos].1;
    }
    node.indices.push((idx, UpdateTrieNode::default()));
    &mut node.indices.last_mut().unwrap().1
}

fn trie_has_prefix_overlap(node: &UpdateTrieNode, ancestor_has_op: bool) -> bool {
    if ancestor_has_op
        && (!node.ops_here.is_empty() || !node.fields.is_empty() || !node.indices.is_empty())
    {
        return true;
    }
    let here_has_op = ancestor_has_op || !node.ops_here.is_empty();
    node.fields
        .iter()
        .any(|(_, child)| trie_has_prefix_overlap(child, here_has_op))
        || node
            .indices
            .iter()
            .any(|(_, child)| trie_has_prefix_overlap(child, here_has_op))
}

fn collect_path(path: &[PathStep], out: &mut UpdateDependencySummary) {
    for step in path {
        match step {
            PathStep::DynIndex(expr) => {
                out.has_dynamic_path = true;
                collect_expr(expr, out);
            }
            PathStep::WildcardFilter(expr) => {
                out.has_dynamic_path = true;
                collect_expr(expr, out);
            }
            PathStep::Field(_)
            | PathStep::Index(_)
            | PathStep::Wildcard
            | PathStep::Descendant(_) => {}
        }
    }
}

fn collect_update_root(root: &Expr, out: &mut UpdateDependencySummary) {
    if !matches!(root, Expr::Root) {
        collect_expr(root, out);
    }
}

fn collect_expr(expr: &Expr, out: &mut UpdateDependencySummary) {
    match expr {
        Expr::Root => out.reads_root = true,
        Expr::Current => out.reads_current = true,
        Expr::Ident(name) if name == UPDATE_FOCUS_BINDING => out.reads_focus = true,
        Expr::Chain(base, steps) => {
            collect_expr(base, out);
            for step in steps {
                collect_step(step, out);
            }
        }
        Expr::BinOp(lhs, _, rhs) | Expr::Coalesce(lhs, rhs) => {
            collect_expr(lhs, out);
            collect_expr(rhs, out);
        }
        Expr::UnaryNeg(inner)
        | Expr::Not(inner)
        | Expr::Kind { expr: inner, .. }
        | Expr::Cast { expr: inner, .. } => collect_expr(inner, out),
        Expr::Object(fields) => {
            for field in fields {
                match field {
                    crate::parse::ast::ObjField::Kv { val, cond, .. } => {
                        collect_expr(val, out);
                        if let Some(cond) = cond {
                            collect_expr(cond, out);
                        }
                    }
                    crate::parse::ast::ObjField::Dynamic { key, val } => {
                        collect_expr(key, out);
                        collect_expr(val, out);
                    }
                    crate::parse::ast::ObjField::Spread(expr)
                    | crate::parse::ast::ObjField::SpreadDeep(expr) => collect_expr(expr, out),
                    crate::parse::ast::ObjField::Short(_) => {}
                }
            }
        }
        Expr::Array(items) => {
            for item in items {
                match item {
                    crate::parse::ast::ArrayElem::Expr(expr)
                    | crate::parse::ast::ArrayElem::Spread(expr) => collect_expr(expr, out),
                }
            }
        }
        Expr::Pipeline { base, steps } => {
            collect_expr(base, out);
            for step in steps {
                if let crate::parse::ast::PipeStep::Forward(expr) = step {
                    collect_expr(expr, out);
                }
            }
        }
        Expr::ListComp {
            expr, iter, cond, ..
        }
        | Expr::SetComp {
            expr, iter, cond, ..
        }
        | Expr::GenComp {
            expr, iter, cond, ..
        } => {
            collect_expr(iter, out);
            collect_expr(expr, out);
            if let Some(cond) = cond {
                collect_expr(cond, out);
            }
        }
        Expr::DictComp {
            key,
            val,
            iter,
            cond,
            ..
        } => {
            collect_expr(iter, out);
            collect_expr(key, out);
            collect_expr(val, out);
            if let Some(cond) = cond {
                collect_expr(cond, out);
            }
        }
        Expr::Lambda { body, .. } => collect_expr(body, out),
        Expr::Let { init, body, .. } => {
            collect_expr(init, out);
            collect_expr(body, out);
        }
        Expr::IfElse { cond, then_, else_ } => {
            collect_expr(cond, out);
            collect_expr(then_, out);
            collect_expr(else_, out);
        }
        Expr::Try { body, default } => {
            collect_expr(body, out);
            collect_expr(default, out);
        }
        Expr::GlobalCall { args, .. } => {
            for arg in args {
                match arg {
                    crate::parse::ast::Arg::Pos(expr) | crate::parse::ast::Arg::Named(_, expr) => {
                        collect_expr(expr, out)
                    }
                }
            }
        }
        Expr::Patch { root, ops } => {
            collect_update_root(root, out);
            for op in ops {
                collect_path(&op.path, out);
                collect_expr(&op.val, out);
                if let Some(cond) = &op.cond {
                    collect_expr(cond, out);
                }
            }
        }
        Expr::UpdateBatch {
            root,
            selector,
            ops,
        } => {
            collect_update_root(root, out);
            collect_path(selector, out);
            for op in ops {
                collect_path(&op.path, out);
                collect_expr(&op.val, out);
                if let Some(cond) = &op.cond {
                    collect_expr(cond, out);
                }
            }
        }
        Expr::FString(parts) => {
            for part in parts {
                if let crate::parse::ast::FStringPart::Interp { expr, .. } = part {
                    collect_expr(expr, out);
                }
            }
        }
        Expr::Match { scrutinee, arms } => {
            collect_expr(scrutinee, out);
            for arm in arms {
                if let Some(guard) = &arm.guard {
                    collect_expr(guard, out);
                }
                collect_expr(&arm.body, out);
            }
        }
        Expr::Null
        | Expr::Bool(_)
        | Expr::Int(_)
        | Expr::Float(_)
        | Expr::Str(_)
        | Expr::DeleteMark => {}
        Expr::Ident(_) => {}
    }
}

fn collect_step(step: &Step, out: &mut UpdateDependencySummary) {
    match step {
        Step::DynIndex(expr) | Step::InlineFilter(expr) => collect_expr(expr, out),
        Step::Method(_, args) | Step::OptMethod(_, args) => {
            for arg in args {
                match arg {
                    crate::parse::ast::Arg::Pos(expr) | crate::parse::ast::Arg::Named(_, expr) => {
                        collect_expr(expr, out)
                    }
                }
            }
        }
        Step::DeepMatch { arms, .. } => {
            for arm in arms {
                if let Some(guard) = &arm.guard {
                    collect_expr(guard, out);
                }
                collect_expr(&arm.body, out);
            }
        }
        Step::Field(_)
        | Step::OptField(_)
        | Step::Descendant(_)
        | Step::DescendAll
        | Step::Index(_)
        | Step::Slice(_, _, _)
        | Step::Wildcard
        | Step::Quantifier(_) => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::parse::ast::{Arg, BinOp};

    #[test]
    fn dependency_summary_tracks_roots_current_dynamic_paths_and_guards() {
        let selector = vec![
            PathStep::Field("books".to_string()),
            PathStep::WildcardFilter(Box::new(Expr::BinOp(
                Box::new(Expr::Chain(
                    Box::new(Expr::Root),
                    vec![Step::Field("cutoff".to_string())],
                )),
                BinOp::Gt,
                Box::new(Expr::Int(0)),
            ))),
        ];
        let ops = vec![PatchOp {
            path: vec![PathStep::Field("tags".to_string())],
            val: Expr::Chain(
                Box::new(Expr::Current),
                vec![Step::Method(
                    "append".to_string(),
                    vec![Arg::Pos(Expr::Chain(
                        Box::new(Expr::Root),
                        vec![Step::Field("suffix".to_string())],
                    ))],
                )],
            ),
            cond: Some(Expr::BinOp(
                Box::new(Expr::Ident("year".to_string())),
                BinOp::Gt,
                Box::new(Expr::Int(1980)),
            )),
        }];

        let summary = analyze_update_batch(&Expr::Root, &selector, &ops);

        assert!(summary.reads_root);
        assert!(summary.reads_current);
        assert!(!summary.reads_focus);
        assert!(summary.has_dynamic_path);
        assert!(summary.has_guards);
    }

    #[test]
    fn dependency_summary_tracks_selected_focus_reads() {
        let selector = vec![PathStep::Field("books".to_string()), PathStep::Wildcard];
        let focus_read = Expr::Chain(
            Box::new(Expr::Ident(UPDATE_FOCUS_BINDING.to_string())),
            vec![Step::Field("tags".to_string())],
        );
        let ops = vec![PatchOp {
            path: vec![PathStep::Field("tags".to_string())],
            val: focus_read,
            cond: None,
        }];

        let summary = analyze_update_batch(&Expr::Root, &selector, &ops);

        assert!(summary.reads_focus);
        assert!(!summary.reads_current);
        assert!(!summary.reads_root);
    }

    #[test]
    fn dependency_summary_stays_empty_for_static_relative_updates() {
        let selector = vec![PathStep::Field("books".to_string()), PathStep::Wildcard];
        let ops = vec![PatchOp {
            path: vec![PathStep::Field("reviewed".to_string())],
            val: Expr::Bool(true),
            cond: None,
        }];

        let summary = analyze_update_batch(&Expr::Root, &selector, &ops);

        assert_eq!(summary, UpdateDependencySummary::default());
    }

    #[test]
    fn update_trie_groups_shared_static_prefixes() {
        let ops = vec![
            PatchOp {
                path: vec![
                    PathStep::Field("meta".to_string()),
                    PathStep::Field("score".to_string()),
                ],
                val: Expr::Int(1),
                cond: None,
            },
            PatchOp {
                path: vec![
                    PathStep::Field("meta".to_string()),
                    PathStep::Field("reviewed".to_string()),
                ],
                val: Expr::Bool(true),
                cond: None,
            },
        ];

        let trie = build_update_trie_plan(&ops);

        assert!(trie.static_prefixes_only);
        assert!(!trie.has_prefix_overlap);
        assert_eq!(trie.op_count, 2);
        assert_eq!(trie.root.fields.len(), 1);
        assert_eq!(trie.root.fields[0].0, "meta");
        assert_eq!(trie.root.fields[0].1.fields.len(), 2);
    }

    #[test]
    fn update_trie_marks_dynamic_and_prefix_overlap() {
        let ops = vec![
            PatchOp {
                path: vec![PathStep::Field("meta".to_string())],
                val: Expr::Object(Vec::new()),
                cond: None,
            },
            PatchOp {
                path: vec![
                    PathStep::Field("meta".to_string()),
                    PathStep::DynIndex(Expr::Ident("k".to_string())),
                ],
                val: Expr::Bool(true),
                cond: None,
            },
        ];

        let trie = build_update_trie_plan(&ops);

        assert!(!trie.static_prefixes_only);
        assert!(trie.has_prefix_overlap);
    }
}