relate-ir 1.0.1

Planner IR (lowered Cypher AST)
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
//! Clause-tree walkers over the planner IR.
//!
//! [`walk_query`] is the clause-tree counterpart of the expression walkers
//! in [`crate::walk`]: it descends into nested queries (`CALL { … }`,
//! `WHEN` branches, `FOREACH` bodies, `NEXT` stages and the
//! pattern/subquery variants [`Expr::children`] skips) with exhaustive
//! matches, so a new clause or expression variant fails compilation here
//! instead of silently skipping a subtree.

use std::collections::HashSet;

use relate_names::SmallName;

use crate::search::SearchSpec;
use crate::walk::each_label_expr_child;
use crate::{
    Clause, Expr, LabelExpr, OrderItem, PathPattern, Projection, Query, RemoveItem, SetItem,
};

mod pattern;

pub use pattern::{
    any_pattern_payload, pattern_anchor_variables, pattern_node_anchor_variables,
    walk_pattern_payloads, PatternPayload,
};

/// The syntactic role an expression occupies for a consumer that must tell
/// a value the statement reads from a name it writes (ADR-0363 decision 13):
/// [`ExprRole::Read`] is every expression evaluated against incoming rows;
/// [`ExprRole::WriteTarget`] is a `SET`/`REMOVE` target and every payload
/// expression of a `CREATE`/`MERGE` target pattern.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExprRole {
    Read,
    WriteTarget,
}

