oqx 0.20.0

OQX (omgbase Query eXpressions): a composable query language and engine for JSON-shaped collections — Rust implementation
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
//! Generic traversal over the AST (`spec/oqx/AST.md` §5; port of
//! `packages/oqx/src/walk.ts`): [`visit`] with a [`Visitor`] (enter/leave with
//! the path, the enclosing clause and the scope depth), [`transform`] (rebuild a
//! query with every expression mapped), [`strip_spans`]. One `children`
//! function per node kind is the single place a node's child slots are named;
//! `visit` and `transform` both read it.

use crate::ast::{
    Expr, Follow, FollowDestination, OpNode, OrderSpec, Query, SelectItem, Span, Subquery, Where,
};

/// A borrowed node of any kind.
#[derive(Clone, Copy, Debug)]
pub enum Node<'a> {
    Query(&'a Query),
    Subquery(&'a Subquery),
    Op(&'a OpNode),
    Follow(&'a Follow),
    Order(&'a OrderSpec),
    Select(&'a SelectItem),
    Where(&'a Where),
    Expr(&'a Expr),
}

impl Node<'_> {
    /// The node's span.
    pub fn span(&self) -> Span {
        match self {
            Node::Query(q) => q.span,
            Node::Subquery(s) => s.span,
            Node::Op(op) => op.span,
            Node::Follow(f) => f.span,
            Node::Order(o) => o.span,
            Node::Select(it) => it.span(),
            Node::Where(w) => w.span(),
            Node::Expr(e) => e.span(),
        }
    }

    /// The `kind` word of the JSON shape.
    pub fn kind(&self) -> &'static str {
        match self {
            Node::Query(_) => "query",
            Node::Subquery(_) => "subquery",
            Node::Op(_) => "op",
            Node::Follow(_) => "follow",
            Node::Order(_) => "order",
            Node::Select(SelectItem::Field { .. }) => "field",
            Node::Select(SelectItem::Collect { .. }) => "collect",
            Node::Where(w) => w.kind(),
            Node::Expr(e) => e.kind(),
        }
    }
}

/// The clause a node sits in. `Source` is the root collection (`from <source>`
/// or the directive receiver); `From` the further re-projections; `Follow` the
/// `Follow` node itself and `Follow*` its parts. The root node has no clause.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Clause {
    Source,
    From,
    Where,
    Select,
    OrderBy,
    Limit,
    Offset,
    Follow,
    FollowDestination,
    /// A `frontier` clause (0.20): a destination block's, read one level OUT
    /// of the block's rows — under the walk's enclosing scope — or a body's
    /// own (its seeds'), read in the row scope like `where`.
    FollowFrontier,
}

impl Clause {
    /// The reference's spelling (`"follow.destination"`, …).
    pub fn as_str(self) -> &'static str {
        match self {
            Clause::Source => "source",
            Clause::From => "from",
            Clause::Where => "where",
            Clause::Select => "select",
            Clause::OrderBy => "orderBy",
            Clause::Limit => "limit",
            Clause::Offset => "offset",
            Clause::Follow => "follow",
            Clause::FollowDestination => "follow.destination",
            Clause::FollowFrontier => "follow.frontier",
        }
    }
}

/// Where a visited node sits. `depth` is the scope depth at which the node is
/// evaluated (0 = the root scope: a top-level `source`, `limit`, `offset`; 1 =
/// a top-level row: its `where`, `select`, `order by`, `from` re-projections
/// and `follow`; a block's rows are one deeper than the block's receiver — a
/// follow destination block's `where` therefore one deeper than the frontier
/// row — and a destination block's `frontier` one level out of its rows).
#[derive(Clone, Debug)]
pub struct VisitContext<'a> {
    /// The ancestors of the node, root first (empty for the root).
    pub path: Vec<Node<'a>>,
    pub clause: Option<Clause>,
    pub depth: usize,
}

/// The callbacks of [`visit`].
pub trait Visitor {
    /// Called before a node's children; return `false` to skip the subtree
    /// (`leave` is still called for the node).
    fn enter(&mut self, node: Node<'_>, ctx: &VisitContext<'_>) -> bool {
        let _ = (node, ctx);
        true
    }
    /// Called after a node's children.
    fn leave(&mut self, node: Node<'_>, ctx: &VisitContext<'_>) {
        let _ = (node, ctx);
    }
}

/// One child slot: the node, the clause it opens (inherited when `None`) and how
/// much deeper its scope is (negative for a destination block's `frontier`).
struct Child<'a> {
    node: Node<'a>,
    clause: Option<Clause>,
    depth: isize,
}

fn child<'a>(node: Node<'a>, clause: Option<Clause>, depth: isize) -> Child<'a> {
    Child {
        node,
        clause,
        depth,
    }
}

