Skip to main content

relate_parser/ast/
pattern.rs

1//! Graph pattern nodes: paths, elements, quantifiers and label expressions.
2
3use super::*;
4
5/// A path pattern like (a)-[r]->(b), optionally named: p = (a)-[r]->(b).
6#[derive(Debug, Clone, PartialEq)]
7pub struct PatternPath {
8    pub variable: Option<SmallName>,
9    /// CIP-73: the subpath variable of a named parenthesized group that is
10    /// itself the whole path body (`MATCH p = ANY SHORTEST (q = (:A)-->+(:B))`,
11    /// `MATCH ANY SHORTEST (q = (:A)-->+(:B))`). [`Self::variable`] carries
12    /// only the enclosing `p = …` name; both names bind the same path value
13    /// and [`Self::path_names`] lists them. A lone group name (no enclosing
14    /// path name) stays here, not in `variable`, so a group reading its own
15    /// name inside its `WHERE` stays distinguishable from an enclosing path
16    /// variable read there (42I21).
17    pub subpath_variable: Option<SmallName>,
18    pub elements: Vec<PatternElement>,
19    /// The trailing `WHERE` of a parenthesized path pattern, e.g.
20    /// `((n)-[r]->(m) WHERE n.p > m.q AND r:S)` (CIP-14 "parenthesized path
21    /// pattern" location). Evaluated once every element in the path is
22    /// bound, ANDed with the pattern match itself.
23    pub where_expr: Option<Expr>,
24    /// CIP-51 explicit path mode prefix (`WALK`/`TRAIL`/`ACYCLIC`/`SIMPLE`),
25    /// written directly or nested inside a `selector`'s own `[path mode]`
26    /// slot. `None` means no explicit keyword (resolves to `Walk`).
27    pub mode: Option<PathMode>,
28    /// CIP-73/CIP-191 path selector prefix (`ALL`/`ANY`/`SHORTEST`/...).
29    /// `None` means no explicit selector (equivalent to an implicit `ALL`).
30    pub selector: Option<PathSelector>,
31    /// True if this path pattern is sugar for the pre-GPM
32    /// `shortestPath(...)`/`allShortestPaths(...)` function (CIP-40/CIP-73),
33    /// rather than an explicit `SHORTEST`/`ALL SHORTEST`
34    /// selector keyword -- even though both normalize to the same
35    /// `selector` value. The two are NOT interchangeable for CIP-40's
36    /// mixing rules: the legacy function forms are exempt from the
37    /// explicit-match-mode and multiple-selective-path-pattern
38    /// restrictions that apply to the keyword selector syntax (see
39    /// `Parser::parse_match`).
40    pub is_shortest_path_function: bool,
41}
42
43impl PatternPath {
44    /// The names this path binds its path value under, in declaration order:
45    /// the outer path variable, then a named parenthesized subpath. The two
46    /// name the same path value; the IR twin is `PathPattern::path_names`.
47    pub fn path_names(&self) -> impl Iterator<Item = &SmallName> {
48        [self.variable.as_ref(), self.subpath_variable.as_ref()]
49            .into_iter()
50            .flatten()
51    }
52}
53
54/// A pattern element is either a node pattern, a relationship pattern, or a
55/// quantified path pattern (CIP-28).
56#[derive(Debug, Clone, PartialEq)]
57pub enum PatternElement {
58    Node(NodePattern),
59    Relationship(RelPattern),
60    Quantified(QuantifiedPathPattern),
61}
62
63/// The `{min, max}` bounds of a CIP-28 quantifier (`*`, `+`, `{m,n}`, `{m,}`,
64/// `{,n}`, `{,}`, `{n}`). `max = None` means unbounded. Bounds are already
65/// normalized and validated by the parser: `{,}` -> `{0,}` and the
66/// bounds checks (upper bound > 0, lower bound <= upper bound) are
67/// enforced at parse time, so every `PathQuantifier` that reaches the AST
68/// is legal.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub struct PathQuantifier {
71    pub min: u32,
72    pub max: Option<u32>,
73}
74
75/// A quantified path pattern: a parenthesized subpath (`elements`),
76/// optionally assigned a subpath variable (e.g. `(p2 = (x)-->(y))*`) and/or a trailing `WHERE` evaluated once per
77/// iteration, followed by a quantifier. Appears as a `PatternElement`
78/// alongside plain `Node`/`Relationship` elements so it composes freely with
79/// them by concatenation.
80///
81/// A bare quantified relationship (`-[r]->*`, Form 5) does *not* produce this
82/// variant: it normalizes directly into the ordinary variable-length
83/// `RelPattern` (`min_hops`/`max_hops`), since it declares no element
84/// variables of its own to expose as a group and its matching semantics are
85/// identical to the legacy `-[*min..max]->` matcher (only the quantifier's
86/// own zero-inclusive defaults differ, e.g. bare `*` means 0 or more here
87/// versus 1 or more for legacy bare `*`). See `Parser::parse_rel_pattern`.
88#[derive(Debug, Clone, PartialEq)]
89pub struct QuantifiedPathPattern {
90    pub subpath_variable: Option<SmallName>,
91    pub elements: Vec<PatternElement>,
92    pub where_expr: Option<Expr>,
93    pub quantifier: PathQuantifier,
94}
95
96/// A node pattern like (n:Label {prop: value}).
97#[derive(Debug, Clone, PartialEq)]
98pub struct NodePattern {
99    pub variable: Option<SmallName>,
100    pub label_expr: Option<LabelExpr>,
101    pub properties: Vec<(SmallName, Expr)>,
102    pub has_properties: bool,
103    /// The `$paramName` whole-property-map shorthand (an alternative to
104    /// `{...}`), e.g. `CREATE (n:Label $props)`. Mutually exclusive with
105    /// `properties`/`has_properties` -- the parser only ever populates one
106    /// property-map form per pattern element.
107    pub properties_param: Option<Expr>,
108    /// The element-pattern `WHERE` of `(n WHERE <expr>)` (CIP-14 "node
109    /// element pattern" location), evaluated once `variable` is bound.
110    pub where_expr: Option<Expr>,
111}
112
113/// A relationship pattern like -[r:TYPE {prop: value}]->.
114#[derive(Debug, Clone, PartialEq)]
115pub struct RelPattern {
116    pub variable: Option<SmallName>,
117    pub type_expr: Option<LabelExpr>,
118    pub properties: Vec<(SmallName, Expr)>,
119    /// Whether a property specification was *written*, in either spelling.
120    /// The rel twin of [`NodePattern`]'s field: set for `{}` too, so
121    /// `-[] {}]-` and `(a {})` agree wherever "has predicates" is asked
122    /// (42N56) — live-verified against Neo4j.
123    pub has_properties: bool,
124    /// The `$paramName` whole-property-map shorthand -- see
125    /// `NodePattern::properties_param`.
126    pub properties_param: Option<Expr>,
127    pub direction: Direction,
128    pub min_hops: Option<u32>,
129    pub max_hops: Option<u32>,
130    /// The element-pattern `WHERE` of `[r WHERE <expr>]`.
131    pub where_expr: Option<Expr>,
132    /// True when `min_hops`/`max_hops` came from a CIP-28 postfix quantifier
133    /// (`-[r]->*`, `-->+`, `-[]->{1,6}`, Form 5) rather than the legacy
134    /// bracket-internal `[r*min..max]` syntax. Distinguishes the two so the
135    /// engine can apply `where_expr` per traversed edge for the CIP-28 form
136    /// without changing the legacy matcher's (TCK-tested) behavior.
137    pub quantified: bool,
138}
139
140impl RelPattern {
141    /// Whether the relationship is variable-length: either hop bound was
142    /// written (`*m..n`, or a CIP-28 quantifier lowered onto the bounds).
143    /// The one predicate every consumer consults instead of re-spelling
144    /// the two `is_some` checks.
145    pub fn is_variable_length(&self) -> bool {
146        self.min_hops.is_some() || self.max_hops.is_some()
147    }
148}
149
150/// A GQL label/relationship-type expression (CIP-14): `&` (conjunction),
151/// `|` (disjunction), `!` (negation), `%` (wildcard -- matches any non-empty
152/// label set, or any relationship since every relationship has exactly one
153/// type), parenthesized grouping (folded directly into the tree, so no
154/// explicit `Group` variant is needed), and CIP-249's dynamic label name
155/// `$(expr)`. The legacy colon-conjunction shorthand `:A:B:C` lowers to
156/// `And([Label(A), Label(B), Label(C)])`, and the legacy relationship-type
157/// disjunction shorthand `:A|B` lowers to `Or([Label(A), Label(B)])`,
158/// preserving pre-CIP-14 behavior exactly.
159#[derive(Debug, Clone, PartialEq)]
160pub enum LabelExpr {
161    /// A single label/type name.
162    Label(SmallName),
163    /// `%`
164    Wildcard,
165    /// `$(expr)` / `$all(expr)` / `$any(expr)` -- a label/type name (or, for
166    /// list-valued `expr`, a set of label/type names) resolved at runtime
167    /// (CIP-249 / CIP-156 / CIP-221).
168    Dynamic(DynamicLabelExpr),
169    /// `!<label-expr>` -- negates only the following primary.
170    Not(Box<LabelExpr>),
171    /// `<label-expr> & <label-expr> & ...`
172    And(Vec<LabelExpr>),
173    /// `<label-expr> | <label-expr> | ...`
174    Or(Vec<LabelExpr>),
175}
176
177/// A dynamic label/type expression's quantifier: `$(expr)` (`Default`),
178/// `$all(expr)` (`All`), or `$any(expr)` (`Any`). `Default` and `All` share
179/// conjunction semantics for list-valued `expr` (and are otherwise
180/// interchangeable); `Any` is disjunction. Kept distinct from `All` so
181/// callers (e.g. `CREATE`/`MERGE` label resolution) can reject the explicit
182/// `$any(...)` form while still accepting the implicit-all `$(...)` form.
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184pub enum DynamicLabelQuantifier {
185    Default,
186    All,
187    Any,
188}
189
190/// The payload of `LabelExpr::Dynamic`: the value expression plus its
191/// quantifier.
192#[derive(Debug, Clone, PartialEq)]
193pub struct DynamicLabelExpr {
194    pub expr: Box<Expr>,
195    pub quantifier: DynamicLabelQuantifier,
196}
197
198impl LabelExpr {
199    /// Returns the flat list of label names if this expression is a plain
200    /// label list: a single label, or an `And` of only plain labels (as
201    /// produced by legacy colon-conjunction `:A:B:C`, or a comma-separated
202    /// SET/REMOVE label item). Returns `None` for anything using `|`, `!`,
203    /// `%`, or a dynamic label -- those aren't valid label lists (CREATE /
204    /// MERGE / SET / REMOVE label specifications, per CIP-14's "DML
205    /// statements" exclusion and CIP-126).
206    pub fn as_label_list(&self) -> Option<Vec<SmallName>> {
207        match self {
208            LabelExpr::Label(name) => Some(vec![name.clone()]),
209            LabelExpr::And(items) => {
210                let mut out = Vec::with_capacity(items.len());
211                for item in items {
212                    match item {
213                        LabelExpr::Label(name) => out.push(name.clone()),
214                        _ => return None,
215                    }
216                }
217                Some(out)
218            }
219            _ => None,
220        }
221    }
222
223    /// True if this expression contains `!` (negation) or `%` (wildcard)
224    /// anywhere, recursively. Used to reject a variable-length quantifier
225    /// combined with negation/wildcard (CIP-14).
226    pub fn contains_not_or_wildcard(&self) -> bool {
227        match self {
228            LabelExpr::Label(_) | LabelExpr::Dynamic(_) => false,
229            LabelExpr::Wildcard | LabelExpr::Not(_) => true,
230            LabelExpr::And(items) | LabelExpr::Or(items) => {
231                items.iter().any(LabelExpr::contains_not_or_wildcard)
232            }
233        }
234    }
235
236    /// Returns the flat list of label/type names if this expression is a
237    /// plain label or `|`-disjunction list: a single label, or an `Or` of
238    /// only plain labels (as produced by `A|B|C`). Returns `None` for
239    /// anything using `&`, `!`, `%`, or a dynamic label. Used by the
240    /// CREATE INDEX / CREATE CONSTRAINT `FOR` target (CIP-11/CIP-38/
241    /// CIP-235's `FOR (n:A|B)` multi-label DDL surface) -- a narrower
242    /// grammar than general MATCH label expressions.
243    pub fn as_ddl_list(&self) -> Option<Vec<SmallName>> {
244        match self {
245            LabelExpr::Label(name) => Some(vec![name.clone()]),
246            LabelExpr::Or(items) => {
247                let mut out = Vec::with_capacity(items.len());
248                for item in items {
249                    match item {
250                        LabelExpr::Label(name) => out.push(name.clone()),
251                        _ => return None,
252                    }
253                }
254                Some(out)
255            }
256            _ => None,
257        }
258    }
259
260    /// True if this expression contains a `$(...)`/`$all(...)`/`$any(...)`
261    /// dynamic label/type atom anywhere, recursively (CIP-156). Used by
262    /// CREATE/MERGE's static "exactly one relationship type" check to defer
263    /// to runtime resolution when the count can't be known until the
264    /// dynamic expression is evaluated.
265    pub fn contains_dynamic(&self) -> bool {
266        match self {
267            LabelExpr::Label(_) | LabelExpr::Wildcard => false,
268            LabelExpr::Dynamic(_) => true,
269            LabelExpr::Not(inner) => inner.contains_dynamic(),
270            LabelExpr::And(items) | LabelExpr::Or(items) => {
271                items.iter().any(LabelExpr::contains_dynamic)
272            }
273        }
274    }
275}
276
277/// Direction of a relationship.
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279pub enum Direction {
280    Right, // (a)-[]->(b)
281    Left,  // (a)<-[]-(b)
282    Both,  // (a)-[]-(b)
283}
284
285// -- Expression nodes --