quarb 0.35.0

Query engine for arbors (arboreal graphs - tree-spanned or tree-dominated graphs)
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
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
//! The query AST.
//!
//! A query is a root-anchored sequence of navigation steps. Each step
//! is an axis (which direction to move), a matcher (which name to
//! keep), and an optional leaf anchor.

pub mod visit;

use crate::value::Value;
use globset::GlobMatcher;
use regex::Regex;

/// A parsed query: a union of navigation branches, then a pipeline of
/// stages applied to the union.
#[derive(Debug, Clone)]
pub struct Query {
    /// Prior expressions joined by `<=>`, evaluated into the context
    /// trace before this query's body; empty for a plain query.
    pub correlations: Vec<Query>,
    pub branches: Vec<Branch>,
    pub pipeline: Vec<Stage>,
    /// Where the correlations bind: the number of the driver's
    /// pipeline stages written before the first `<=>`. Those stages
    /// run first, the join binds against the capsae as they then
    /// stand (register, marks, node), and the rest of the pipeline
    /// follows — a join forks the capsa it leaves, as a hop does.
    pub join_at: usize,
    /// Meaningful on a correlation entry: `true` when the marker
    /// following it was `<=>?` — the outer join. The entry's
    /// context may then bind null: a current-side row that no
    /// tuple admits survives with this witness slot null, its
    /// trace-referencing predicates vacuous (the ON clause of a
    /// LEFT JOIN).
    pub outer: bool,
}

/// Where a navigation (a branch, a navigation stage, or an operand
/// path) starts. The parenthesized mark anchors mirror the
/// register's sigil law on the node side: `(name)` one mark by
/// name, `(N)` one by 1-based position, `(.)` the latest, `(@)`
/// ALL of the thread's marks — forking into one thread per marked
/// node — and `(@name)` every node marked under one (possibly
/// shadowed) name.
/// Every anchor resolves to a LIST of start nodes; the singular
/// forms yield at most one, and a miss yields nothing (never an
/// error).
#[derive(Debug, Clone)]
pub enum Anchor {
    /// Navigate from the current node (the default).
    Current,
    /// `^` — navigate from the arbor root. At the top level the
    /// two coincide; inside a subcontext body the anchor reaches
    /// back to the root (`.t(^/row @| count)` — the whole-table
    /// total from any capsa).
    Root,
    /// `(name)` — the most recent mark under `name` in scope.
    Mark(String),
    /// `(N)` — the mark at 1-based position `N` in the thread's
    /// mark array (names never shift positions; they are
    /// references layered on top).
    MarkIndex(usize),
    /// `(.)` — the most recent mark, named or not (the top of
    /// the mark array, mirroring the register's `$.`).
    MarkTop,
    /// `(@)` — every mark in the thread's array, in push order:
    /// the navigation forks into one thread per marked node,
    /// registers and marks carried (the sigil law's plural — it
    /// yields THREADS, not a list value; node identity never
    /// enters the value space).
    MarksAll,
    /// `(@name)` — every mark pushed under `name`, shadowed ones
    /// included, in push order; forks like `(@)`.
    MarksNamed(String),
    /// `((!expr))` — the node-id anchor: the node
    /// whose id the expression yields — a literal (`((!7))`), a
    /// value's origin (`((!$.v:::origin))`), a coordinate record
    /// (`:::%origin`, its `id` field), or a list of them, which
    /// forks like `((@))`. The coordinate stood on again — in this
    /// run or the next, since adapters mint ids deterministically.
    /// An id the adapter never minted yields no node.
    Id(Box<Operand>),
}

impl PartialEq for Anchor {
    fn eq(&self, other: &Anchor) -> bool {
        match (self, other) {
            (Anchor::Current, Anchor::Current)
            | (Anchor::Root, Anchor::Root)
            | (Anchor::MarkTop, Anchor::MarkTop)
            | (Anchor::MarksAll, Anchor::MarksAll) => true,
            (Anchor::Mark(a), Anchor::Mark(b)) | (Anchor::MarksNamed(a), Anchor::MarksNamed(b)) => {
                a == b
            }
            (Anchor::MarkIndex(a), Anchor::MarkIndex(b)) => a == b,
            // Two id anchors are equal when they are spelled alike.
            (Anchor::Id(a), Anchor::Id(b)) => {
                crate::unparse::operand_text(a) == crate::unparse::operand_text(b)
            }
            _ => false,
        }
    }
}