/// The children of a node in canonical source order — the one table every walk
/// reads (`spec/oqx/AST.md` §5).
fn children<'a>(node: Node<'a>) -> Vec<Child<'a>> {
    let mut out = Vec::new();
    match node {
        Node::Query(q) => {
            out.extend(
                q.select
                    .iter()
                    .map(|it| child(Node::Select(it), Some(Clause::Select), 1)),
            );
            out.push(child(Node::Expr(&q.source), Some(Clause::Source), 0));
            out.extend(
                q.from
                    .iter()
                    .map(|e| child(Node::Expr(e), Some(Clause::From), 1)),
            );
            if let Some(w) = &q.r#where {
                out.push(child(Node::Where(w), Some(Clause::Where), 1));
            }
            // The body's `frontier` (0.20) reads each seed in the row scope, like `where`.
            if let Some(e) = &q.frontier {
                out.push(child(Node::Expr(e), Some(Clause::FollowFrontier), 1));
            }
            if let Some(f) = &q.follow {
                out.push(child(Node::Follow(f), Some(Clause::Follow), 1));
            }
            if let Some(o) = &q.order_by {
                out.extend(
                    o.iter()
                        .map(|s| child(Node::Order(s), Some(Clause::OrderBy), 1)),
                );
            }
            if let Some(e) = &q.limit {
                out.push(child(Node::Expr(e), Some(Clause::Limit), 0));
            }
            if let Some(e) = &q.offset {
                out.push(child(Node::Expr(e), Some(Clause::Offset), 0));
            }
        }
        Node::Subquery(s) => {
            out.extend(
                s.select
                    .iter()
                    .map(|it| child(Node::Select(it), Some(Clause::Select), 0)),
            );
            out.extend(
                s.from
                    .iter()
                    .map(|e| child(Node::Expr(e), Some(Clause::From), 0)),
            );
            if let Some(w) = &s.r#where {
                out.push(child(Node::Where(w), Some(Clause::Where), 0));
            }
            // A destination block's `frontier` reads the occurrence under the
            // walk's enclosing scope — one level OUT of the block's rows; any
            // other block's reads its seeds in the row scope, like `where`
            // (`go`/`Transformer::subquery` tell the two apart by position).
            if let Some(e) = &s.frontier {
                out.push(child(Node::Expr(e), Some(Clause::FollowFrontier), -1));
            }
            if let Some(f) = &s.follow {
                out.push(child(Node::Follow(f), Some(Clause::Follow), 0));
            }
            if let Some(o) = &s.order_by {
                out.extend(
                    o.iter()
                        .map(|x| child(Node::Order(x), Some(Clause::OrderBy), 0)),
                );
            }
            if let Some(e) = &s.limit {
                out.push(child(Node::Expr(e), Some(Clause::Limit), 0));
            }
            if let Some(e) = &s.offset {
                out.push(child(Node::Expr(e), Some(Clause::Offset), 0));
            }
        }
        Node::Op(op) => {
            out.push(child(Node::Expr(&op.receiver), None, 0));
            out.push(child(Node::Subquery(&op.sub), None, 1));
        }
        Node::Follow(f) => {
            out.extend(f.destinations.iter().map(|d| {
                let n = match d {
                    FollowDestination::Relation(e) => Node::Expr(e),
                    FollowDestination::Block(op) => Node::Op(op),
                };
                child(n, Some(Clause::FollowDestination), 0)
            }));
        }
        Node::Order(o) => out.push(child(Node::Expr(&o.expr), None, 0)),
        Node::Select(SelectItem::Field { expr, .. }) => out.push(child(Node::Expr(expr), None, 0)),
        Node::Select(SelectItem::Collect { op, .. }) => out.push(child(Node::Op(op), None, 0)),
        Node::Where(w) => match w {
            Where::And { parts, .. } | Where::Or { parts, .. } => {
                out.extend(parts.iter().map(|p| child(where_node(p), None, 0)));
            }
            Where::Not { expr, .. } => out.push(child(where_node(expr), None, 0)),
            Where::Scalar { expr, .. } => out.push(child(Node::Expr(expr), None, 0)),
            Where::Op(op) => return children(Node::Op(op)),
        },
        Node::Expr(e) => match e {
            Expr::Lit { .. } | Expr::Ident { .. } | Expr::Outer { .. } | Expr::Binding { .. } => {}
            Expr::Member { recv, .. } => out.push(child(Node::Expr(recv), None, 0)),
            Expr::Call { recv, args, .. } => {
                if let Some(r) = recv {
                    out.push(child(Node::Expr(r), None, 0));
                }
                out.extend(args.iter().map(|a| child(Node::Expr(a), None, 0)));
            }
            Expr::Unary { expr, .. } | Expr::Required { expr, .. } => {
                out.push(child(Node::Expr(expr), None, 0))
            }
            // A value-position directive: its receiver, then its body one deeper.
            Expr::Op(op) => return children(Node::Op(op)),
            Expr::Binary { left, right, .. }
            | Expr::Logical { left, right, .. }
            | Expr::In { left, right, .. } => {
                out.push(child(Node::Expr(left), None, 0));
                out.push(child(Node::Expr(right), None, 0));
            }
            Expr::Range { lo, hi, .. } => {
                if let Some(l) = lo {
                    out.push(child(Node::Expr(l), None, 0));
                }
                if let Some(h) = hi {
                    out.push(child(Node::Expr(h), None, 0));
                }
            }
            Expr::Tuple { items, .. } => {
                out.extend(items.iter().map(|x| child(Node::Expr(x), None, 0)));
            }
        },
    }
    out
}

