Skip to main content

relate_ir/ast/
pattern.rs

1//! The pattern model: [`PathPattern`] and the element vocabulary it is
2//! built from ([`NodePattern`], [`RelPattern`], [`QuantifiedPathPattern`],
3//! [`PatternElement`]), the match/path modes and selectors, and the label
4//! and type expression families ([`LabelExpr`], [`TypeExpr`]). Split from
5//! [`super`] so the statement/clause vocabulary and the pattern vocabulary
6//! stay one concern per file; [`super`] re-exports every item, so the
7//! public path is unchanged (`ast::call` and `ast::expr` set the same
8//! precedent).
9
10use relate_names::{NamedToken, SmallName};
11
12use super::{Clause, Expr};
13
14/// The entry of `name` in a [`NamedToken`] list (a pattern's labels, types
15/// or `prop_keys`); a name the list does not spell reads by name
16/// (`Token::Unresolved`).
17pub fn named_token(list: &[NamedToken], name: &str) -> NamedToken {
18    list.iter()
19        .find(|(known, _)| *known == name)
20        .cloned()
21        .unwrap_or_else(|| relate_names::unresolved(SmallName::from_name(name)))
22}
23
24/// The token of the pattern-map key `name` from a pattern's `prop_keys`
25/// ([`named_token`] over that list).
26pub fn pattern_prop_key(keys: &[NamedToken], name: &str) -> NamedToken {
27    named_token(keys, name)
28}
29
30#[derive(Debug, Clone, PartialEq)]
31pub struct PathPattern {
32    /// Named path: `MATCH p = (a)-[]->(b)`.
33    pub variable: Option<SmallName>,
34    /// A second name bound to the same path value when the path's whole body
35    /// is a named parenthesized group (`MATCH p = ANY SHORTEST
36    /// (q = (a)-[]->(b))`). The executor binds it beside [`Self::variable`].
37    pub subpath_variable: Option<SmallName>,
38    /// Lossless GPM element sequence. Empty only for legacy callers that
39    /// construct the compact `nodes`/`rels` representation directly.
40    pub elements: Vec<PatternElement>,
41    pub nodes: Vec<NodePattern>,
42    pub rels: Vec<RelPattern>,
43    pub where_clause: Option<Box<Expr>>,
44    pub mode: Option<PathMode>,
45    pub selector: Option<PathSelector>,
46    pub is_shortest_path_function: bool,
47}
48
49#[derive(Debug, Clone, PartialEq)]
50pub enum PatternElement {
51    Node(NodePattern),
52    Relationship(RelPattern),
53    Quantified(QuantifiedPathPattern),
54}
55
56impl PathPattern {
57    /// Whether node `np` of this CREATE/MERGE path is a *reference* to an
58    /// existing binding of its name instead of a fresh declaration. Only a
59    /// bare variable beside a relationship reuses (`(a)-[:R]->(b)`, the
60    /// openCypher `(n)-[:R]->(n)` rows); a standalone node, or one that adds
61    /// labels or properties, declares — and when an enclosing scope bound
62    /// the name (a `FOREACH` body), the declaration shadows it. The one rule
63    /// the planner's CREATE binder and the executor's materializer share.
64    pub fn node_reuses_binding(&self, np: &NodePattern) -> bool {
65        !self.rels.is_empty() && !np.declares_shape()
66    }
67
68    /// The names this pattern binds its path value under, in declaration
69    /// order: the outer path variable, then a named parenthesized subpath.
70    /// The one enumeration every binder, scope walk and variable collector
71    /// consults — the two names name the same path value.
72    pub fn path_names(&self) -> impl Iterator<Item = &SmallName> {
73        [self.variable.as_ref(), self.subpath_variable.as_ref()]
74            .into_iter()
75            .flatten()
76    }
77
78    /// The pattern's boundary node patterns: the first and last elements,
79    /// when both are nodes. The one endpoint read every boundary consumer
80    /// (the frontier compile, the shortest-path static common-end rule)
81    /// consults; `None` for any other element sequence.
82    pub fn boundary_nodes(&self) -> Option<(&NodePattern, &NodePattern)> {
83        match (self.elements.first(), self.elements.last()) {
84            (Some(PatternElement::Node(start)), Some(PatternElement::Node(end))) => {
85                Some((start, end))
86            }
87            _ => None,
88        }
89    }
90
91    /// Every relationship variable the pattern binds, in element order,
92    /// recursing into quantified groups. Both views are consulted: the
93    /// compact `rels` view retains a var-length relationship's name, while
94    /// the GPM `elements` view quantifies it.
95    pub fn relationship_variables(&self) -> impl Iterator<Item = &SmallName> {
96        let mut names: Vec<&SmallName> = Vec::new();
97        collect_element_rel_vars(&self.elements, &mut names);
98        for rel in &self.rels {
99            if let Some(name) = rel.variable.as_ref() {
100                if !names.contains(&name) {
101                    names.push(name);
102                }
103            }
104        }
105        names.into_iter()
106    }
107
108    /// Whether the pattern binds a path value under any of its names (the
109    /// outer path variable or a named parenthesized subpath).
110    pub fn has_path_name(&self) -> bool {
111        self.path_names().next().is_some()
112    }
113
114    /// Whether `nodes`/`rels` and `elements` are in 1-to-1 alternating
115    /// correspondence (no quantified elements, no path mode, selector, or
116    /// path-level `WHERE`). True for plain patterns and for fixed-length
117    /// patterns whose only GPM feature is inline node/relationship `WHERE`
118    /// predicates — allowing `WHERE` folding and orientation reversal while
119    /// keeping `nodes`/`rels` and `elements` in sync.
120    pub fn has_compact_alternating_elements(&self) -> bool {
121        let f = self.classify_features();
122        !f.path_level_gpm && f.compact_alternating
123    }
124
125    /// Whether this path must be matched by the GPM engine rather than the
126    /// compact node/rel walker: either the compact `nodes`/`rels`
127    /// representation was cleared at lowering (non-alternating or quantified
128    /// element sequence), or GPM-only features are present (path mode, path
129    /// selector, path-level or element-level predicates).
130    pub fn needs_gpm(&self) -> bool {
131        let f = self.classify_features();
132        f.path_level_gpm || !f.compact_alternating || f.inline_where
133    }
134
135    fn classify_features(&self) -> PatternFeatures {
136        let path_level_gpm = self.nodes.is_empty()
137            || self.mode.is_some()
138            || self.selector.is_some()
139            || self.where_clause.is_some();
140        let compact_alternating = self.elements.is_empty()
141            || (self.elements.len() == self.nodes.len() + self.rels.len()
142                && self
143                    .elements
144                    .iter()
145                    .enumerate()
146                    .all(|(i, element)| match element {
147                        PatternElement::Node(_) => i % 2 == 0,
148                        PatternElement::Relationship(rel) => i % 2 == 1 && !rel.quantified,
149                        PatternElement::Quantified(_) => false,
150                    }));
151        let inline_where = self.elements.iter().any(|element| match element {
152            PatternElement::Node(node) => node.where_clause.is_some(),
153            PatternElement::Relationship(rel) => rel.where_clause.is_some(),
154            PatternElement::Quantified(_) => false,
155        }) || self.nodes.iter().any(|n| n.where_clause.is_some())
156            || self.rels.iter().any(|r| r.where_clause.is_some());
157        PatternFeatures {
158            path_level_gpm,
159            compact_alternating,
160            inline_where,
161        }
162    }
163}
164
165/// A one-node, relationship-free pattern whose node is the whole node
166/// population ([`PathPattern::whole_population_node`]). The path variable
167/// and the `USING SCAN` flag are facets the caller reads or refuses: the
168/// executor's counts ignore both, the planner's scan-order rewrite
169/// refuses both.
170#[derive(Debug, Clone, Copy)]
171pub struct WholePopulationNode<'a> {
172    pub variable: &'a SmallName,
173    /// The pattern's own path variable (`p = (n)`), if any.
174    pub path_variable: Option<&'a SmallName>,
175    /// `USING SCAN` on the node.
176    pub force_scan: bool,
177}
178
179impl PathPattern {
180    /// The whole-population node of a one-node, relationship-free pattern
181    /// the compact walker owns (no [`Self::needs_gpm`] feature) whose node
182    /// is named and [unconstrained](NodePattern::is_unconstrained). `None`
183    /// for an anonymous node and every other shape.
184    pub fn whole_population_node(&self) -> Option<WholePopulationNode<'_>> {
185        let ([node], true) = (&self.nodes[..], self.rels.is_empty()) else {
186            return None;
187        };
188        if self.needs_gpm() || !node.is_unconstrained() {
189            return None;
190        }
191        Some(WholePopulationNode {
192            variable: node.variable.as_ref()?,
193            path_variable: self.variable.as_ref(),
194            force_scan: node.force_scan,
195        })
196    }
197}
198
199/// A plain `MATCH` clause ([`Clause::plain_match`]): its patterns, and
200/// whether it carries `USING INDEX` / `USING JOIN` hints (a facet: the
201/// executor's recognizers ignore hints, the scan-order rewrite refuses them).
202#[derive(Debug, Clone, Copy)]
203pub struct PlainMatch<'a> {
204    pub patterns: &'a [PathPattern],
205    pub hinted: bool,
206}
207
208impl Clause {
209    /// The clause-level plain-`MATCH` gate: a non-optional `MATCH` in the
210    /// default relationship mode, no `WHERE`, no `SEARCH`. The pattern-level
211    /// gates stay with each caller.
212    pub fn plain_match(&self) -> Option<PlainMatch<'_>> {
213        let Clause::Match {
214            optional: false,
215            match_mode: MatchMode::DifferentRelationships,
216            patterns,
217            where_clause: None,
218            search: None,
219            using_index,
220            using_join,
221        } = self
222        else {
223            return None;
224        };
225        Some(PlainMatch {
226            patterns,
227            hinted: !using_index.is_empty() || !using_join.is_empty(),
228        })
229    }
230}
231
232#[derive(Clone, Copy)]
233struct PatternFeatures {
234    path_level_gpm: bool,
235    compact_alternating: bool,
236    inline_where: bool,
237}
238
239/// Collect the relationship variables of a pattern element list, recursing
240/// into quantified groups ([`PathPattern::relationship_variables`]).
241fn collect_element_rel_vars<'a>(elements: &'a [PatternElement], out: &mut Vec<&'a SmallName>) {
242    for element in elements {
243        match element {
244            PatternElement::Relationship(rel) => {
245                if let Some(name) = rel.variable.as_ref() {
246                    if !out.contains(&name) {
247                        out.push(name);
248                    }
249                }
250            }
251            PatternElement::Quantified(qpp) => collect_element_rel_vars(&qpp.elements, out),
252            PatternElement::Node(_) => {}
253        }
254    }
255}
256
257#[derive(Debug, Clone, PartialEq)]
258pub struct QuantifiedPathPattern {
259    pub subpath_variable: Option<SmallName>,
260    pub elements: Vec<PatternElement>,
261    pub where_clause: Option<Expr>,
262    pub min: u32,
263    pub max: Option<u32>,
264}
265
266impl QuantifiedPathPattern {
267    /// The inner rel when this element is exactly a quantified var-length
268    /// relationship — one plain one-hop rel between two implicit anonymous
269    /// boundary nodes, no subpath variable, no group predicate: the form
270    /// every `-[r:T*m..n]-` spelling lowers to (LABS-661), with the hop
271    /// bounds on the quantifier (`min`/`max`). The rel's `quantified`
272    /// marker (the postfix `->{m,n}` spelling's origin, carrying its
273    /// per-edge inline-WHERE semantics) does not change the shape. Any
274    /// other quantified shape (a parenthesized group with named inner
275    /// elements) answers `None`. The one decoder for this shape — the
276    /// shortest-route guard, the plan-text renderer, and the group-name
277    /// origin rules all consult it.
278    pub fn implicit_var_length_rel(&self) -> Option<&RelPattern> {
279        if self.subpath_variable.is_some() || self.where_clause.is_some() {
280            return None;
281        }
282        let [PatternElement::Node(head), PatternElement::Relationship(rel), PatternElement::Node(tail)] =
283            self.elements.as_slice()
284        else {
285            return None;
286        };
287        let implicit = |node: &NodePattern| {
288            node.variable.is_none()
289                && node.labels.is_empty()
290                && node.label_expr.is_none()
291                && node.properties.is_none()
292                && node.where_clause.is_none()
293        };
294        if !implicit(head) || !implicit(tail) || rel.var_length {
295            return None;
296        }
297        Some(rel)
298    }
299}
300
301#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
302pub enum MatchMode {
303    #[default]
304    DifferentRelationships,
305    RepeatableElements,
306}
307
308#[derive(Debug, Clone, Copy, PartialEq, Eq)]
309pub enum PathMode {
310    Walk,
311    Trail,
312    Acyclic,
313    Simple,
314}
315
316#[derive(Debug, Clone, PartialEq)]
317pub enum PathCount {
318    Literal(u32),
319    Parameter(String),
320}
321
322#[derive(Debug, Clone, PartialEq)]
323pub enum PathSelector {
324    All,
325    Any(Option<PathCount>),
326    AnyShortest,
327    AllShortest,
328    Shortest {
329        count: Option<PathCount>,
330        group: bool,
331    },
332}
333
334#[derive(Debug, Clone, PartialEq)]
335pub struct NodePattern {
336    pub variable: Option<SmallName>,
337    /// Static conjunction, retained for catalog/index candidate selection,
338    /// each name beside its token (`Unresolved` until planning resolves the
339    /// pattern against a store, ADR-0541).
340    ///
341    /// An empty list is ambiguous on its own: it means both "the node
342    /// names no label" and "the label expression is not a plain
343    /// conjunction" (a disjunction, negation or wildcard keeps its shape
344    /// only in `label_expr`). A consumer that must tell the two apart reads
345    /// `label_expr`; one that only wants candidate labels reads this.
346    pub labels: Vec<NamedToken>,
347    /// Complete CIP-14/CIP-156 label expression.
348    pub label_expr: Option<LabelExpr>,
349    pub properties: Option<Expr>,
350    /// The literal keys of `properties`, each beside its token
351    /// (`Unresolved` until planning resolves them, ADR-0541). A key the
352    /// map does not spell literally has no entry here and reads by name.
353    pub prop_keys: Vec<NamedToken>,
354    pub where_clause: Option<Expr>,
355    /// `USING SCAN <var>:<Label>`: candidate selection must take the
356    /// label scan, never an index seek. Unlike the other hints this is not
357    /// merely a plan preference — an indexed equality seek and a scan
358    /// genuinely answer differently for a zoned-datetime DST overlap (the
359    /// index keys instant plus zone, `=` keys the wall clock), which the
360    /// measured acceptance suite pins.
361    pub force_scan: bool,
362}
363
364impl NodePattern {
365    /// Whether the node spells a label requirement or a property map: the
366    /// shape that makes an element variable a *declaration* rather than a
367    /// bare reference to an existing binding. The one predicate behind
368    /// [`PathPattern::node_reuses_binding`].
369    pub fn declares_shape(&self) -> bool {
370        !self.labels.is_empty() || self.label_expr.is_some() || self.properties.is_some()
371    }
372
373    /// Whether the node constrains nothing the label/property half could
374    /// check: [`Self::declares_shape`] is false and there is no inline
375    /// `WHERE` — the whole node population. The one predicate behind the
376    /// executor's whole-count arm and [`PathPattern::whole_population_node`].
377    pub fn is_unconstrained(&self) -> bool {
378        !self.declares_shape() && self.where_clause.is_none()
379    }
380
381    /// Whether the label requirement is static: no label expression, or a
382    /// plain conjunction (so `labels` holds its operands, except that a
383    /// nested conjunction keeps its shape only in `label_expr`). The one
384    /// canonical predicate the executor's seek, fold and shortest-path
385    /// guards read; an anonymous node (no requirement) answers `true`.
386    pub fn has_static_labels(&self) -> bool {
387        self.label_expr
388            .as_ref()
389            .is_none_or(LabelExpr::is_static_conjunction)
390    }
391
392    /// The implicit anonymous boundary node of a synthesized quantified
393    /// group — anonymous and unconstrained, exactly what `(()-[r:T]-()){m,n}`
394    /// lowers for its `()`. The one spelling of the shape, at the type's
395    /// home: the front's lowering and the executor's NFA compile and GPM
396    /// anonymous start both build it.
397    pub fn anonymous() -> Self {
398        NodePattern {
399            variable: None,
400            labels: Vec::new(),
401            label_expr: None,
402            properties: None,
403            prop_keys: Vec::new(),
404            where_clause: None,
405            force_scan: false,
406        }
407    }
408
409    /// The label names, without their tokens.
410    pub fn label_names(&self) -> impl Iterator<Item = &SmallName> {
411        self.labels.iter().map(|(name, _)| name)
412    }
413
414    /// The disjunction arms of the pattern's label expression (LABS-1083)
415    /// — the one accessor every consumer of the folded shape reads (the
416    /// executor's union serve, the plan narration, the warning's scan
417    /// shape), so the derivation is spelled once at the type's home.
418    /// `None` for every other shape: no label expression, a plain
419    /// conjunction, or a shape the classifier declines.
420    pub fn static_disjunction_arms(&self) -> Option<DisjunctionArms<'_>> {
421        self.label_expr.as_ref()?.static_disjunction_arms()
422    }
423}
424
425#[derive(Debug, Clone, PartialEq)]
426pub struct RelPattern {
427    pub variable: Option<SmallName>,
428    /// Static disjunction, retained for typed-CSR candidate selection, each
429    /// name beside its token (`Unresolved` until planning resolves the
430    /// pattern against a store, ADR-0541).
431    pub types: Vec<NamedToken>,
432    /// Complete CIP-14/CIP-156 relationship type expression.
433    pub type_expr: Option<LabelExpr>,
434    pub direction: Direction,
435    pub properties: Option<Expr>,
436    /// The literal keys of `properties`, each beside its token — see
437    /// [`NodePattern::prop_keys`].
438    pub prop_keys: Vec<NamedToken>,
439    pub var_length: bool,
440    pub min_hops: u32,
441    pub max_hops: Option<u32>,
442    pub where_clause: Option<Expr>,
443    pub quantified: bool,
444    /// The type list was written with the deprecated `|:` separator
445    /// (`[:R|:T]`): the one fact the deprecation notification reads.
446    pub legacy_type_separator: bool,
447}
448
449impl RelPattern {
450    /// The type names, without their tokens.
451    pub fn type_names(&self) -> impl Iterator<Item = &SmallName> {
452        self.types.iter().map(|(name, _)| name)
453    }
454
455    /// Whether `type_expr` spells exactly the static `types` list — a
456    /// single label, or an `Or` of the same labels in the same order
457    /// (LABS-801). Such an expression is fully applied by any walk that
458    /// filters on `types`, so per-edge admission need not re-evaluate it.
459    /// Anything else — a negated or conjunctive expression, or a list the
460    /// expression does not spell (the CREATE/MERGE rewrite sets `types`
461    /// from a resolved type list beside an `And` expression, exactly that
462    /// case) — answers `false` and keeps the per-edge evaluation.
463    pub fn type_expr_is_static_types(&self) -> bool {
464        match self.type_expr.as_ref() {
465            Some(LabelExpr::Label(label)) => self.types.len() == 1 && label == &self.types[0].0,
466            Some(LabelExpr::Or(items)) => {
467                items.len() == self.types.len()
468                    && items
469                        .iter()
470                        .zip(&self.types)
471                        .all(|(item, ty)| matches!(item, LabelExpr::Label(label) if *label == ty.0))
472            }
473            _ => false,
474        }
475    }
476
477    /// Whether the `types` list is the complete relationship-type filter:
478    /// `type_expr` is absent (an untyped hop carries an empty list, which
479    /// means "every type"), or it spells exactly the non-empty static
480    /// list. An empty `Or` is a filter that matches nothing, not the
481    /// any-type set, so it answers `false`.
482    pub fn types_are_complete_filter(&self) -> bool {
483        self.type_expr.is_none() || (self.type_expr_is_static_types() && !self.types.is_empty())
484    }
485}
486
487#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
488pub enum Direction {
489    Outgoing,
490    Incoming,
491    Both,
492}
493
494impl Direction {
495    /// The opposite traversal direction (`Both` flips to itself).
496    pub fn flip(self) -> Direction {
497        match self {
498            Direction::Outgoing => Direction::Incoming,
499            Direction::Incoming => Direction::Outgoing,
500            Direction::Both => Direction::Both,
501        }
502    }
503}
504
505#[derive(Debug, Clone, PartialEq)]
506pub enum LabelExpr {
507    Label(SmallName),
508    Wildcard,
509    Dynamic {
510        expr: Box<Expr>,
511        quantifier: DynamicLabelQuantifier,
512    },
513    Not(Box<LabelExpr>),
514    And(Vec<LabelExpr>),
515    Or(Vec<LabelExpr>),
516}
517
518#[derive(Debug, Clone, Copy, PartialEq, Eq)]
519pub enum DynamicLabelQuantifier {
520    Default,
521    All,
522    Any,
523}
524
525#[derive(Debug, Clone, Copy, PartialEq, Eq)]
526pub enum QuantifierKind {
527    All,
528    Any,
529    None,
530    Single,
531}
532
533impl LabelExpr {
534    /// Static conjunction: a single label or an `And`-chain of static labels.
535    pub fn is_static_conjunction(&self) -> bool {
536        match self {
537            LabelExpr::Label(_) => true,
538            // An empty conjunction is degenerate, not static — and it
539            // is constructible: the parser never builds one, but
540            // exec/create.rs's post-resolution synthesis can when a
541            // dynamic label list resolves empty. Callers (node_ok's
542            // label arm, has_static_labels) must not trust a
543            // construction invariant, so `And([])` declines here and
544            // routes to the dynamic/scan arms instead (PR #359
545            // F-2-6/F-3-2).
546            LabelExpr::And(items) => {
547                !items.is_empty() && items.iter().all(LabelExpr::is_static_conjunction)
548            }
549            _ => false,
550        }
551    }
552
553    /// Static disjunction: a single label or an `Or`-chain of static labels.
554    pub fn is_static_disjunction(&self) -> bool {
555        match self {
556            LabelExpr::Label(_) => true,
557            // The degenerate-case twin of the `And` arm above: an empty
558            // `Or` is constructible the same way and declines here so
559            // no caller trusts a construction invariant (PR #359
560            // F-3-1/F-3-3).
561            LabelExpr::Or(items) => {
562                !items.is_empty() && items.iter().all(LabelExpr::is_static_disjunction)
563            }
564            _ => false,
565        }
566    }
567
568    /// The per-arm borrowed views of a disjunction-bearing label
569    /// expression (LABS-1083): the two shapes the planner's disjunction
570    /// fold and the parsed `(p:A|B)` produce. `Or([A, B])` answers one
571    /// view — empty base, disjuncts `[A, B]` — each disjunct its own arm;
572    /// `And([C, Or([A, B])])` (the pattern's own conjunction carried
573    /// beside the folded `Or`) answers base `[C]`, disjuncts `[A, B]` —
574    /// every arm the shared conjunction plus one disjunct. Every arm is a
575    /// static conjunction, and the union of the arms' conjunctions is
576    /// equivalent to the expression, so a consumer that serves each arm's
577    /// conjunction and unions the answers (deduplicated) serves the
578    /// expression. `None` for everything else: no disjunction (a plain
579    /// label or conjunction), a nested `Or`, an `And` of several `Or`s (a
580    /// DNF no producer builds), an empty `Or`, or any wildcard, dynamic,
581    /// or negated leaf. The arm-extraction twin of
582    /// [`is_static_conjunction`](Self::is_static_conjunction):
583    /// conjunction consumers read a node's retained `labels`, disjunction
584    /// consumers read this.
585    ///
586    /// The views borrow: arm *i* is
587    /// [`DisjunctionArms::arms`](DisjunctionArms::arm) — the base's names
588    /// plus one disjunct, iterated over the expression's own names —
589    /// never a per-disjunct `Vec` clone of the shared conjunction (the
590    /// O(n·k) copies an owned per-arm answer would pay for an O(n+k)
591    /// expression).
592    pub fn static_disjunction_arms(&self) -> Option<DisjunctionArms<'_>> {
593        // The shared conjunction every arm carries: empty under a bare
594        // `Or`, the `And`'s plain labels beside a folded one. Each arm
595        // of this match yields the `Or`'s own item slice directly — the
596        // shape is discriminated once here, never re-matched below.
597        let (base, items): (Vec<&SmallName>, &[LabelExpr]) = match self {
598            LabelExpr::Or(items) => (Vec::new(), items),
599            LabelExpr::And(items) => {
600                // A plain conjunction carries no `Or` — decline before
601                // building the base list, the per-funnel-call allocation
602                // the LABS-1083 review flags (the fold's shape always
603                // spells a non-conjunction `And`).
604                if self.is_static_conjunction() {
605                    return None;
606                }
607                // Two lists built in one pass: the plain labels, and the
608                // at-most-one `Or` (the fold appends exactly one; a second
609                // is a DNF this classification declines).
610                let mut base: Vec<&SmallName> = Vec::new();
611                let mut or = None;
612                for item in items {
613                    match item {
614                        LabelExpr::Label(label) => base.push(label),
615                        LabelExpr::Or(items) if or.is_none() => or = Some(items.as_slice()),
616                        _ => return None,
617                    }
618                }
619                (base, or?)
620            }
621            _ => return None,
622        };
623        // The degenerate empty `Or` is constructible (the conjunction
624        // classifier's twin decline) and answers no arm.
625        if items.is_empty() {
626            return None;
627        }
628        // Every disjunct a plain label — a nested `Or`, wildcard, dynamic,
629        // or negated leaf declines the whole classification. The disjuncts
630        // collect as borrowed names (never a per-disjunct `Vec` clone of
631        // the base); each arm is the base plus one of these, composed per
632        // consumer use by [`DisjunctionArms::arms`].
633        let disjuncts: Option<Vec<&SmallName>> = items
634            .iter()
635            .map(|item| match item {
636                LabelExpr::Label(label) => Some(label),
637                _ => None,
638            })
639            .collect();
640        Some(DisjunctionArms {
641            base,
642            disjuncts: disjuncts?,
643        })
644    }
645}
646
647/// The borrowed per-arm views of a disjunction-bearing label expression
648/// (LABS-1083): the shared conjunction base every arm carries (empty
649/// under a bare `Or`) and the disjunct labels — arm *i* is the base plus
650/// disjunct *i*. Constructed only by
651/// [`LabelExpr::static_disjunction_arms`](LabelExpr::static_disjunction_arms)
652/// and [`DisjunctionArms::single`](Self::single) (the single-label view
653/// the keyed narration unifies with the disjunction's arms); the arms
654/// borrow the expression's own names, so serving them costs no
655/// per-disjunct clone of the shared conjunction.
656#[derive(Debug, Clone, PartialEq)]
657pub struct DisjunctionArms<'a> {
658    /// The shared conjunction labels every arm carries.
659    base: Vec<&'a SmallName>,
660    /// The disjunct labels — one per arm: arm *i* is `base` plus
661    /// `disjuncts[i]`.
662    disjuncts: Vec<&'a SmallName>,
663}
664
665impl<'a> DisjunctionArms<'a> {
666    /// The single-label arm: one arm, no shared base — the view shape a
667    /// lone static label and a disjunction's arms read through alike, so
668    /// a consumer that serves per arm serves both without a second
669    /// spelling (LABS-1083's keyed narration unifies them).
670    pub fn single(label: &'a SmallName) -> Self {
671        DisjunctionArms {
672            base: Vec::new(),
673            disjuncts: vec![label],
674        }
675    }
676
677    /// The shared conjunction labels every arm carries — empty under a
678    /// bare `Or`, the `And`'s plain labels beside a folded one.
679    pub fn base(&self) -> &[&'a SmallName] {
680        &self.base
681    }
682
683    /// The disjunct labels, statement order — arm *i* is
684    /// [`base`](Self::base) plus `disjuncts()[i]`.
685    pub fn disjuncts(&self) -> &[&'a SmallName] {
686        &self.disjuncts
687    }
688
689    /// The arm count — one per disjunct; a capacity hint, never an
690    /// iteration protocol (the arms are iterated, not indexed).
691    pub fn len(&self) -> usize {
692        self.disjuncts.len()
693    }
694
695    /// Whether the view answers no arm — no live construction does (the
696    /// classifier declines an empty `Or`); held beside [`len`](Self::len)
697    /// for the slice-shaped API.
698    pub fn is_empty(&self) -> bool {
699        self.disjuncts.is_empty()
700    }
701
702    /// Every arm's labels, one iterator per arm — each arm is the shared
703    /// base plus one disjunct, iterated over the expression's own
704    /// borrowed names, never a per-disjunct `Vec`. The natural
705    /// iteration protocol: no unchecked arm index for a consumer
706    /// pattern whose only shape is "every arm".
707    pub fn arms(&self) -> impl Iterator<Item = impl Iterator<Item = &'a SmallName> + '_> + '_ {
708        self.disjuncts
709            .iter()
710            .map(|disjunct| self.base.iter().copied().chain(std::iter::once(*disjunct)))
711    }
712}
713
714#[derive(Debug, Clone, PartialEq)]
715pub enum TypeExpr {
716    Predefined {
717        kind: PredefinedType,
718        not_null: bool,
719    },
720    List {
721        element: Box<TypeExpr>,
722        not_null: bool,
723    },
724    PropertyValue {
725        not_null: bool,
726    },
727    Union(Vec<TypeExpr>),
728    Vector {
729        coord: Option<String>,
730        dimension: Option<i64>,
731        not_null: bool,
732    },
733}
734
735#[derive(Debug, Clone, Copy, PartialEq, Eq)]
736pub enum PredefinedType {
737    Nothing,
738    Null,
739    Any,
740    Boolean,
741    String,
742    Integer,
743    Float,
744    Date,
745    Duration,
746    Point,
747    LocalTime,
748    ZonedTime,
749    LocalDateTime,
750    ZonedDateTime,
751    Node,
752    Relationship,
753    Path,
754    Map,
755    /// CIP-246.
756    Uuid,
757}
758
759impl PredefinedType {
760    /// The type's Cypher keyword — the one type→text map, so a diagnostic
761    /// that echoes a type expression (`x IS :: STRING`) spells the keyword
762    /// the query wrote instead of a `Debug` rendering.
763    pub fn as_str(self) -> &'static str {
764        match self {
765            PredefinedType::Nothing => "NOTHING",
766            PredefinedType::Null => "NULL",
767            PredefinedType::Any => "ANY",
768            PredefinedType::Boolean => "BOOLEAN",
769            PredefinedType::String => "STRING",
770            PredefinedType::Integer => "INTEGER",
771            PredefinedType::Float => "FLOAT",
772            PredefinedType::Date => "DATE",
773            PredefinedType::Duration => "DURATION",
774            PredefinedType::Point => "POINT",
775            PredefinedType::LocalTime => "LOCAL TIME",
776            PredefinedType::ZonedTime => "ZONED TIME",
777            PredefinedType::LocalDateTime => "LOCAL DATETIME",
778            PredefinedType::ZonedDateTime => "ZONED DATETIME",
779            PredefinedType::Node => "NODE",
780            PredefinedType::Relationship => "RELATIONSHIP",
781            PredefinedType::Path => "PATH",
782            PredefinedType::Map => "MAP",
783            PredefinedType::Uuid => "UUID",
784        }
785    }
786}
787
788#[cfg(test)]
789mod tests {
790    //! LABS-1083's arm-classifier pins: the two fold shapes answer their
791    //! per-arm views (base plus one disjunct each, borrowed), and every
792    //! other shape declines — the same decline vocabulary
793    //! `is_static_conjunction` keeps for its shapes.
794
795    use super::{Direction, DisjunctionArms, LabelExpr, RelPattern, SmallName};
796
797    fn label(name: &str) -> LabelExpr {
798        LabelExpr::Label(SmallName::from_name(name))
799    }
800
801    /// One view's arms, each arm's names rendered and collected — the
802    /// readable form the assertions compare.
803    fn rendered(arms: &DisjunctionArms<'_>) -> Vec<Vec<String>> {
804        arms.arms()
805            .map(|arm| arm.map(|label| label.to_string()).collect())
806            .collect()
807    }
808
809    /// The two fold shapes answer their per-arm views: a bare `Or` is one
810    /// arm per disjunct over no shared base, and an `And` carrying the
811    /// pattern's own conjunction beside the folded `Or` is every arm that
812    /// base plus one disjunct — the union of the arms equivalent to the
813    /// expression.
814    #[test]
815    fn the_fold_shapes_answer_their_per_arm_views() {
816        let bare = LabelExpr::Or(vec![label("Model"), label("Source")]);
817        let arms = bare.static_disjunction_arms().expect("the bare Or folds");
818        assert_eq!(
819            rendered(&arms),
820            vec![vec!["Model".to_string()], vec!["Source".to_string()]]
821        );
822        assert!(arms.base().is_empty());
823        assert_eq!(arms.len(), 2);
824
825        let nested = LabelExpr::And(vec![
826            label("C"),
827            LabelExpr::Or(vec![label("A"), label("B")]),
828        ]);
829        let arms = nested.static_disjunction_arms().expect("the And folds");
830        assert_eq!(
831            rendered(&arms),
832            vec![
833                vec!["C".to_string(), "A".to_string()],
834                vec!["C".to_string(), "B".to_string()]
835            ]
836        );
837        assert_eq!(
838            arms.base(),
839            vec![&SmallName::from_name("C")],
840            "the shared conjunction every arm carries"
841        );
842    }
843
844    /// Everything else declines: no disjunction (a plain label or
845    /// conjunction), a nested `Or`, an `And` of several `Or`s, an empty
846    /// `Or`, and any wildcard, dynamic, or negated leaf.
847    #[test]
848    fn every_other_shape_declines() {
849        assert!(label("A").static_disjunction_arms().is_none());
850        assert!(LabelExpr::And(vec![label("A"), label("B")])
851            .static_disjunction_arms()
852            .is_none());
853        // A nested Or: the disjunct is not a plain label.
854        let nested = LabelExpr::Or(vec![
855            label("A"),
856            LabelExpr::Or(vec![label("B"), label("C")]),
857        ]);
858        assert!(nested.static_disjunction_arms().is_none());
859        // An And of two Ors: a DNF no producer builds.
860        let dnf = LabelExpr::And(vec![
861            LabelExpr::Or(vec![label("A"), label("B")]),
862            LabelExpr::Or(vec![label("C"), label("D")]),
863        ]);
864        assert!(dnf.static_disjunction_arms().is_none());
865        // An empty Or is constructible and answers no arm.
866        assert!(LabelExpr::Or(Vec::new())
867            .static_disjunction_arms()
868            .is_none());
869        // Wildcard and negated leaves decline the whole classification.
870        let wild = LabelExpr::Or(vec![label("A"), LabelExpr::Wildcard]);
871        assert!(wild.static_disjunction_arms().is_none());
872        let negated = LabelExpr::Or(vec![label("A"), LabelExpr::Not(Box::new(label("B")))]);
873        assert!(negated.static_disjunction_arms().is_none());
874        assert!(LabelExpr::Wildcard.static_disjunction_arms().is_none());
875    }
876
877    /// The single-label arm: one arm, no shared base — the same view shape
878    /// a lone label and a disjunction's arms read through.
879    #[test]
880    fn the_single_label_view_answers_one_arm() {
881        let name = SmallName::from_name("Model");
882        let arms = DisjunctionArms::single(&name);
883        assert_eq!(rendered(&arms), vec![vec!["Model".to_string()]]);
884        assert!(arms.base().is_empty());
885        assert_eq!(arms.disjuncts(), vec![&name]);
886        assert!(!arms.is_empty());
887    }
888
889    fn rel(types: &[&str], type_expr: Option<LabelExpr>) -> RelPattern {
890        RelPattern {
891            variable: None,
892            types: types
893                .iter()
894                .map(|name| relate_names::unresolved(SmallName::from_name(name)))
895                .collect(),
896            type_expr,
897            direction: Direction::Outgoing,
898            properties: None,
899            prop_keys: Vec::new(),
900            var_length: false,
901            min_hops: 1,
902            max_hops: Some(1),
903            where_clause: None,
904            quantified: false,
905            legacy_type_separator: false,
906        }
907    }
908
909    /// The `types` list is the complete filter for an absent expression
910    /// (the untyped hop included) and for an expression spelling exactly
911    /// the non-empty list; an empty `Or` (matches nothing), a negation, or
912    /// a list the expression does not spell is not.
913    #[test]
914    fn types_are_the_complete_filter_only_when_the_list_says_all_of_it() {
915        assert!(rel(&[], None).types_are_complete_filter());
916        assert!(rel(&["A"], None).types_are_complete_filter());
917        assert!(rel(&["A"], Some(label("A"))).types_are_complete_filter());
918        assert!(rel(
919            &["A", "B"],
920            Some(LabelExpr::Or(vec![label("A"), label("B")]))
921        )
922        .types_are_complete_filter());
923        assert!(!rel(&[], Some(LabelExpr::Or(Vec::new()))).types_are_complete_filter());
924        assert!(
925            !rel(&["A"], Some(LabelExpr::Not(Box::new(label("A"))))).types_are_complete_filter()
926        );
927        assert!(!rel(&["A"], Some(label("B"))).types_are_complete_filter());
928        assert!(!rel(&[], Some(LabelExpr::Wildcard)).types_are_complete_filter());
929    }
930
931    /// The static/dynamic label criterion: no expression, a plain
932    /// conjunction (nested ones included) are static; an empty `And`, a
933    /// disjunction, a negation and the wildcard are dynamic.
934    #[test]
935    fn has_static_labels_splits_static_from_dynamic() {
936        use super::NodePattern;
937        let mut np = NodePattern::anonymous();
938        assert!(np.has_static_labels());
939        np.label_expr = Some(label("A"));
940        assert!(np.has_static_labels());
941        np.label_expr = Some(LabelExpr::And(vec![label("A"), label("B")]));
942        assert!(np.has_static_labels());
943        np.label_expr = Some(LabelExpr::And(vec![
944            LabelExpr::And(vec![label("A"), label("B")]),
945            label("C"),
946        ]));
947        assert!(np.has_static_labels());
948        for dynamic in [
949            LabelExpr::And(Vec::new()),
950            LabelExpr::Or(vec![label("A"), label("B")]),
951            LabelExpr::Not(Box::new(label("A"))),
952            LabelExpr::Wildcard,
953        ] {
954            np.label_expr = Some(dynamic);
955            assert!(!np.has_static_labels());
956        }
957    }
958}