impl Eq for Anchor {}

/// One `||` branch: navigation and an optional projection.
#[derive(Debug, Clone)]
pub struct Branch {
    pub steps: Vec<PathElem>,
    pub projection: Option<Projection>,
    /// Where the branch starts navigating (see [`Anchor`]).
    pub anchor: Anchor,
}

/// A pipeline stage.
///
/// The execution unit here is the *capsa* — a node with a register
/// (its breadcrumbs) and a current topic (the scalar being worked on).
#[derive(Debug, Clone)]
pub enum Stage {
    /// `| f` — a per-capsa scalar transform of the topic.
    Func(FnCall),
    /// `| .` or `| .name` — push the topic onto the register.
    Push(Option<String>),
    /// `| .(expr)` or `| .name(expr)` — evaluate `expr` from the
    /// current node, reduce it to a scalar, set it as the topic, and
    /// push it (grouped aggregation).
    Subcontext {
        name: Option<String>,
        body: Box<Query>,
    },
    /// `| ::a * ::b` — a value expression evaluated against the
    /// capsa's node, set as the topic.
    Expr(Operand),
    /// `| .(::a * ::b)` or `| .name(::a * ::b)` — a value expression
    /// evaluated against the capsa's node, set as the topic and
    /// pushed (a computed column).
    ExprPush { name: Option<String>, expr: Operand },
    /// `@| f` — reduce the whole context's topics to a new context.
    /// Keyed aggregates (`sort_by`, `unique_by`, `min_by`, `max_by`,
    /// `top`, `bottom`) instead reorder or filter the capsae
    /// themselves, preserving nodes and registers.
    Agg(FnCall),
    /// `@| [n]` / `@| [a..b]` — positional selection of capsae from
    /// the whole context, with the same numbering as the
    /// navigation-side index and range predicates.
    Select(Predicate),
    /// `| [cond]` — a per-capsa filter: each capsa is kept iff the
    /// condition holds against its node.
    Filter(PredExpr),
    /// `| $.`, `| $.name`, `| @.` — recall a register value as the
    /// topic.
    Recall(RegRef),
    /// `| %%(...)` — the named register view (`%.`) enriched with
    /// the given fields: register fields first in the `%.` layout,
    /// the args after in written order, an arg overriding a
    /// register field that shares its name. The call carries the
    /// record convention, normalized to `rec`.
    RecordWith(FnCall),
    /// `| .%(...)` / `| .name%(...)` — build the record and push it
    /// in one step, anonymous or named, the topic set to the record
    ///; `.%%(...)` builds the enriched register view
    /// instead. The operand spelling `.name(%(...))` cannot exist: a
    /// record constructor in operand position would ride its first
    /// field as the topic, so the push carries the
    /// constructor itself.
    RecordPush {
        name: Option<String>,
        call: FnCall,
        enriched: bool,
    },
    /// `| ...` — the spread: fork a list topic into one thread per
    /// element (Cypher's UNWIND). Core syntax, not a function — it
    /// computes nothing, it changes how many threads exist. Null
    /// forks to nothing; a non-list scalar passes through; a record
    /// passes whole. The outer form `| ...?` differs in exactly one
    /// case: where the plain spread would fork to nothing (null or
    /// an empty list), it emits ONE thread with a null topic — the
    /// row-multiplying half of OPTIONAL MATCH / LEFT JOIN.
    Spread { outer: bool },
    /// `| .%` — the fields push: the topic is a record, and each of
    /// its fields is pushed as a named regula — the mirror image of
    /// `%.`, which reads the named regulae as a record. (`| .`
    /// files the record as ONE regula; the bare `.%` spreads it.)
    FieldsPush,
    /// `| /path…` — a navigation stage: resume navigation from each
    /// capsa's node (or from `^` / a `(name)` mark), fanning out
    /// into one capsa per result with registers and marks carried
    /// forward — the pipeline spelling of a path continuation. The
    /// steps behave in every respect (predicates, marks, groups,
    /// the navigation-predicate scope law) as if written in the
    /// path. Legal only in navigation mode — no live topic; after a
    /// projection, a push (`| .`) files the topic and navigation
    /// resumes. A trailing projection moves the thread to scalar
    /// mode exactly like a branch projection. Refused under `@|`
    /// and `$|`: hops are per-thread.
    Nav(Branch),
    /// `$| stage` — the iteration pipe, the scope-dual of `@|`: where
    /// `@|` hands its stage ALL topics at once (the context), `$|`
    /// hands it ONE element at a time, within the topic — per
    /// capsa, capsae unchanged. `$| f` maps, `$| [cond]` filters
    /// elements (`$_` = the element; a comprehension's WHERE),
    /// `$| [a..b]` slices. Null maps to null; a non-list topic is
    /// a singleton; an expanding inner stage flattens.
    Map(Box<Stage>),
    /// `.v(body){N}` — a quantified push: the push
    /// applied to the context again and again, each round reading
    /// the previous round's values (the snapshot rule) and filing
    /// one more regula on the same capsa — the iteration loop.
    /// `{N}` runs exactly N rounds; `{m;n}` at least m, then stops
    /// at a fixpoint (a round that repointed no name and changed
    /// no topic) or at n; `{m;}` likewise up to the quantifier
    /// bound.
    Repeat {
        stage: Box<Stage>,
        min: usize,
        max: Option<usize>,
    },
}