/// A block is a follow destination block when its `OpNode` is a direct
/// destination of a `Follow` node. `path` is the ancestors with the block
/// itself last.
fn is_destination_block(path: &[Node<'_>]) -> bool {
    let n = path.len();
    n >= 3 && matches!(path[n - 2], Node::Op(_)) && matches!(path[n - 3], Node::Follow(_))
}

/// How much deeper a child's scope is: the table's value, except a block's
/// `frontier`, which is one level OUT only for a destination block (the walk's
/// enclosing scope) and the row scope itself for a body with its own `follow`.
fn child_depth(node: Node<'_>, c: &Child<'_>, path: &[Node<'_>]) -> isize {
    if matches!(node, Node::Subquery(_))
        && c.clause == Some(Clause::FollowFrontier)
        && !is_destination_block(path)
    {
        return 0;
    }
    c.depth
}

/// A where-position consumer test is the `OpNode` itself (`kind: "op"`).
fn where_node(w: &Where) -> Node<'_> {
    match w {
        Where::Op(op) => Node::Op(op),
        other => Node::Where(other),
    }
}

/// Walk a tree depth-first in canonical source order.
pub fn visit<'a, V: Visitor>(root: Node<'a>, visitor: &mut V) {
    let mut path: Vec<Node<'a>> = Vec::new();
    go(root, None, 0, &mut path, visitor);
}

