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 /// Whether the type list used the deprecated repeated-colon separator
152 /// (`[:R|:T]`) instead of the plain bar (`[:R|T]`). Only legal on a bare
153 /// type list; the parser rejects it beside a variable, inline
154 /// properties or a hop bound, so a set flag is always a deprecation
155 /// fact, never a semantic difference.
156 pub legacy_type_separator: bool,
157}
158
159impl RelPattern {
160 /// Whether the relationship is variable-length: either hop bound was
161 /// written (`*m..n`, or a CIP-28 quantifier lowered onto the bounds).
162 /// The one predicate every consumer consults instead of re-spelling
163 /// the two `is_some` checks.
164 pub fn is_variable_length(&self) -> bool {
165 self.min_hops.is_some() || self.max_hops.is_some()
166 }
167}
168
169/// A GQL label/relationship-type expression (CIP-14): `&` (conjunction),
170/// `|` (disjunction), `!` (negation), `%` (wildcard -- matches any non-empty
171/// label set, or any relationship since every relationship has exactly one
172/// type), parenthesized grouping (folded directly into the tree, so no
173/// explicit `Group` variant is needed), and CIP-249's dynamic label name
174/// `$(expr)`. The legacy colon-conjunction shorthand `:A:B:C` lowers to
175/// `And([Label(A), Label(B), Label(C)])`, and the legacy relationship-type
176/// disjunction shorthand `:A|B` lowers to `Or([Label(A), Label(B)])`,
177/// preserving pre-CIP-14 behavior exactly.
178#[derive(Debug, Clone, PartialEq)]
179pub enum LabelExpr {
180 /// A single label/type name.
181 Label(SmallName),
182 /// `%`
183 Wildcard,
184 /// `$(expr)` / `$all(expr)` / `$any(expr)` -- a label/type name (or, for
185 /// list-valued `expr`, a set of label/type names) resolved at runtime
186 /// (CIP-249 / CIP-156 / CIP-221).
187 Dynamic(DynamicLabelExpr),
188 /// `!<label-expr>` -- negates only the following primary.
189 Not(Box<LabelExpr>),
190 /// `<label-expr> & <label-expr> & ...`
191 And(Vec<LabelExpr>),
192 /// `<label-expr> | <label-expr> | ...`
193 Or(Vec<LabelExpr>),
194}
195
196/// A dynamic label/type expression's quantifier: `$(expr)` (`Default`),
197/// `$all(expr)` (`All`), or `$any(expr)` (`Any`). `Default` and `All` share
198/// conjunction semantics for list-valued `expr` (and are otherwise
199/// interchangeable); `Any` is disjunction. Kept distinct from `All` so
200/// callers (e.g. `CREATE`/`MERGE` label resolution) can reject the explicit
201/// `$any(...)` form while still accepting the implicit-all `$(...)` form.
202#[derive(Debug, Clone, Copy, PartialEq, Eq)]
203pub enum DynamicLabelQuantifier {
204 Default,
205 All,
206 Any,
207}
208
209/// The payload of `LabelExpr::Dynamic`: the value expression plus its
210/// quantifier.
211#[derive(Debug, Clone, PartialEq)]
212pub struct DynamicLabelExpr {
213 pub expr: Box<Expr>,
214 pub quantifier: DynamicLabelQuantifier,
215}
216
217impl LabelExpr {
218 /// Returns the flat list of label names if this expression is a plain
219 /// label list: a single label, or an `And` of only plain labels (as
220 /// produced by legacy colon-conjunction `:A:B:C`, or a comma-separated
221 /// SET/REMOVE label item). Returns `None` for anything using `|`, `!`,
222 /// `%`, or a dynamic label -- those aren't valid label lists (CREATE /
223 /// MERGE / SET / REMOVE label specifications, per CIP-14's "DML
224 /// statements" exclusion and CIP-126).
225 pub fn as_label_list(&self) -> Option<Vec<SmallName>> {
226 match self {
227 LabelExpr::Label(name) => Some(vec![name.clone()]),
228 LabelExpr::And(items) => {
229 let mut out = Vec::with_capacity(items.len());
230 for item in items {
231 match item {
232 LabelExpr::Label(name) => out.push(name.clone()),
233 _ => return None,
234 }
235 }
236 Some(out)
237 }
238 _ => None,
239 }
240 }
241
242 /// True if this expression contains `!` (negation) or `%` (wildcard)
243 /// anywhere, recursively. Used to reject a variable-length quantifier
244 /// combined with negation/wildcard (CIP-14).
245 pub fn contains_not_or_wildcard(&self) -> bool {
246 match self {
247 LabelExpr::Label(_) | LabelExpr::Dynamic(_) => false,
248 LabelExpr::Wildcard | LabelExpr::Not(_) => true,
249 LabelExpr::And(items) | LabelExpr::Or(items) => {
250 items.iter().any(LabelExpr::contains_not_or_wildcard)
251 }
252 }
253 }
254
255 /// Returns the flat list of label/type names if this expression is a
256 /// plain label or `|`-disjunction list: a single label, or an `Or` of
257 /// only plain labels (as produced by `A|B|C`). Returns `None` for
258 /// anything using `&`, `!`, `%`, or a dynamic label. Used by the
259 /// CREATE INDEX / CREATE CONSTRAINT `FOR` target (CIP-11/CIP-38/
260 /// CIP-235's `FOR (n:A|B)` multi-label DDL surface) -- a narrower
261 /// grammar than general MATCH label expressions.
262 pub fn as_ddl_list(&self) -> Option<Vec<SmallName>> {
263 match self {
264 LabelExpr::Label(name) => Some(vec![name.clone()]),
265 LabelExpr::Or(items) => {
266 let mut out = Vec::with_capacity(items.len());
267 for item in items {
268 match item {
269 LabelExpr::Label(name) => out.push(name.clone()),
270 _ => return None,
271 }
272 }
273 Some(out)
274 }
275 _ => None,
276 }
277 }
278
279 /// True if this expression contains a `$(...)`/`$all(...)`/`$any(...)`
280 /// dynamic label/type atom anywhere, recursively (CIP-156). Used by
281 /// CREATE/MERGE's static "exactly one relationship type" check to defer
282 /// to runtime resolution when the count can't be known until the
283 /// dynamic expression is evaluated.
284 pub fn contains_dynamic(&self) -> bool {
285 match self {
286 LabelExpr::Label(_) | LabelExpr::Wildcard => false,
287 LabelExpr::Dynamic(_) => true,
288 LabelExpr::Not(inner) => inner.contains_dynamic(),
289 LabelExpr::And(items) | LabelExpr::Or(items) => {
290 items.iter().any(LabelExpr::contains_dynamic)
291 }
292 }
293 }
294}
295
296/// Direction of a relationship.
297#[derive(Debug, Clone, Copy, PartialEq, Eq)]
298pub enum Direction {
299 Right, // (a)-[]->(b)
300 Left, // (a)<-[]-(b)
301 Both, // (a)-[]-(b)
302}
303
304// -- Expression nodes --