/// A reference into a capsa's register.
#[derive(Debug, Clone)]
pub enum RegRef {
    /// `$.` — the top (most recently pushed) regula.
    Top,
    /// `$.N` — the regula at 1-based index `N`.
    Index(usize),
    /// `$.name` — a named regula.
    Named(String),
    /// `@.` — the whole register, as a list.
    Whole,
    /// `%.` — the *named* view of the register, as a record: one
    /// field per named regula, in first-push order, carrying the
    /// latest value pushed under that name. Unnamed regulae are
    /// invisible to it (they stay reachable positionally).
    Record,
    /// `%%.` — the FULL register view, as a record: the named
    /// regulae exactly as `%.` renders them, plus every anonymous
    /// regula keyed `#N` by its 1-based register position (the
    /// same number `$.N` recalls it by). `#` cannot appear in a
    /// push name, so the keys cannot collide — names themselves
    /// MAY be numeric (the pivot macro writes data-valued column
    /// names).
    FullRecord,
}

/// A pipeline-stage function call: `name` or `name(arg, …)`.
#[derive(Debug, Clone)]
pub struct FnCall {
    pub name: String,
    pub args: Vec<Arg>,
}

/// One function argument: a literal, a value expression evaluated
/// per capsa against its node (the key of a keyed aggregate like
/// `sort_by(::age)`), or an offset range (`window(-2..0)`, either
/// end optional).
#[derive(Debug, Clone)]
pub enum Arg {
    Lit(Value),
    Expr(Operand),
    Range(Option<i64>, Option<i64>),
    /// A named option of the call (`csv(";")` carries its
    /// delimiter as `delimiter`), typed rather than a marker
    /// string a consumer has to recognise.
    Named {
        name: String,
        value: Value,
    },
}

/// The field name an expression carries on its own, for `record(...)`
/// auto-naming: the projection's key (`::href` → `href`,
/// `/a/b::c` → `c`, `:::name` → `name`, `;;;tag` → `tag`). Computed
/// expressions and bare paths carry none and need an explicit name.
pub fn auto_field_name(op: &Operand) -> Option<&str> {
    if let Operand::Outer(inner) = op {
        return auto_field_name(inner);
    }
    if let Operand::Recall(RegRef::Named(n)) = op {
        return Some(n);
    }
    // `:title` — a record's field derives its name as a projection
    // does: `group(:title)`, `%(:title, 'n', 1)`.
    if let Operand::Field { name, .. } = op {
        return Some(name);
    }
    if let Operand::ValueMeta { key, .. } = op {
        return Some(key);
    }
    // `<-link:.v` — a peer's named regula derives its name as a
    // recall does.
    if let Operand::PeerReg {
        reg: RegRef::Named(n),
        ..
    } = op
    {
        return Some(n);
    }
    if matches!(op, Operand::Ordinal) {
        return Some("ordinal");
    }
    if let Operand::Edge { projection } | Operand::Edges { projection } = op {
        return Some(match projection {
            Some(Projection::Property(Some(k))) => k,
            _ => {
                if matches!(op, Operand::Edge { .. }) {
                    "edge"
                } else {
                    "edges"
                }
            }
        });
    }
    let projection = match op {
        Operand::Rel { projection, .. } | Operand::Ctx { projection, .. } => projection.as_ref(),
        _ => None,
    }?;
    match projection {
        Projection::Property(Some(k)) => Some(k),
        Projection::CoreMeta(k) | Projection::AdapterMeta(k) => Some(k),
        Projection::Property(None) => None,
    }
}