fn go<'a, V: Visitor>(
    node: Node<'a>,
    clause: Option<Clause>,
    depth: usize,
    path: &mut Vec<Node<'a>>,
    visitor: &mut V,
) {
    let ctx = VisitContext {
        path: path.clone(),
        clause,
        depth,
    };
    if visitor.enter(node, &ctx) {
        path.push(node);
        for c in children(node) {
            let d = (depth as isize + child_depth(node, &c, path)).max(0) as usize;
            go(c.node, c.clause.or(clause), d, path, visitor);
        }
        path.pop();
    }
    visitor.leave(node, &ctx);
}

/// The query's root as a [`Node`].
pub fn node(q: &Query) -> Node<'_> {
    Node::Query(q)
}

// ---- transform -----------------------------------------------------------------

/// Rebuild a query with every expression mapped through `f`, children first (so
/// `f` sees an expression whose operands are already mapped). Spans of nodes
/// `f` returns unchanged are preserved (they are the same values).
pub fn transform<F>(q: &Query, f: &mut F) -> Query
where
    F: FnMut(Expr, &VisitContext<'_>) -> Expr,
{
    let mut t = Transformer {
        f,
        path: Vec::new(),
    };
    t.path.push(Node::Query(q));
    let out = Query {
        select: t.items(&q.select, Clause::Select, 1),
        source: t.expr(&q.source, Clause::Source, 0),
        from: q.from.iter().map(|e| t.expr(e, Clause::From, 1)).collect(),
        r#where: q.r#where.as_ref().map(|w| t.r#where(w, Clause::Where, 1)),
        frontier: q
            .frontier
            .as_ref()
            .map(|e| t.expr(e, Clause::FollowFrontier, 1)),
        follow: q.follow.as_ref().map(|fl| t.follow(fl, 1)),
        order_by: q
            .order_by
            .as_ref()
            .map(|o| o.iter().map(|s| t.order(s, 1)).collect()),
        limit: q.limit.as_ref().map(|e| t.expr(e, Clause::Limit, 0)),
        offset: q.offset.as_ref().map(|e| t.expr(e, Clause::Offset, 0)),
        consumer: q.consumer,
        distinct: q.distinct,
        values: q.values,
        span: q.span,
    };
    t.path.pop();
    out
}

/// [`transform`] for a block body (evaluated at scope `depth`).
pub fn transform_subquery<F>(s: &Subquery, depth: usize, f: &mut F) -> Subquery
where
    F: FnMut(Expr, &VisitContext<'_>) -> Expr,
{
    let mut t = Transformer {
        f,
        path: Vec::new(),
    };
    t.subquery(s, depth, None)
}

struct Transformer<'a, 'f, F> {
    f: &'f mut F,
    path: Vec<Node<'a>>,
}

impl<'a, F> Transformer<'a, '_, F>
where
    F: FnMut(Expr, &VisitContext<'_>) -> Expr,
{
    fn ctx(&self, clause: Option<Clause>, depth: usize) -> VisitContext<'a> {
        VisitContext {
            path: self.path.clone(),
            clause,
            depth,
        }
    }

    fn items(&mut self, items: &'a [SelectItem], clause: Clause, depth: usize) -> Vec<SelectItem> {
        items
            .iter()
            .map(|it| self.item(it, clause, depth))
            .collect()
    }

    fn item(&mut self, it: &'a SelectItem, clause: Clause, depth: usize) -> SelectItem {
        self.path.push(Node::Select(it));
        let out = match it {
            SelectItem::Field {
                name,
                expr,
                lift,
                span,
            } => SelectItem::Field {
                name: name.clone(),
                expr: self.expr(expr, clause, depth),
                lift: *lift,
                span: *span,
            },
            SelectItem::Collect { name, op, span } => SelectItem::Collect {
                name: name.clone(),
                op: Box::new(self.op(op, clause, depth)),
                span: *span,
            },
        };
        self.path.pop();
        out
    }

    fn op(&mut self, op: &'a OpNode, clause: Clause, depth: usize) -> OpNode {
        self.path.push(Node::Op(op));
        let out = OpNode {
            receiver: self.expr(&op.receiver, clause, depth),
            op: op.op,
            sub: self.subquery(&op.sub, depth + 1, Some(clause)),
            count_cmp: op.count_cmp.clone(),
            distinct: op.distinct,
            span: op.span,
        };
        self.path.pop();
        out
    }

    fn subquery(&mut self, s: &'a Subquery, depth: usize, _outer: Option<Clause>) -> Subquery {
        self.path.push(Node::Subquery(s));
        // A destination block's `frontier` is read one level OUT of its rows,
        // any other block's (its seeds') in the row scope.
        let frontier_depth = if is_destination_block(&self.path) {
            depth.saturating_sub(1)
        } else {
            depth
        };
        let out = Subquery {
            select: self.items(&s.select, Clause::Select, depth),
            from: s
                .from
                .iter()
                .map(|e| self.expr(e, Clause::From, depth))
                .collect(),
            r#where: s
                .r#where
                .as_ref()
                .map(|w| self.r#where(w, Clause::Where, depth)),
            frontier: s
                .frontier
                .as_ref()
                .map(|e| self.expr(e, Clause::FollowFrontier, frontier_depth)),
            depth: s.depth,
            follow: s.follow.as_ref().map(|fl| self.follow(fl, depth)),
            order_by: s
                .order_by
                .as_ref()
                .map(|o| o.iter().map(|x| self.order(x, depth)).collect()),
            limit: s.limit.as_ref().map(|e| self.expr(e, Clause::Limit, depth)),
            offset: s
                .offset
                .as_ref()
                .map(|e| self.expr(e, Clause::Offset, depth)),
            values: s.values,
            span: s.span,
        };
        self.path.pop();
        out
    }

    fn follow(&mut self, f: &'a Follow, depth: usize) -> Follow {
        self.path.push(Node::Follow(f));
        let out = Follow {
            destinations: f
                .destinations
                .iter()
                .map(|d| match d {
                    FollowDestination::Relation(e) => {
                        FollowDestination::Relation(self.expr(e, Clause::FollowDestination, depth))
                    }
                    FollowDestination::Block(op) => FollowDestination::Block(Box::new(self.op(
                        op,
                        Clause::FollowDestination,
                        depth,
                    ))),
                })
                .collect(),
            distinct: f.distinct,
            span: f.span,
        };
        self.path.pop();
        out
    }

    fn order(&mut self, o: &'a OrderSpec, depth: usize) -> OrderSpec {
        self.path.push(Node::Order(o));
        let out = OrderSpec {
            expr: self.expr(&o.expr, Clause::OrderBy, depth),
            desc: o.desc,
            span: o.span,
        };
        self.path.pop();
        out
    }

    fn r#where(&mut self, w: &'a Where, clause: Clause, depth: usize) -> Where {
        if let Where::Op(op) = w {
            return Where::Op(Box::new(self.op(op, clause, depth)));
        }
        self.path.push(Node::Where(w));
        let out = match w {
            Where::And { parts, span } => Where::And {
                parts: parts
                    .iter()
                    .map(|p| self.r#where(p, clause, depth))
                    .collect(),
                span: *span,
            },
            Where::Or { parts, span } => Where::Or {
                parts: parts
                    .iter()
                    .map(|p| self.r#where(p, clause, depth))
                    .collect(),
                span: *span,
            },
            Where::Not { expr, span } => Where::Not {
                expr: Box::new(self.r#where(expr, clause, depth)),
                span: *span,
            },
            Where::Scalar { expr, span } => Where::Scalar {
                expr: self.expr(expr, clause, depth),
                span: *span,
            },
            Where::Op(_) => unreachable!("handled above"),
        };
        self.path.pop();
        out
    }

    fn expr(&mut self, e: &'a Expr, clause: Clause, depth: usize) -> Expr {
        self.path.push(Node::Expr(e));
        let rebuilt = match e {
            Expr::Lit { .. } | Expr::Ident { .. } | Expr::Outer { .. } | Expr::Binding { .. } => {
                e.clone()
            }
            Expr::Member { recv, name, span } => Expr::Member {
                recv: Box::new(self.expr(recv, clause, depth)),
                name: name.clone(),
                span: *span,
            },
            Expr::Call {
                recv,
                name,
                args,
                span,
            } => Expr::Call {
                recv: recv
                    .as_deref()
                    .map(|r| Box::new(self.expr(r, clause, depth))),
                name: name.clone(),
                args: args.iter().map(|a| self.expr(a, clause, depth)).collect(),
                span: *span,
            },
            Expr::Unary { op, expr, span } => Expr::Unary {
                op: *op,
                expr: Box::new(self.expr(expr, clause, depth)),
                span: *span,
            },
            Expr::Required { expr, span } => Expr::Required {
                expr: Box::new(self.expr(expr, clause, depth)),
                span: *span,
            },
            // An op is an expression only by position: its parts are mapped and
            // the op rebuilt; `f` never sees the op itself (AST.md §1).
            Expr::Op(op) => {
                self.path.pop();
                return Expr::Op(Box::new(self.op(op, clause, depth)));
            }
            Expr::Binary {
                op,
                left,
                right,
                span,
            } => Expr::Binary {
                op: *op,
                left: Box::new(self.expr(left, clause, depth)),
                right: Box::new(self.expr(right, clause, depth)),
                span: *span,
            },
            Expr::Logical {
                op,
                left,
                right,
                span,
            } => Expr::Logical {
                op: *op,
                left: Box::new(self.expr(left, clause, depth)),
                right: Box::new(self.expr(right, clause, depth)),
                span: *span,
            },
            Expr::In { left, right, span } => Expr::In {
                left: Box::new(self.expr(left, clause, depth)),
                right: Box::new(self.expr(right, clause, depth)),
                span: *span,
            },
            Expr::Range {
                lo,
                hi,
                exclusive_end,
                span,
            } => Expr::Range {
                lo: lo.as_deref().map(|x| Box::new(self.expr(x, clause, depth))),
                hi: hi.as_deref().map(|x| Box::new(self.expr(x, clause, depth))),
                exclusive_end: *exclusive_end,
                span: *span,
            },
            Expr::Tuple { items, span } => Expr::Tuple {
                items: items.iter().map(|x| self.expr(x, clause, depth)).collect(),
                span: *span,
            },
        };
        self.path.pop();
        let ctx = self.ctx(Some(clause), depth);
        (self.f)(rebuilt, &ctx)
    }
}

// ---- strip_spans ----------------------------------------------------------------

/// The tree with every span set to [`Span::EMPTY`], for shape comparisons (the
/// fixtures and the round-trip law compare stripped trees; a tree from
/// [`crate::build`] is already stripped).
pub fn strip_spans(q: &Query) -> Query {
    let mut q = q.clone();
    strip_query_spans(&mut q);
    q
}

fn strip_query_spans(q: &mut Query) {
    q.span = Span::EMPTY;
    q.select.iter_mut().for_each(strip_item_spans);
    strip_expr_spans(&mut q.source);
    q.from.iter_mut().for_each(strip_expr_spans);
    if let Some(w) = &mut q.r#where {
        strip_where_spans(w);
    }
    if let Some(e) = &mut q.frontier {
        strip_expr_spans(e);
    }
    if let Some(f) = &mut q.follow {
        strip_follow_spans(f);
    }
    if let Some(o) = &mut q.order_by {
        o.iter_mut().for_each(strip_order_spans);
    }
    if let Some(e) = &mut q.limit {
        strip_expr_spans(e);
    }
    if let Some(e) = &mut q.offset {
        strip_expr_spans(e);
    }
}

fn strip_sub_spans(s: &mut Subquery) {
    s.span = Span::EMPTY;
    s.select.iter_mut().for_each(strip_item_spans);
    s.from.iter_mut().for_each(strip_expr_spans);
    if let Some(w) = &mut s.r#where {
        strip_where_spans(w);
    }
    if let Some(e) = &mut s.frontier {
        strip_expr_spans(e);
    }
    if let Some(f) = &mut s.follow {
        strip_follow_spans(f);
    }
    if let Some(o) = &mut s.order_by {
        o.iter_mut().for_each(strip_order_spans);
    }
    if let Some(e) = &mut s.limit {
        strip_expr_spans(e);
    }
    if let Some(e) = &mut s.offset {
        strip_expr_spans(e);
    }
}

fn strip_order_spans(o: &mut OrderSpec) {
    o.span = Span::EMPTY;
    strip_expr_spans(&mut o.expr);
}

fn strip_op_spans(op: &mut OpNode) {
    op.span = Span::EMPTY;
    strip_expr_spans(&mut op.receiver);
    strip_sub_spans(&mut op.sub);
}

fn strip_item_spans(it: &mut SelectItem) {
    match it {
        SelectItem::Field { expr, span, .. } => {
            *span = Span::EMPTY;
            strip_expr_spans(expr);
        }
        SelectItem::Collect { op, span, .. } => {
            *span = Span::EMPTY;
            strip_op_spans(op);
        }
    }
}

fn strip_follow_spans(f: &mut Follow) {
    f.span = Span::EMPTY;
    for d in &mut f.destinations {
        match d {
            FollowDestination::Block(op) => strip_op_spans(op),
            FollowDestination::Relation(e) => strip_expr_spans(e),
        }
    }
}

fn strip_where_spans(w: &mut Where) {
    match w {
        Where::And { parts, span } | Where::Or { parts, span } => {
            *span = Span::EMPTY;
            parts.iter_mut().for_each(strip_where_spans);
        }
        Where::Not { expr, span } => {
            *span = Span::EMPTY;
            strip_where_spans(expr);
        }
        Where::Scalar { expr, span } => {
            *span = Span::EMPTY;
            strip_expr_spans(expr);
        }
        Where::Op(op) => strip_op_spans(op),
    }
}

/// Every span inside an expression, including the blocks of value-position
/// directives (which `transform` rebuilds but does not hand to its mapping).
fn strip_expr_spans(e: &mut Expr) {
    match e {
        Expr::Op(op) => strip_op_spans(op),
        other => {
            *other.span_mut() = Span::EMPTY;
            match other {
                Expr::Lit { .. }
                | Expr::Ident { .. }
                | Expr::Outer { .. }
                | Expr::Binding { .. } => {}
                Expr::Member { recv, .. } => strip_expr_spans(recv),
                Expr::Call { recv, args, .. } => {
                    if let Some(r) = recv {
                        strip_expr_spans(r);
                    }
                    args.iter_mut().for_each(strip_expr_spans);
                }
                Expr::Unary { expr, .. } | Expr::Required { expr, .. } => strip_expr_spans(expr),
                Expr::Binary { left, right, .. }
                | Expr::Logical { left, right, .. }
                | Expr::In { left, right, .. } => {
                    strip_expr_spans(left);
                    strip_expr_spans(right);
                }
                Expr::Range { lo, hi, .. } => {
                    for b in [lo, hi].into_iter().flatten() {
                        strip_expr_spans(b);
                    }
                }
                Expr::Tuple { items, .. } => items.iter_mut().for_each(strip_expr_spans),
                Expr::Op(_) => unreachable!("handled above"),
            }
        }
    }
}