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