/// A projection turning the node context into scalar values.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Projection {
    /// `::name` (a named property) or `::` (the default projection).
    Property(Option<String>),
    /// `:::key` — engine-computed core metadata.
    CoreMeta(String),
    /// `;;;key` — adapter-defined metadata.
    AdapterMeta(String),
}

/// One element of a navigation path: a plain hop, a parenthesized
/// path-pattern group (alternation + quantifier), or — inside a
/// group — a breadcrumb push.
#[derive(Debug, Clone)]
pub enum PathElem {
    /// `.name` (bare, node context) — mark the current node in the
    /// thread's mark array, under `name` when one is given; a bare
    /// `.` marks anonymously (the slot is still `((.N))`-addressable,
    /// and `((.))`/`((@))` see it). A name is an identifier or a
    /// quoted string — positions number themselves. Not a hop:
    /// navigation continues from the same node.
    Mark(Option<String>),
    Step(Step),
    Group(Group),
    /// `.(body)` / `.name(body)` inside a path pattern: evaluate the
    /// body from the path's current node (with `$-` in scope after
    /// an edge hop), reduce to a scalar, and push it onto the
    /// expansion path's register. A pattern that pushes yields one
    /// result per path, the register carried into the result capsa.
    Push {
        name: Option<String>,
        body: PushBody,
    },
}

/// A pattern push's body: a navigating sub-query (reduced like a
/// subcontext), or a plain value expression.
#[derive(Debug, Clone)]
pub enum PushBody {
    Query(Box<Query>),
    Expr(Operand),
}

/// `( alt | alt | … ) quant reach` — a path-pattern group. Expansion
/// follows simple-path semantics: within one expansion path no node
/// is visited twice (the start node included), and open-ended
/// quantifiers stop at the adapter's quantifier bound.
#[derive(Debug, Clone)]
pub struct Group {
    /// Alternative subpaths (at least one, each non-empty). Each
    /// repetition takes the union over the alternatives.
    pub alts: Vec<Vec<PathElem>>,
    pub quant: Quant,
    /// `[...]` expression predicates on the group's matches,
    /// applied per repetition count BEFORE reach — so
    /// `(...)+[P]?` is "the proximal satisfying P" (a shortest
    /// path search, stopping at the first tier with a survivor).
    /// Positional predicates are refused (no ordering across
    /// tiers). Mirrors the axis rule: matcher before reach.
    pub predicates: Vec<Predicate>,
    /// `<...>` trait filters on the group's matches, tested with
    /// the predicates (before reach): `(>token){2}<word>` is the
    /// second next token when it is a word. Multiple clauses are
    /// ANDed together.
    pub traits: Vec<TraitClause>,
    /// `?` / `!` after the quantifier: keep only the matches at the
    /// smallest / largest repetition count. Default keeps all.
    pub reach: Reach,
}

/// `{m,n}`-style repetition. `max` is `None` for the open-ended
/// forms, clamped to the adapter's quantifier bound at execution.
/// A plain group is `{1,1}`; `+` is `{1,}`; `*` is `{0,}`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Quant {
    pub min: usize,
    pub max: Option<usize>,
}

/// One navigation step.
#[derive(Debug, Clone)]
pub struct Step {
    pub axis: Axis,
    pub matcher: Matcher,
    /// `<...>` trait filters. Multiple clauses are ANDed together.
    pub traits: Vec<TraitClause>,
    /// `[...]` predicates. All must pass.
    pub predicates: Vec<Predicate>,
    /// Trailing `$`: keep the match only if it is a leaf (no children).
    pub leaf: bool,
}