/// Pre-order walk over a statement's clause tree.
///
/// `on_clause` sees every clause and `on_expr` every expression in the
/// statement: UNION-arm `parts`, `NEXT` stages, `CALL { … }` subqueries,
/// `WHEN` branches, `FOREACH` bodies and the queries inside expression
/// subqueries (`EXISTS`/`COUNT`/`COLLECT { … }`) are all descended into.
/// The matches are exhaustive over [`Clause`], [`crate::PatternElement`] and the
/// item enums, so a new variant fails compilation here instead of silently
/// skipping a subtree the way an [`Expr::children`] fold skips the
/// pattern/subquery variants.
pub fn walk_query<'a>(
    query: &'a Query,
    on_clause: &mut impl FnMut(&'a Clause),
    on_expr: &mut impl FnMut(&'a Expr),
) {
    walk_query_with_roles(query, on_clause, &mut |expr, _role| on_expr(expr));
}

/// [`walk_query`] with each expression's [`ExprRole`], for the readers that
/// distinguish read evidence from a write target (ADR-0363 decision 13).
pub(crate) fn walk_query_with_roles<'a>(
    query: &'a Query,
    on_clause: &mut impl FnMut(&'a Clause),
    on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
    walk_query_at(
        query,
        false,
        &mut |clause, _nested| on_clause(clause),
        on_expr,
    );
}

/// The nesting-aware walk over one query: `nested` is the caller's context
/// (a `CALL { … }` body, a `WHEN` branch or an expression subquery is
/// nested), and every clause callback receives the clause's own nesting as
/// data — never derived from the callback order.
fn walk_query_at<'a>(
    query: &'a Query,
    nested: bool,
    on_clause: &mut impl FnMut(&'a Clause, bool),
    on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
    for part in &query.parts {
        walk_clauses_at(&part.clauses, nested, on_clause, on_expr);
    }
    if let Some(next) = query.next.as_deref() {
        // `NEXT` is a statement stage, not a nested body.
        walk_query_at(next, nested, on_clause, on_expr);
    }
}

/// [`walk_query`] over a clause list, for plan shapes that store clauses
/// directly rather than as a [`Query`] (e.g. a logical plan's parts).
pub fn walk_clauses<'a>(
    clauses: &'a [Clause],
    on_clause: &mut impl FnMut(&'a Clause),
    on_expr: &mut impl FnMut(&'a Expr),
) {
    walk_clauses_at(
        clauses,
        false,
        &mut |clause, _nested| on_clause(clause),
        &mut |expr, _role| on_expr(expr),
    );
}

/// [`walk_clauses`] with each expression's [`ExprRole`], reporting each
/// clause with a `nested` flag: `false` for the top-level clauses of
/// `clauses`, `true` for every clause inside a `CALL { … }` body, a `WHEN`
/// branch, a `FOREACH` body or an expression subquery.
pub fn walk_clauses_with_roles<'a>(
    clauses: &'a [Clause],
    on_clause: &mut impl FnMut(&'a Clause, bool),
    on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
    walk_clauses_at(clauses, false, on_clause, on_expr);
}

/// The one clause-list walk: `nested` is the list's own context, and the
/// nested bodies it descends into pass `true`.
fn walk_clauses_at<'a>(
    clauses: &'a [Clause],
    nested: bool,
    on_clause: &mut impl FnMut(&'a Clause, bool),
    on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
    for clause in clauses {
        on_clause(clause, nested);
        match clause {
            Clause::Match {
                patterns,
                where_clause,
                search,
                ..
            } => {
                for pattern in patterns {
                    walk_pattern(pattern, ExprRole::Read, on_clause, on_expr);
                }
                if let Some(where_clause) = where_clause {
                    walk_expr(where_clause, ExprRole::Read, on_clause, on_expr);
                }
                if let Some(search) = search {
                    walk_search_spec(&search.spec, on_clause, on_expr);
                }
            }
            // A write target's own payload names what the statement brings
            // into existence, so it is a write target, not read evidence.
            Clause::Create { patterns } => {
                for pattern in patterns {
                    walk_pattern(pattern, ExprRole::WriteTarget, on_clause, on_expr);
                }
            }
            Clause::Merge {
                pattern,
                on_create,
                on_match,
            } => {
                walk_pattern(pattern, ExprRole::WriteTarget, on_clause, on_expr);
                for item in on_create.iter().chain(on_match) {
                    walk_set_item(item, on_clause, on_expr);
                }
            }
            Clause::Call {
                args, where_clause, ..
            } => {
                for arg in args {
                    walk_expr(arg, ExprRole::Read, on_clause, on_expr);
                }
                if let Some(where_clause) = where_clause {
                    walk_expr(where_clause, ExprRole::Read, on_clause, on_expr);
                }
            }
            Clause::Delete { expressions, .. } => {
                for expr in expressions {
                    walk_expr(expr, ExprRole::Read, on_clause, on_expr);
                }
            }
            Clause::Set { items } => {
                for item in items {
                    walk_set_item(item, on_clause, on_expr);
                }
            }
            Clause::Remove { items } => {
                for item in items {
                    walk_remove_item(item, on_clause, on_expr);
                }
            }
            Clause::With {
                items,
                order,
                skip,
                limit,
                where_clause,
                group_by,
                ..
            } => {
                walk_projection(items, order, skip, limit, group_by, on_clause, on_expr);
                if let Some(where_clause) = where_clause {
                    walk_expr(where_clause, ExprRole::Read, on_clause, on_expr);
                }
            }
            Clause::Return {
                items,
                order,
                skip,
                limit,
                group_by,
                ..
            } => {
                walk_projection(items, order, skip, limit, group_by, on_clause, on_expr);
            }
            Clause::Unwind { expression, .. } => {
                walk_expr(expression, ExprRole::Read, on_clause, on_expr)
            }
            Clause::LoadCsv { url, .. } => walk_expr(url, ExprRole::Read, on_clause, on_expr),
            Clause::CallSubquery {
                query,
                in_transactions,
                ..
            } => {
                walk_query_at(query, true, on_clause, on_expr);
                if let Some(tx) = in_transactions {
                    // The one slot enumeration lives in
                    // `InTransactions::exprs`, so the walker cannot drift
                    // from the planner's modifier checks.
                    for expr in tx.exprs() {
                        walk_expr(expr, ExprRole::Read, on_clause, on_expr);
                    }
                }
            }
            Clause::Conditional {
                branches,
                else_query,
            } => {
                for (predicate, query) in branches {
                    walk_expr(predicate, ExprRole::Read, on_clause, on_expr);
                    walk_query_at(query, true, on_clause, on_expr);
                }
                if let Some(query) = else_query.as_deref() {
                    walk_query_at(query, true, on_clause, on_expr);
                }
            }
            Clause::Foreach { list, clauses, .. } => {
                walk_expr(list, ExprRole::Read, on_clause, on_expr);
                walk_clauses_at(clauses, true, on_clause, on_expr);
            }
            Clause::Use { graph } => walk_expr(graph, ExprRole::Read, on_clause, on_expr),
            Clause::Catalog(_)
            | Clause::CreateIndex { .. }
            | Clause::DropIndex { .. }
            | Clause::ShowIndexes
            | Clause::Finish => {}
        }
    }
}

/// Walk every expression of a CIP-278 `<source specification clause>`.
/// The slot enumeration and its exhaustive-match compile guarantee live
/// in `SearchSpec::exprs` (ADR-0379); the planner consumes the same
/// exactly `SearchSpec::exprs()`'s consumer, so there is no second
/// match here to drift.
fn walk_search_spec<'a>(
    spec: &'a SearchSpec,
    on_clause: &mut impl FnMut(&'a Clause, bool),
    on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
    for expr in spec.exprs() {
        walk_expr(expr, ExprRole::Read, on_clause, on_expr);
    }
}

/// Pre-order expression walk used by [`walk_query`]: unlike
/// [`Expr::visit`], descends into the pattern- and subquery-bearing
/// variants that [`Expr::children`] deliberately skips. The enclosing
/// [`ExprRole`] is handed to the callback and inherited by every child.
pub(crate) fn walk_expr<'a>(
    expr: &'a Expr,
    role: ExprRole,
    on_clause: &mut impl FnMut(&'a Clause, bool),
    on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
    on_expr(expr, role);
    // An expression-subquery body is walked as a nested query instead of
    // the generic child descent — the one accessor decides which
    // expressions open one (a new variant extends it, not every walk).
    if let Some(query) = expr.subquery_body() {
        walk_query_at(query, true, on_clause, on_expr);
        return;
    }
    match expr {
        Expr::PatternPred { path } | Expr::ShortestPath { path, .. } => {
            walk_pattern(path, role, on_clause, on_expr);
        }
        Expr::PatternComp {
            path,
            predicate,
            projection,
        } => {
            walk_pattern(path, role, on_clause, on_expr);
            if let Some(predicate) = predicate.as_deref() {
                walk_expr(predicate, role, on_clause, on_expr);
            }
            walk_expr(projection, role, on_clause, on_expr);
        }
        // Every scope-bearing variant is matched above; a new one must be
        // added there, not silently fall through to the flat child walk.
        other => {
            debug_assert!(
                !other.is_scope_bearing(),
                "scope-bearing variant {other:?} fell through to each_child"
            );
            other.each_child(&mut |child| walk_expr(child, role, &mut *on_clause, &mut *on_expr));
        }
    }
}

/// The shared projection shape of `WITH` and `RETURN`; every position is a
/// read.
fn walk_projection<'a>(
    items: &'a [Projection],
    order: &'a [OrderItem],
    skip: &'a Option<Expr>,
    limit: &'a Option<Expr>,
    group_by: &'a Option<Vec<Expr>>,
    on_clause: &mut impl FnMut(&'a Clause, bool),
    on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
    for item in items {
        walk_expr(&item.expr, ExprRole::Read, on_clause, on_expr);
    }
    for item in order {
        walk_expr(&item.expr, ExprRole::Read, on_clause, on_expr);
    }
    for expr in skip.iter().chain(limit) {
        walk_expr(expr, ExprRole::Read, on_clause, on_expr);
    }
    if let Some(group_by) = group_by {
        for expr in group_by {
            walk_expr(expr, ExprRole::Read, on_clause, on_expr);
        }
    }
}

/// A `SET` item: the target is a write target, the value a read (so
/// `SET n.key = n.other` still reads `other` — ADR-0363 decision 13).
fn walk_set_item<'a>(
    item: &'a SetItem,
    on_clause: &mut impl FnMut(&'a Clause, bool),
    on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
    match item {
        SetItem::Property { target, value }
        | SetItem::ReplaceAll { target, value }
        | SetItem::MergeMap { target, value }
        | SetItem::LabelsFunction { target, value, .. } => {
            walk_expr(target, ExprRole::WriteTarget, on_clause, on_expr);
            walk_expr(value, ExprRole::Read, on_clause, on_expr);
        }
        SetItem::Labels { target, labels } => {
            walk_expr(target, ExprRole::WriteTarget, on_clause, on_expr);
            for label in labels {
                walk_label_expr(label, ExprRole::WriteTarget, on_clause, on_expr);
            }
        }
    }
}

/// A `REMOVE` item: every position is a write target.
fn walk_remove_item<'a>(
    item: &'a RemoveItem,
    on_clause: &mut impl FnMut(&'a Clause, bool),
    on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
    match item {
        RemoveItem::Property { target } => {
            walk_expr(target, ExprRole::WriteTarget, on_clause, on_expr)
        }
        RemoveItem::Labels { target, labels } => {
            walk_expr(target, ExprRole::WriteTarget, on_clause, on_expr);
            for label in labels {
                walk_label_expr(label, ExprRole::WriteTarget, on_clause, on_expr);
            }
        }
    }
}

fn walk_pattern<'a>(
    pattern: &'a PathPattern,
    role: ExprRole,
    on_clause: &mut impl FnMut(&'a Clause, bool),
    on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
    walk_pattern_full(pattern, role, on_clause, on_expr, &mut |_| {});
}

/// [`walk_pattern`] plus the pattern's *binding* positions: `on_binding`
/// sees every variable a pattern binds (path variable, node/relationship
/// variables, quantified subpath variables) at the same exclusive
/// [`walk_pattern_payloads`] dispatch, so a caller needing "every name a
/// pattern mentions" does not re-enumerate the payload fields.
fn walk_pattern_full<'a>(
    pattern: &'a PathPattern,
    role: ExprRole,
    on_clause: &mut impl FnMut(&'a Clause, bool),
    on_expr: &mut impl FnMut(&'a Expr, ExprRole),
    on_binding: &mut impl FnMut(&'a SmallName),
) {
    if let Some(variable) = &pattern.variable {
        on_binding(variable);
    }
    walk_pattern_payloads(pattern, &mut |payload| match payload {
        PatternPayload::Node(node) => walk_node_pattern(node, role, on_clause, on_expr, on_binding),
        PatternPayload::Relationship(rel) => {
            walk_rel_pattern(rel, role, on_clause, on_expr, on_binding)
        }
        PatternPayload::Quantified(quantified) => {
            if let Some(variable) = &quantified.subpath_variable {
                on_binding(variable);
            }
            if let Some(where_clause) = &quantified.where_clause {
                walk_expr(where_clause, role, on_clause, on_expr);
            }
        }
    });
    if let Some(where_clause) = pattern.where_clause.as_deref() {
        walk_expr(where_clause, role, on_clause, on_expr);
    }
}

/// The one enumeration of a node pattern's payload — binding, label
/// expression, property map, element predicate — consulted by both the
/// compact view and the elements sequence.
fn walk_node_pattern<'a>(
    node: &'a crate::NodePattern,
    role: ExprRole,
    on_clause: &mut impl FnMut(&'a Clause, bool),
    on_expr: &mut impl FnMut(&'a Expr, ExprRole),
    on_binding: &mut impl FnMut(&'a SmallName),
) {
    if let Some(variable) = &node.variable {
        on_binding(variable);
    }
    if let Some(label_expr) = &node.label_expr {
        walk_label_expr(label_expr, role, on_clause, on_expr);
    }
    if let Some(properties) = &node.properties {
        walk_expr(properties, role, on_clause, on_expr);
    }
    if let Some(where_clause) = &node.where_clause {
        walk_expr(where_clause, role, on_clause, on_expr);
    }
}

/// The relationship counterpart of [`walk_node_pattern`].
fn walk_rel_pattern<'a>(
    rel: &'a crate::RelPattern,
    role: ExprRole,
    on_clause: &mut impl FnMut(&'a Clause, bool),
    on_expr: &mut impl FnMut(&'a Expr, ExprRole),
    on_binding: &mut impl FnMut(&'a SmallName),
) {
    if let Some(variable) = &rel.variable {
        on_binding(variable);
    }
    if let Some(type_expr) = &rel.type_expr {
        walk_label_expr(type_expr, role, on_clause, on_expr);
    }
    if let Some(properties) = &rel.properties {
        walk_expr(properties, role, on_clause, on_expr);
    }
    if let Some(where_clause) = &rel.where_clause {
        walk_expr(where_clause, role, on_clause, on_expr);
    }
}

/// Every variable name a path pattern *mentions*: each bound variable
/// (path, node, relationship, quantified subpath — a bound name equal to
/// an already-bound outer name is a correlation predicate, not a fresh
/// binding) plus every variable its expressions reference (property maps,
/// dynamic label/type expressions, element and path predicates). Built on
/// the canonical [`walk_pattern_payloads`] payload walk so the
/// elements-vs-compact dispatch and the per-field enumeration live exactly
/// once.
pub fn path_pattern_mentions(path: &PathPattern, out: &mut HashSet<String>) {
    let mut bindings = HashSet::new();
    walk_pattern_full(
        path,
        ExprRole::Read,
        &mut |_, _| {},
        &mut |expr, _role| crate::walk::expr_vars(expr, out),
        &mut |name| {
            bindings.insert(name.to_string());
        },
    );
    out.extend(bindings);
}

/// The expressions inside a label expression's dynamic (`$(…)`) forms.
fn walk_label_expr<'a>(
    label_expr: &'a LabelExpr,
    role: ExprRole,
    on_clause: &mut impl FnMut(&'a Clause, bool),
    on_expr: &mut impl FnMut(&'a Expr, ExprRole),
) {
    each_label_expr_child(label_expr, &mut |child| {
        walk_expr(child, role, &mut *on_clause, &mut *on_expr)
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        Direction, DynamicLabelQuantifier, MatchMode, NodePattern, PatternElement,
        QuantifiedPathPattern, RelPattern, SingleQuery,
    };

    fn var(name: &str) -> Expr {
        Expr::Variable(name.into())
    }

    fn use_clause(name: &str) -> Clause {
        Clause::Use {
            graph: Expr::Variable(name.into()),
        }
    }

    fn query(clauses: Vec<Clause>) -> Query {
        Query {
            parts: vec![SingleQuery { clauses }],
            union_all: Vec::new(),
            next: None,
            cypher_version: None,
        }
    }

    /// A dynamic `$(COUNT { USE <name> … })` label expression.
    fn dynamic_label(name: &str) -> LabelExpr {
        LabelExpr::Dynamic {
            expr: Box::new(Expr::CountSubquery {
                query: query(vec![use_clause(name)]),
            }),
            quantifier: DynamicLabelQuantifier::Default,
        }
    }

    /// The `USE` graph names the walk sees, in walk order.
    fn seen_use_graphs(query: &Query) -> Vec<String> {
        let mut seen = Vec::new();
        walk_query(
            query,
            &mut |clause| {
                if let Clause::Use {
                    graph: Expr::Variable(name),
                } = clause
                {
                    seen.push(name.to_string());
                }
            },
            &mut |_| {},
        );
        seen
    }

    #[test]
    fn walk_query_descends_into_set_and_remove_label_payloads() {
        // Regression: SetItem::Labels / RemoveItem::Labels carry a
        // Vec<LabelExpr> whose dynamic $(…) forms can hold nested queries;
        // skipping the payload lets a nested USE escape resolution.
        let top = query(vec![
            Clause::Set {
                items: vec![SetItem::Labels {
                    target: Expr::Variable("n".into()),
                    labels: vec![dynamic_label("set_inner")],
                }],
            },
            Clause::Remove {
                items: vec![RemoveItem::Labels {
                    target: Expr::Variable("n".into()),
                    labels: vec![dynamic_label("remove_inner")],
                }],
            },
        ]);
        assert_eq!(
            seen_use_graphs(&top),
            vec!["set_inner".to_string(), "remove_inner".to_string()]
        );
    }

    #[test]
    fn walk_query_descends_into_pattern_element_label_exprs() {
        // Regression: lowering clears the compact `nodes`/`rels` repr for
        // quantified (non-compact) patterns, so the `elements` sequence is
        // the surviving representation — its label_expr/type_expr payloads
        // must be walked too.
        fn node(label: Option<LabelExpr>) -> NodePattern {
            NodePattern {
                variable: None,
                labels: Vec::new(),
                label_expr: label,
                properties: None,
                prop_keys: Vec::new(),
                where_clause: None,
                force_scan: false,
            }
        }
        let pattern = PathPattern {
            variable: None,
            subpath_variable: None,
            nodes: Vec::new(),
            rels: Vec::new(),
            elements: vec![
                PatternElement::Node(node(Some(dynamic_label("node_label")))),
                PatternElement::Relationship(RelPattern {
                    variable: None,
                    types: Vec::new(),
                    type_expr: Some(dynamic_label("rel_type")),
                    direction: Direction::Outgoing,
                    properties: None,
                    prop_keys: Vec::new(),
                    var_length: false,
                    min_hops: 1,
                    max_hops: None,
                    where_clause: None,
                    quantified: false,
                }),
                PatternElement::Quantified(QuantifiedPathPattern {
                    subpath_variable: None,
                    elements: vec![PatternElement::Node(node(Some(dynamic_label(
                        "quantified_node",
                    ))))],
                    where_clause: None,
                    min: 1,
                    max: None,
                }),
            ],
            where_clause: None,
            mode: None,
            selector: None,
            is_shortest_path_function: false,
        };
        let top = query(vec![Clause::Match {
            optional: false,
            match_mode: MatchMode::DifferentRelationships,
            patterns: vec![pattern],
            where_clause: None,
            using_index: Vec::new(),
            using_join: Vec::new(),
            search: None,
        }]);
        assert_eq!(
            seen_use_graphs(&top),
            vec![
                "node_label".to_string(),
                "rel_type".to_string(),
                "quantified_node".to_string()
            ]
        );
    }

    #[test]
    fn walk_pattern_visits_compact_pattern_payloads_exactly_once() {
        // Regression: a lowered compact pattern carries both the `elements`
        // sequence and the cloned compact `nodes`/`rels` view (`lower_path`
        // in relate-front); walking both representations double-visits
        // every label_expr/properties payload. The post-rewrite precedence
        // reads the compact view once for a non-GPM shape.
        let node = NodePattern {
            variable: None,
            labels: Vec::new(),
            label_expr: Some(dynamic_label("node_label")),
            properties: None,
            prop_keys: Vec::new(),
            where_clause: None,
            force_scan: false,
        };
        let pattern = PathPattern {
            variable: None,
            subpath_variable: None,
            nodes: vec![node.clone()],
            rels: Vec::new(),
            elements: vec![PatternElement::Node(node)],
            where_clause: None,
            mode: None,
            selector: None,
            is_shortest_path_function: false,
        };
        let top = query(vec![Clause::Match {
            optional: false,
            match_mode: MatchMode::DifferentRelationships,
            patterns: vec![pattern],
            where_clause: None,
            using_index: Vec::new(),
            using_join: Vec::new(),
            search: None,
        }]);
        assert_eq!(seen_use_graphs(&top), vec!["node_label".to_string()]);
    }

    #[test]
    fn walk_query_descends_into_subqueries_and_next_stages() {
        // USE clauses nested in a CALL subquery, a COUNT expression
        // subquery (which `Expr::children` skips) and a NEXT stage are all
        // seen by the clause-tree walk.
        let mut top = query(vec![
            Clause::CallSubquery {
                query: Box::new(query(vec![use_clause("call_inner")])),
                optional: false,
                scope: crate::CallScope::Wildcard,
                in_transactions: None,
            },
            Clause::Return {
                distinct: false,
                group_by: None,
                items: vec![Projection {
                    expr: Expr::CountSubquery {
                        query: query(vec![use_clause("count_inner")]),
                    },
                    alias: None,
                    source_text: None,
                }],
                order: Vec::new(),
                skip: None,
                limit: None,
            },
        ]);
        top.next = Some(Box::new(query(vec![use_clause("next_stage")])));
        let mut seen: Vec<String> = Vec::new();
        walk_query(
            &top,
            &mut |clause| {
                if let Clause::Use { graph } = clause {
                    seen.push(format!("{graph:?}"));
                }
            },
            &mut |_| {},
        );
        assert_eq!(seen.len(), 3, "expected all three USE clauses: {seen:?}");
    }

    #[test]
    fn path_pattern_mentions_covers_bindings_predicates_and_compact_view() {
        let rel = |variable: Option<&str>, where_clause: Option<Expr>| RelPattern {
            variable: variable.map(Into::into),
            types: vec![],
            type_expr: None,
            direction: crate::Direction::Outgoing,
            properties: None,
            prop_keys: Vec::new(),
            var_length: false,
            min_hops: 1,
            max_hops: None,
            where_clause,
            quantified: false,
        };
        let node = |variable: Option<&str>,
                    label_expr: Option<LabelExpr>,
                    properties: Option<Expr>,
                    where_clause: Option<Expr>| NodePattern {
            variable: variable.map(Into::into),
            labels: vec![],
            label_expr,
            properties,
            prop_keys: Vec::new(),
            where_clause,
            force_scan: false,
        };
        let path = PathPattern {
            variable: None,
            subpath_variable: None,
            elements: vec![],
            nodes: vec![node(
                Some("n"),
                Some(LabelExpr::Dynamic {
                    expr: Box::new(var("lbl")),
                    quantifier: crate::DynamicLabelQuantifier::Default,
                }),
                Some(var("props")),
                Some(var("nw")),
            )],
            rels: vec![rel(Some("r"), Some(var("rw")))],
            where_clause: Some(Box::new(var("pw"))),
            mode: None,
            selector: None,
            is_shortest_path_function: false,
        };
        let mut out = HashSet::new();
        path_pattern_mentions(&path, &mut out);
        for expected in ["n", "r", "lbl", "props", "nw", "rw", "pw"] {
            assert!(out.contains(expected), "missing mention {expected}");
        }
        assert!(!out.contains("other"));

        // Elements view: quantified subpaths recurse.
        let path = PathPattern {
            variable: None,
            subpath_variable: None,
            elements: vec![PatternElement::Quantified(crate::QuantifiedPathPattern {
                subpath_variable: Some("q".into()),
                elements: vec![PatternElement::Node(node(None, None, None, None))],
                where_clause: Some(var("qw")),
                min: 1,
                max: None,
            })],
            nodes: vec![],
            rels: vec![],
            where_clause: None,
            mode: None,
            selector: None,
            is_shortest_path_function: false,
        };
        let mut out = HashSet::new();
        path_pattern_mentions(&path, &mut out);
        for expected in ["q", "qw"] {
            assert!(out.contains(expected), "missing mention {expected}");
        }
        assert!(!out.contains("n"));
    }
}