/// A `[...]` filter on a step.
#[derive(Debug, Clone)]
pub enum Predicate {
    /// `[n]` — keep the `n`-th node (1-based; negative counts from
    /// the end, `[-1]` is the last) of the hop's result list from
    /// one source node, as filtered by the predicates to its left.
    /// Position among the hop's results, *not* sibling position —
    /// that is spelled `[:::index = n]`. Out of range selects
    /// nothing.
    Index(i64),
    /// `[a..b]` — keep the inclusive positional range of the hop's
    /// result list, under the same rules as `Index`. Either end may
    /// be omitted (`[2..]`, `[..3]`) or negative (`[2..-1]`); ends
    /// clamp to the list.
    Range(Option<i64>, Option<i64>),
    /// `[expr]` — keep nodes for which `expr` is truthy.
    Expr(PredExpr),
}

/// A boolean predicate expression.
#[derive(Debug, Clone)]
pub enum PredExpr {
    Or(Box<PredExpr>, Box<PredExpr>),
    And(Box<PredExpr>, Box<PredExpr>),
    Not(Box<PredExpr>),
    /// A comparison between two operands.
    Compare(Operand, CmpOp, Operand),
    /// A bare operand, taken for its truthiness (a structural path is
    /// truthy when it selects any node; a projection when its value is
    /// truthy).
    Truthy(Operand),
}

/// One segment of a pattern literal on `=` / `!=`:
/// quoted literal text and the glob star. The stars live outside
/// the quotes, so the quoted text is always literal and no escape
/// mechanism exists or is needed; strict alternation is enforced
/// by the parser (stars never touch).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PatSeg {
    Star,
    Lit(String),
}

/// An operand: a value relative to the current node, or a literal.
#[derive(Debug, Clone)]
pub enum Operand {
    /// A pattern literal — `*"sub"*`, `"app"*`, `*".gz"`,
    /// `*"a"*"b"*` — legal only as the right operand of `=` / `!=`
    /// (the parser assembles it from a glued star/string chain and
    /// refuses it anywhere else). The stars are syntax, not data: a
    /// value containing `*` never globs.
    Pattern(Vec<PatSeg>),
    /// A path from the current node — descending, ascending, sideways,
    /// or across a crosslink — with an optional projection. Empty
    /// `steps` + a projection is a projection of the
    /// current node (`::size`); non-empty `steps` navigate first
    /// (`/address::city`). The anchor mirrors the branch anchor:
    /// `[;;;short = ^/tags/*;;;short]` compares against a set
    /// gathered elsewhere (existentially, like any multi-valued
    /// operand); `(name)`/`(N)`/`(.)` start from one marked node;
    /// `(@)`/`(@name)` union the values gathered from every
    /// matching mark. An unset anchor yields no values.
    Rel {
        steps: Vec<PathElem>,
        projection: Option<Projection>,
        anchor: Anchor,
    },
    /// A literal string or number.
    Lit(Value),
    /// An arithmetic combination of two operands, each contributing
    /// its first value; operands without a numeric reading make the
    /// result null (spec: Value Expressions and Arithmetic).
    Arith {
        op: ArithOp,
        left: Box<Operand>,
        right: Box<Operand>,
    },
    /// Unary minus.
    Neg(Box<Operand>),
    /// A parenthesized sub-expression used as a value; a boolean
    /// group in operand position is its truth value.
    Group(Box<PredExpr>),
    /// `$.name` / `$.` — a register recall as an operand. Null when
    /// no capsa scope is in reach (e.g. navigation predicates).
    Recall(RegRef),
    /// `$_` — the topic: the current pipeline value.
    Topic,
    /// `base:name` — a field of a record value: the
    /// bottom rung of the colon ladder, a value's field below a
    /// node's property. A leading `:name` reads the topic's field.
    Field { base: Box<Operand>, name: String },
    /// `base:::key` — a value's provenance: the core-metadata rung
    /// after a register value or the topic, defined over the
    /// origins the value was read from (`source`, `instant`,
    /// `dpid`, `provenance`, `origins`, `elided`).
    ValueMeta { base: Box<Operand>, key: String },
    /// `X:.r` — the cross-capsa read: `at` is a node
    /// path (a `Rel`, a `Ctx`, or the served node); at each node it
    /// reaches, the regula `reg` of every capsa of the stage's
    /// *input* context standing there (the `@*` snapshot rule), one
    /// value per (node, capsa), in context order. No values where
    /// nobody stands; null outside a pipeline context.
    PeerReg { at: Box<Operand>, reg: RegRef },
    /// `%+` — the record of the last match's named groups (Perl's
    /// `%+`); the empty record outside any match.
    NamedCaptures,
    /// `@(a; b; c)` — the list literal: each item
    /// contributes every value it yields, so `@(/tags/*::)` gathers
    /// a path's values into one list. `@()` is the empty list.
    List(Vec<Operand>),
    /// `$ordinal` / `$ord` — the capsa's 1-based position in the
    /// current context. Ephemeral order (it changes with every
    /// sort, filter, and group), unlike the stable tree fact
    /// `:::index`.
    Ordinal,
    /// `$name` — a fragment parameter, legal only inside a `def`
    /// body; expansion replaces it with the invocation's argument
    /// form. Never reaches the executor.
    Param(String),
    /// `$1` … `$9` — a regex capture: the group captured by the last
    /// successful `=~` match in a per-capsa filter stage. Null until
    /// a filter has matched (and in navigation predicates, where no
    /// capsa exists).
    Capture(usize),
    /// `$$.name`, `$$_`, `$$ord` — the same capsa-scope
    /// operand, one scope *out*: the invoking capsa of the enclosing
    /// subcontext body. Each extra `$` steps out one more level;
    /// null where no enclosing scope exists.
    Outer(Box<Operand>),
    /// `$-` — the arrived-by edge: the crosslink hop the current
    /// thread most recently walked. Bare, it reads as the edge's
    /// label; projected (`$-::prop`), as the edge's own property
    /// (adapter-provided). Null where no edge has been walked — an
    /// edge-hop's own predicates and pattern stages after an edge
    /// hop are the defined scopes.
    Edge { projection: Option<Projection> },
    /// `@*` — the current context: every capsa of the stage's
    /// INPUT (the snapshot rule — a stage is the transition, so
    /// "the context" during its evaluation is what it received).
    /// Bare, the peers' topics as a list; projected (`@*::prop`,
    /// `:::`, `;;;`), the projection mapped over the peers' nodes.
    /// Null where no context exists (navigation predicates).
    Capsae { projection: Option<Projection> },
    /// `(expr | f @| g ...)` — an operand with a pipe tail. Stage
    /// semantics mirror the pipeline exactly: each value rides a
    /// pseudo-capsa (the enclosing node and register, the value as
    /// topic) through the ordinary stage machinery. `@|` treats a
    /// single list value as a context of its elements. Pushes and
    /// subcontexts refuse (a pipe inside an expression transforms a
    /// value; pushes belong to real capsae).
    Piped {
        expr: Box<Operand>,
        stages: Vec<Stage>,
    },
    /// `now()` — the invocation instant (spec: The Temporal
    /// Fragment, Determinism): one timeline point bound by the
    /// runner BEFORE evaluation begins, denoted identically by
    /// every occurrence in the query, displayed as UTC. The only
    /// nullary call operand; evaluation itself never reads a
    /// clock, and the runner lets the caller pin it (`qua --now`).
    Now,
    /// `(cond ? then : else)` — the conditional, parenthesized
    /// only (like every boolean-bearing operand). The condition is
    /// a full predicate expression, decided by truthiness; only the
    /// taken branch evaluates. Branches parse the conditional rule
    /// themselves, so chains need no inner parens:
    /// `(a < 1 ? 'low' : a < 10 ? 'mid' : 'high')`.
    Cond {
        cond: Box<PredExpr>,
        then: Box<Operand>,
        other: Box<Operand>,
    },
    /// `@-` — ALL the edges that reached this capsa on the walk's
    /// final hop, as a list (the sigil law: `$` one, `@` all). Bare,
    /// the labels; projected (`@-::prop`), each edge's property.
    /// Aggregated, never forking: a node reached by three crossings
    /// keeps one capsa whose `@-` has three elements. Empty where
    /// the walk's last element was not a hop.
    Edges { projection: Option<Projection> },
    /// `"text ${expr} text"` — an interpolated string: text segments
    /// and holes, each hole an expression evaluated in the current
    /// scope and spliced as text (null splices as empty).
    Interp(Vec<InterpSeg>),
    /// `(x ?= k1 ? r1 : k2 ? r2 : else)` — the value match: the
    /// scrutinee is evaluated once and compared against each arm's
    /// test in order (equality by the standard coercion; a regex
    /// arm tests `=~` instead); the first hit's result is the
    /// value, only that branch evaluating. The final expression —
    /// the first not followed by `?` — is the required else.
    Match {
        scrutinee: Box<Operand>,
        /// (test, is-regex, result) per arm, in document order.
        arms: Vec<(Operand, bool, Operand)>,
        other: Box<Operand>,
    },
    /// A correlation context reference, optionally navigated and
    /// projected: `$*N/child::proj` descends from the `N`-th prior
    /// context's bound node before projecting, exactly as `Rel` does
    /// from the current node. `index` is `None` for the current node
    /// (`$*`); empty `steps` projects the bound node in place
    /// (`$*1::limit`).
    Ctx {
        index: Option<usize>,
        steps: Vec<PathElem>,
        projection: Option<Projection>,
    },
}

/// One segment of an interpolated string.
#[derive(Debug, Clone)]
pub enum InterpSeg {
    Text(String),
    Expr(Operand),
    /// `${expr:?}` / `${expr:?message}` — the strict hole (ruling
    /// #34): refuses when the hole would splice nothing, with the
    /// optional message. Bash's own spelling for "error if unset".
    Strict(Operand, Option<String>),
    /// `${expr:-fallback}` — the default hole:
    /// `default(expr, fallback)`, bash-faithfully spelled. The
    /// fallback is a full value expression — quote a literal.
    Default(Operand, Operand),
}

/// An arithmetic operator (spec: Value Expressions and Arithmetic).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArithOp {
    /// `+`
    Add,
    /// `-`
    Sub,
    /// `*`
    Mul,
    /// `div` — always a float.
    Div,
    /// `idiv` — integer division, truncating toward zero.
    IDiv,
    /// `mod` — remainder; the sign follows the dividend.
    Mod,
}

/// A comparison operator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CmpOp {
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
    Match,
    NotMatch,
    /// `*=` — the left value contains the right as a substring.
    Contains,
}

/// One `<...>` trait filter. Alternatives inside it are ORed; a
/// node passes if it has at least one.
#[derive(Debug, Clone)]
pub struct TraitClause {
    pub alts: Vec<String>,
}

impl TraitClause {
    /// Whether a node satisfies this clause. A leading `!` negates
    /// a literal (impossible in a real trait name, so the marker
    /// cannot collide); `*` matches any node that has at least one
    /// trait, `!*` a traitless one.
    /// The test runs through a predicate — the adapter's
    /// `has_trait`, which may honour aliases — with `any` saying
    /// whether the node bears any trait at all (for `*` / `!*`).
    pub fn matches_with(&self, any: bool, has: impl Fn(&str) -> bool) -> bool {
        self.alts.iter().any(|alt| match alt.strip_prefix('!') {
            Some("*") => !any,
            Some(name) => !has(name),
            None if alt == "*" => any,
            None => has(alt),
        })
    }
}

/// The direction a step moves.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Axis {
    /// `/` — immediate children.
    Child,
    /// `//`, `//?`, `//!` — descendants at any depth.
    Descendant(Reach),
    /// `*//` — the universal search: every node of the arbor,
    /// the root and its descendants in document order, then the
    /// nodes outside the tree in the adapter's order. Written
    /// only as the head of a branch; it takes no reach.
    Universal,
    /// `\` — the immediate parent.
    Parent,
    /// `\\`, `\\?`, `\\!` — ancestors at any distance.
    Ancestor(Reach),
    /// `>` — the next sibling.
    NextSibling,
    /// `<` — the previous sibling.
    PrevSibling,
    /// `>>`, `>>?`, `>>!` — following siblings at any distance
    /// (all matches / proximal / distal match), in document
    /// order.
    FollowingSiblings(Reach),
    /// `<<`, `<<?`, `<<!` — preceding siblings at any distance,
    /// in document order; the proximal (`?`) is the latest one
    /// before the node.
    PrecedingSiblings(Reach),
    /// `->` — outgoing crosslink; the step's matcher matches the edge
    /// label, not the target's name.
    OutLink,
    /// `<-` — incoming crosslink; the matcher matches the edge label.
    InLink,
    /// `--` — either-direction crosslink: the union of `->` and
    /// `<-` under one matcher. The headless member of the arrow
    /// family — an edge followed without asserting its direction;
    /// on typed data (a value node vs. the rows referencing it)
    /// only one direction usually exists, so the spelling drops
    /// the direction claim the data never needed.
    BothLink,
    /// `::prop-->label` — resolve a cross-reference (the glued name
    /// is the reference label): the adapter maps
    /// `(node, property, label)` to a target node. With no property
    /// (`//a-->`, the bare arrow) the adapter names the node's own
    /// reference property — an html anchor's `href`.
    Resolve {
        property: Option<String>,
        label: Option<String>,
    },
    /// `<--label(SCOPE::prop)` — reverse resolution, the inverse of
    /// `-->`: every node whose `prop` resolves to the current node
    /// ("what points here?"). The argument names the referring
    /// nodes' property and, by its scope path, where to look; with
    /// no property, each candidate's own reference property; `::*`
    /// any property (a scope is then required). Bare `<--` takes the
    /// whole arbor, which an adapter must open to the walk.
    ReverseResolve {
        label: Option<String>,
        /// The scope path, root-anchored; `None` is the whole arbor.
        scope: Option<ScopePath>,
        property: RefProp,
    },
    /// `::a=>(SCOPE::b)` — the value match: the nodes of SCOPE whose
    /// `b` equals the current node's `a`, plain equality of two named
    /// properties, no resolution function, neither a key. One
    /// spelling in both directions; a 1-to-many hop.
    ValueMatch {
        property: String,
        scope: Option<ScopePath>,
        target: String,
    },
}

/// A root-anchored scope path inside an arrow's argument. Two
/// scopes are equal when they are spelled alike.
#[derive(Debug, Clone)]
pub struct ScopePath(pub Vec<PathElem>);

impl ScopePath {
    /// The scope as the canonical query text — what a model's
    /// `index SCOPE::prop;` declaration is matched against.
    pub fn text(&self) -> String {
        self.0.iter().map(crate::unparse::elem).collect()
    }
}
impl PartialEq for ScopePath {
    fn eq(&self, other: &ScopePath) -> bool {
        self.text() == other.text()
    }
}
impl Eq for ScopePath {}

/// Which property of a candidate a reverse resolution consults.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RefProp {
    /// `(::y)` — the named property.
    Named(String),
    /// `(SCOPE::*)` — any property the candidate has.
    Any,
    /// Omitted — the candidate's own reference property.
    Default,
}

/// For descendant/ancestor axes, which matches to keep by distance.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reach {
    /// All matches at any distance.
    All,
    /// `?` — only the proximal (nearest) match(es) (minimum distance).
    Proximal,
    /// `!` — only the distal (farthest) match(es) (maximum distance).
    Distal,
}

/// How a step selects among candidate nodes by name.
#[derive(Clone)]
pub enum Matcher {
    /// A literal name (`src`, `main.rs`).
    Name(String),
    /// A glob over the name (`*.rs`, `data.*`).
    Glob(GlobMatcher),
    /// A `~(...)` regex over the name.
    Regex(Regex),
    /// `*` — any name.
    Any,
    /// `.` inside a path pattern — matches any hop name (the pattern
    /// dot wildcard; unnamed nodes included, like `*`).
    Dot,
}

impl Matcher {
    /// Whether `name` satisfies this matcher.
    pub fn matches(&self, name: &str) -> bool {
        match self {
            Matcher::Name(n) => n == name,
            Matcher::Glob(g) => g.is_match(name),
            Matcher::Regex(r) => r.is_match(name),
            Matcher::Any | Matcher::Dot => true,
        }
    }
}

impl std::fmt::Debug for Matcher {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Matcher::Name(n) => write!(f, "Name({n:?})"),
            Matcher::Glob(g) => write!(f, "Glob({:?})", g.glob().glob()),
            Matcher::Regex(r) => write!(f, "Regex({:?})", r.as_str()),
            Matcher::Any => write!(f, "Any"),
            Matcher::Dot => write!(f, "Dot"),
        }
    }
}