relate_parser/parser/patterns.rs
1use super::*;
2
3/// The property spec and element `WHERE` read after a node or relationship
4/// element's variable and label/type spec.
5#[derive(Default)]
6struct ElementTail {
7 properties: Vec<(SmallName, Expr)>,
8 has_properties: bool,
9 properties_param: Option<Expr>,
10 where_expr: Option<Expr>,
11}
12
13impl<'a> Parser<'a> {
14 // ---- Pattern parsing ----
15
16 pub(super) fn parse_pattern(&mut self) -> ParseResult<Vec<PatternPath>> {
17 self.parse_pattern_after(None)
18 }
19
20 /// A pattern list whose first path carries a path variable the caller
21 /// already consumed — the `MATCH p = REPEATABLE ELEMENTS …` form, where
22 /// the `<name> =` prefix precedes the clause-level match-mode phrase.
23 /// The variable is handed to the one path-variable production instead of
24 /// being patched onto the parsed path afterwards.
25 pub(super) fn parse_pattern_after_leading_variable(
26 &mut self,
27 variable: SmallName,
28 ) -> ParseResult<Vec<PatternPath>> {
29 self.parse_pattern_after(Some(variable))
30 }
31
32 fn parse_pattern_after(
33 &mut self,
34 mut leading_variable: Option<SmallName>,
35 ) -> ParseResult<Vec<PatternPath>> {
36 let mut paths = Vec::new();
37 loop {
38 let path = match leading_variable.take() {
39 Some(variable) => self.parse_pattern_path_with_variable(variable)?,
40 None => self.parse_pattern_path()?,
41 };
42 paths.push(path);
43 if self.peek_type() != TokenType::Comma {
44 break;
45 }
46 self.next_token();
47 }
48 Ok(paths)
49 }
50
51 /// True when the token `offset` ahead is a symbolic name directly
52 /// followed by `=` -- the named-path prefix `name = ...` (ADR-0191: a
53 /// keyword spelling works too). The callers pass `offset == 0` at a
54 /// pattern position and `offset == 1` past a leading `(` (the
55 /// parenthesized subpath group).
56 pub(super) fn peek_named_path_prefix(&self, offset: usize) -> bool {
57 self.peek_at(offset).ty.is_schema_name() && self.peek_at(offset + 1).ty == TokenType::Equals
58 }
59
60 pub(super) fn parse_pattern_path(&mut self) -> ParseResult<PatternPath> {
61 // Optional named-path prefix: `p = ...`. Consumed up front so that a
62 // path variable assigned to a top-level parenthesized path pattern
63 // (`p = ((a)-[r]->(b))`, CIP-19 basic-structure #15) is recognized
64 // before `parse_pattern_path_body`'s own inner double-paren handling.
65 // The variable is a symbolic name, so any keyword spelling works
66 // unquoted too (ADR-0191).
67 let outer_var = if self.peek_named_path_prefix(0) {
68 let tok = self.next_token(); // consume the path variable
69 self.next_token(); // consume =
70 Some(SmallName::from_name(&tok.literal))
71 } else {
72 None
73 };
74 self.parse_pattern_path_named(outer_var)
75 }
76
77 /// [`parse_pattern_path`] with the `<name> =` prefix already consumed
78 /// (the path variable may precede a match-mode phrase).
79 pub(super) fn parse_pattern_path_with_variable(
80 &mut self,
81 variable: SmallName,
82 ) -> ParseResult<PatternPath> {
83 self.parse_pattern_path_named(Some(variable))
84 }
85
86 fn parse_pattern_path_named(
87 &mut self,
88 outer_var: Option<SmallName>,
89 ) -> ParseResult<PatternPath> {
90 // Pre-GPM `shortestPath(...)`/`allShortestPaths(...)` used as a
91 // top-level MATCH pattern: sugar for
92 // `SHORTEST 1 PATH (...)` / `ALL SHORTEST (...)` respectively.
93 // Checked before `parse_path_prefix` -- a bare `shortestPath`
94 // identifier can never otherwise start a pattern (every path
95 // pattern begins with `(`), so there is no ambiguity with the
96 // `ALL`/`ANY`/`SHORTEST` selector keywords.
97 if self.peek_type() == TokenType::Identifier {
98 let lower = self.peek().literal.to_ascii_lowercase();
99 if (lower == "shortestpath" || lower == "allshortestpaths")
100 && self.peek_at(1).ty == TokenType::LeftParen
101 {
102 self.next_token(); // consume shortestPath/allShortestPaths
103 self.next_token(); // consume (
104 let selector = if lower == "allshortestpaths" {
105 PathSelector::AllShortest
106 } else {
107 PathSelector::Shortest {
108 count: Some(PathCount::Literal(1)),
109 group: false,
110 }
111 };
112 let mut path =
113 self.parse_pattern_path_body(Some(&selector), outer_var.is_some())?;
114 self.expect(TokenType::RightParen)?;
115 if contains_gpm_quantification(&path.elements) {
116 return Err(self.error(
117 "QuantifiedPathPatternInShortestPath: a quantified path pattern cannot be used inside shortestPath()/allShortestPaths()",
118 ));
119 }
120 if let Some(var) = outer_var {
121 if let Some(inner) = path.variable.take() {
122 if inner == var {
123 return Err(self.error(format!(
124 "VariableAlreadyDefined: variable `{var}` already declared"
125 )));
126 }
127 path.subpath_variable = Some(inner);
128 }
129 if path.subpath_variable.as_ref() == Some(&var) {
130 return Err(self.error(format!(
131 "VariableAlreadyDefined: variable `{var}` already declared"
132 )));
133 }
134 path.variable = Some(var);
135 }
136 path.mode = None;
137 path.selector = Some(selector);
138 path.is_shortest_path_function = true;
139 return self.finish_pattern_path(path);
140 }
141 }
142
143 let (selector, mode) = self.parse_path_prefix()?;
144
145 // The path variable declaration
146 // must precede the mode/selector prefix. If another `name =`
147 // follows the prefix we just consumed, the input was actually
148 // `MODE p = ...` (mode before the variable) -- reject it explicitly
149 // rather than silently reinterpreting it. A keyword spelling is a
150 // path variable too (ADR-0191), so it must be rejected here the
151 // same way.
152 if self.peek_named_path_prefix(0) {
153 return Err(self.error(
154 "InvalidPathModePosition: the path variable declaration must precede the path mode/selector prefix",
155 ));
156 }
157
158 let mut path = self.parse_pattern_path_body(selector.as_ref(), outer_var.is_some())?;
159 if let Some(var) = outer_var {
160 // A named parenthesized group that is the whole body
161 // (`p = ANY SHORTEST (q = (:A)-->+(:B))`) keeps both names: the
162 // element group already put `q` in `variable`, and the enclosing
163 // path name `p` binds the same path value. Reusing the enclosing
164 // path's own name for the group is Neo4j's 42N59 duplicate
165 // declaration, not a silent collapse to one name.
166 if let Some(inner) = path.variable.take() {
167 if inner == var {
168 return Err(self.error(format!(
169 "VariableAlreadyDefined: variable `{var}` already declared"
170 )));
171 }
172 path.subpath_variable = Some(inner);
173 }
174 if path.subpath_variable.as_ref() == Some(&var) {
175 return Err(self.error(format!(
176 "VariableAlreadyDefined: variable `{var}` already declared"
177 )));
178 }
179 path.variable = Some(var);
180 }
181 path.mode = mode;
182 path.selector = selector;
183
184 self.finish_pattern_path(path)
185 }
186
187 /// Shared tail of `parse_pattern_path`: the rule that a
188 /// top-level path pattern must have a minimum node count > 0 -- it
189 /// cannot consist entirely of zero-lower-bound quantified path patterns
190 /// (which could all collapse to zero iterations, leaving no node at
191 /// all). A plain `Node` element always guarantees at least one node; a
192 /// `Quantified` element guarantees one only if its own quantifier
193 /// requires at least one iteration.
194 pub(super) fn finish_pattern_path(&self, path: PatternPath) -> ParseResult<PatternPath> {
195 let has_guaranteed_node = path.elements.iter().any(|e| match e {
196 PatternElement::Node(_) => true,
197 PatternElement::Quantified(q) => q.quantifier.min >= 1,
198 PatternElement::Relationship(_) => false,
199 });
200 if !has_guaranteed_node {
201 return Err(self.error(
202 "MinimumNodeCountZero: a path pattern must have a minimum node count greater than zero",
203 ));
204 }
205
206 Ok(path)
207 }
208
209 /// Parses one path pattern's body: an optional named-path prefix
210 /// (`ident = `, recognized both at the top level and for a subpath
211 /// variable inside a quantification, e.g. `(p2 = (x)-->(y))*`) followed
212 /// by a sequence of node, relationship, and quantified-path-pattern
213 /// factors (by concatenation). Node and quantified
214 /// factors may be juxtaposed directly (no relationship between them,
215 /// e.g. `(x)((a)-->(b))*` or `((a)-->(b))*((c)-->(d))*`); a relationship
216 /// factor must always be preceded by an already-parsed element and
217 /// followed by a node or quantified factor.
218 pub(super) fn parse_pattern_path_body(
219 &mut self,
220 selector: Option<&PathSelector>,
221 outer_named: bool,
222 ) -> ParseResult<PatternPath> {
223 let mut path = PatternPath {
224 variable: None,
225 subpath_variable: None,
226 elements: Vec::new(),
227 where_expr: None,
228 mode: None,
229 selector: None,
230 is_shortest_path_function: false,
231 };
232
233 // Check for named path: symbolic name = (...) -- a keyword spelling
234 // included (ADR-0191), e.g. a subpath variable inside a quantified
235 // path pattern (`(MATCH = (x)-->(y))*`).
236 if self.peek_named_path_prefix(0) {
237 let tok = self.next_token();
238 self.next_token(); // consume =
239 path.variable = Some(SmallName::from_name(&tok.literal));
240 }
241
242 loop {
243 match self.peek_type() {
244 TokenType::LeftParen if self.peek_is_parenthesized_subpath_start() => {
245 // Parenthesized subpath group: `((...) [WHERE ...])`
246 // (CIP-14). Either quantified into a `Quantified`
247 // element (CIP-28), or -- if unquantified -- legal only
248 // as the sole factor of the whole pattern.
249 self.next_token(); // consume outer (
250 // ADR-0257: nested parenthesized subpaths recurse here
251 // directly, bypassing `parse_expression`, so each level
252 // must count separately (LABS-69).
253 let inner =
254 self.with_expr_depth(|p| p.parse_pattern_path_body(selector, outer_named))?;
255 let where_expr = if self.peek_type() == TokenType::WHERE {
256 self.next_token();
257 Some(self.parse_expression()?)
258 } else {
259 None
260 };
261 self.expect(TokenType::RightParen)?;
262
263 if matches!(
264 self.peek_type(),
265 TokenType::Star | TokenType::Plus | TokenType::LeftBrace
266 ) {
267 self.side_effects.quantifiers.gpm_form = true;
268 let quantifier = self.parse_quantifier()?;
269 // The operand's minimum path length must be
270 // > 0 -- a single node pattern cannot be quantified.
271 let has_relationship = inner
272 .elements
273 .iter()
274 .any(|e| matches!(e, PatternElement::Relationship(_)));
275 if !has_relationship {
276 return Err(self.error(
277 "MinimumPathLengthZero: the operand of a quantified path pattern must have a minimum path length greater than zero",
278 ));
279 }
280 // Quantified path patterns cannot be nested,
281 // directly or through concatenation.
282 if contains_quantification(&inner.elements) {
283 return Err(self.error(
284 "NestedQuantification: quantified path patterns cannot be nested",
285 ));
286 }
287 path.elements
288 .push(PatternElement::Quantified(QuantifiedPathPattern {
289 subpath_variable: inner.variable.or(inner.subpath_variable),
290 elements: inner.elements,
291 where_expr,
292 quantifier,
293 }));
294 } else {
295 // Unquantified parenthesized pattern: only legal as
296 // the entire pattern path (CIP-14 pre-existing
297 // feature) -- nothing may precede or follow it.
298 if !path.elements.is_empty()
299 || matches!(
300 self.peek_type(),
301 TokenType::LeftParen | TokenType::Dash | TokenType::ArrowLeft
302 )
303 {
304 return Err(self.error(
305 "UnquantifiedParenthesizedPattern: an unquantified parenthesized path pattern cannot be juxtaposed with other pattern elements",
306 ));
307 }
308 // Neo4j 2026 (Cypher 25) supports naming a
309 // parenthesized group only under a selective path
310 // search (ANY / SHORTEST...). Under ALL, or with no
311 // selector (the implicit ALL), `(p = ...)` as the
312 // whole path body is 42N42 "sub-path assignment is
313 // not supported". The unnamed group stays legal in
314 // every selector, and so does an outer path name
315 // (`p = ((:A)-->+(:B))`). Relate keeps the
316 // CIP-28 sub-path form when the enclosing pattern
317 // carries its own path name (`p = (q = …)`), an
318 // extension the compatibility corpus does not pin.
319 if inner.variable.is_some()
320 && !outer_named
321 && !selector_is_selective(selector)
322 {
323 return Err(self.error(
324 "UnsupportedSubPathBinding: sub-path assignment is not supported",
325 ));
326 }
327 path.elements = inner.elements;
328 path.where_expr = where_expr;
329 // A doubly-parenthesized named group files its name on the inner
330 // path's `subpath_variable`, so read both fields: taking only
331 // `inner.variable` dropped the name for `((p = (:A)-->(:B)))`.
332 if let Some(v) = inner.variable.or(inner.subpath_variable) {
333 // The group's own sub-path name stays in
334 // `subpath_variable` (not `variable`, which is
335 // the enclosing `p = …` name). Keeping the two
336 // apart lets the validator tell a group reading
337 // its *own* name inside its `WHERE`
338 // (Neo4j-legal, `ANY SHORTEST (q = (…) WHERE
339 // length(q) …)`) from an enclosing path
340 // variable read there (42I21,
341 // `p = ((…) WHERE length(p) …)`): both bind the
342 // path value, so `path_names()` is unchanged.
343 path.subpath_variable = Some(v);
344 }
345 return Ok(path);
346 }
347 }
348 TokenType::LeftParen => {
349 let node = self.parse_node_pattern()?;
350 path.elements.push(PatternElement::Node(node));
351 }
352 TokenType::Dash | TokenType::ArrowLeft => {
353 if path.elements.is_empty() {
354 return Err(self.error("a pattern must start with a node pattern"));
355 }
356 let rel = self.parse_rel_pattern()?;
357 path.elements.push(PatternElement::Relationship(rel));
358 if self.peek_type() != TokenType::LeftParen {
359 return Err(self.error("expected node pattern after relationship"));
360 }
361 }
362 _ => break,
363 }
364 }
365
366 if path.elements.is_empty() {
367 return Err(self.error("expected a pattern"));
368 }
369
370 Ok(path)
371 }
372
373 /// True if the parser is positioned at the start of a parenthesized
374 /// subpath group (CIP-14 `((...))`) -- either the plain `((` form, or
375 /// Consumes the current token if it is the contextual identifier `s`
376 /// (see `peek_is_ident`); returns whether it did. Used for the
377 /// CIP-51/CIP-73/CIP-191 contextual keywords (WALK, TRAIL, ACYCLIC,
378 /// SIMPLE, ANY, SHORTEST, GROUP, GROUPS, PATH, PATHS), which stay
379 /// ordinary identifiers everywhere else in the grammar (so they never
380 /// shadow the `all()`/`any()`/`none()`/`single()` predicate functions or
381 /// a variable of the same name).
382 pub(super) fn consume_ident(&mut self, s: &str) -> bool {
383 if self.peek_is_ident(s) {
384 self.next_token();
385 true
386 } else {
387 false
388 }
389 }
390
391 /// Parses an optional CIP-51 path mode keyword (`WALK`/`TRAIL`/
392 /// `ACYCLIC`/`SIMPLE`).
393 pub(super) fn parse_path_mode_keyword(&mut self) -> Option<PathMode> {
394 if self.consume_ident("walk") {
395 Some(PathMode::Walk)
396 } else if self.consume_ident("trail") {
397 Some(PathMode::Trail)
398 } else if self.consume_ident("acyclic") {
399 Some(PathMode::Acyclic)
400 } else if self.consume_ident("simple") {
401 Some(PathMode::Simple)
402 } else {
403 None
404 }
405 }
406
407 /// Consumes an optional CIP-51/CIP-73 `PATH`/`PATHS` noise keyword
408 /// (`<path keywords>` / `<path or paths>`); has no semantic effect.
409 pub(super) fn consume_path_or_paths_noise(&mut self) {
410 if !self.consume_ident("path") {
411 self.consume_ident("paths");
412 }
413 }
414
415 /// Parses the `<number of paths>`/`<number of groups>`
416 /// non-terminal, extended by CIP-191's `<dynamic parameter
417 /// specification>`: an unsigned integer literal (validated `> 0` here)
418 /// or a bare `$parameter` (validated at runtime, once its value
419 /// is known). Returns `None` if neither is present.
420 pub(super) fn parse_number_of_paths(&mut self) -> ParseResult<Option<PathCount>> {
421 if self.peek_type() == TokenType::Integer {
422 let tok = self.next_token();
423 // Checked conversion via the shared bound helper, not a silent
424 // clamp (LABS-81): `ANY 4294967296 PATHS` used to wrap to
425 // selector 0.
426 let n = self.parse_u32_bound(&tok, "InvalidNumberOfPaths: number of paths/groups")?;
427 if n == 0 {
428 return Err(self.error_at_token(
429 &tok,
430 "InvalidNumberOfPaths: the number of paths/groups must be greater than 0",
431 ));
432 }
433 return Ok(Some(PathCount::Literal(n)));
434 }
435 if self.peek_type() == TokenType::Parameter {
436 let tok = self.next_token();
437 return Ok(Some(PathCount::Parameter(tok.literal.into_owned())));
438 }
439 Ok(None)
440 }
441
442 /// Parses the optional CIP-51 path-mode-only prefix or CIP-73/CIP-191
443 /// path-search (selector) prefix that may precede a path pattern's body
444 /// (`<path pattern prefix>`). Returns
445 /// `(selector, mode)`; both `None` when neither is written.
446 pub(super) fn parse_path_prefix(
447 &mut self,
448 ) -> ParseResult<(Option<PathSelector>, Option<PathMode>)> {
449 if self.peek_type() == TokenType::ALL {
450 self.next_token(); // consume ALL
451 if self.consume_ident("shortest") {
452 let mode = self.parse_path_mode_keyword();
453 self.consume_path_or_paths_noise();
454 return Ok((Some(PathSelector::AllShortest), mode));
455 }
456 let mode = self.parse_path_mode_keyword();
457 self.consume_path_or_paths_noise();
458 return Ok((Some(PathSelector::All), mode));
459 }
460 if self.peek_is_ident("any") {
461 self.next_token(); // consume ANY
462 if self.consume_ident("shortest") {
463 let mode = self.parse_path_mode_keyword();
464 self.consume_path_or_paths_noise();
465 return Ok((Some(PathSelector::AnyShortest), mode));
466 }
467 let count = self.parse_number_of_paths()?;
468 let mode = self.parse_path_mode_keyword();
469 self.consume_path_or_paths_noise();
470 return Ok((Some(PathSelector::Any(count)), mode));
471 }
472 if self.peek_is_ident("shortest") {
473 self.next_token(); // consume SHORTEST
474 let count = self.parse_number_of_paths()?;
475 let mode = self.parse_path_mode_keyword();
476 self.consume_path_or_paths_noise();
477 let group = self.consume_ident("group") || self.consume_ident("groups");
478 if !group && count.is_none() {
479 return Err(self.error(
480 "InvalidNumberOfPaths: SHORTEST requires a number of paths unless followed by GROUP/GROUPS",
481 ));
482 }
483 return Ok((Some(PathSelector::Shortest { count, group }), mode));
484 }
485 // No selector: a bare path-mode-only prefix, if any.
486 let mode = self.parse_path_mode_keyword();
487 if mode.is_some() {
488 self.consume_path_or_paths_noise();
489 }
490 Ok((None, mode))
491 }
492
493 /// `(name = (` when the group itself carries a subpath variable
494 /// (e.g. `(p2 = (x)-->(y))*`). Distinguishes this
495 /// from a plain node pattern, whose own label/property spec never
496 /// starts with `(`. The subpath variable is a symbolic name, so any
497 /// keyword spelling works unquoted too (ADR-0191).
498 pub(super) fn peek_is_parenthesized_subpath_start(&self) -> bool {
499 if self.peek_type() != TokenType::LeftParen {
500 return false;
501 }
502 if self.peek_at(1).ty == TokenType::LeftParen {
503 return true;
504 }
505 self.peek_named_path_prefix(1) && self.peek_at(3).ty == TokenType::LeftParen
506 }
507
508 /// Parses a CIP-28 quantifier: `*`, `+`, `{m,n}`, `{m,}`, `{,n}`, `{,}`,
509 /// or `{n}`. The current token must be `Star`, `Plus`, or `LeftBrace`.
510 /// Applies the `{,}` -> `{0,}` normalization (an absent lower bound
511 /// defaults to 0) and the bounds validation (upper bound > 0 if
512 /// present, lower bound <= upper bound).
513 pub(super) fn parse_quantifier(&mut self) -> ParseResult<PathQuantifier> {
514 match self.peek_type() {
515 TokenType::Star => {
516 self.next_token();
517 Ok(PathQuantifier { min: 0, max: None })
518 }
519 TokenType::Plus => {
520 self.next_token();
521 Ok(PathQuantifier { min: 1, max: None })
522 }
523 TokenType::LeftBrace => {
524 self.next_token(); // consume {
525 let lower = if self.peek_type() == TokenType::Integer {
526 let tok = self.next_token();
527 Some(self.parse_u32_bound(&tok, "quantifier lower bound")?)
528 } else {
529 None
530 };
531 let (min, max) = if self.peek_type() == TokenType::Comma {
532 self.next_token(); // consume ,
533 let upper = if self.peek_type() == TokenType::Integer {
534 let tok = self.next_token();
535 Some(self.parse_u32_bound(&tok, "quantifier upper bound")?)
536 } else {
537 None
538 };
539 (lower.unwrap_or(0), upper)
540 } else {
541 // No comma: a fixed quantifier `{n}`, equivalent to `{n,n}`.
542 let n = lower
543 .ok_or_else(|| self.error("expected an integer or ',' in quantifier"))?;
544 (n, Some(n))
545 };
546 self.expect(TokenType::RightBrace)?;
547 if let Some(upper) = max {
548 if upper == 0 {
549 return Err(self.error(
550 "ZeroUpperBound: a quantifier's upper bound must be greater than zero",
551 ));
552 }
553 if min > upper {
554 return Err(self.error(
555 "LowerBoundGreaterThanUpperBound: a quantifier's lower bound cannot exceed its upper bound",
556 ));
557 }
558 }
559 Ok(PathQuantifier { min, max })
560 }
561 _ => Err(self.error("expected a quantifier")),
562 }
563 }
564
565 /// ADR-0191 Decision point 4: true when the token `offset` ahead can be
566 /// read as a node or relationship pattern's element variable. Only a
567 /// symbolic name (`is_schema_name()`: an `Identifier` or any keyword)
568 /// can be one; the `WHERE` and `IS` spellings additionally keep their
569 /// existing meanings in front of the variable read, decided by a
570 /// one-token lookahead:
571 ///
572 /// - a leading `WHERE` is the variable only when the next token cannot
573 /// start the inline element predicate (`)`, `]`, `:`, `IS`, `$`, `-`,
574 /// `<-`, `WHERE`); otherwise the inline-predicate meaning wins, so
575 /// `(WHERE 1 = 1)` stays an anonymous element with a predicate while
576 /// `(WHERE)` and `(where WHERE true)` read `WHERE` as the variable;
577 /// - a leading `IS` is the variable only when the next token cannot
578 /// start a label spec; otherwise the variable-less GPM
579 /// label-introducer meaning wins, so `(IS)`/`[IS]` read `IS` as the
580 /// variable while `(IS A&B)`/`-[IS R]->` keep `IS` as the introducer.
581 /// The label-spec test is the shared offset-aware
582 /// `peek_can_start_label_expr_at`, so this lookahead and the
583 /// expression-level label reader cannot drift apart.
584 ///
585 /// Also used by the pattern-comprehension/predicate lookahead
586 /// (`node_pattern_precedes_relationship`), which must skip exactly the
587 /// tokens this reader would consume as the variable.
588 pub(super) fn peek_pattern_name_is_variable(&self, offset: usize) -> bool {
589 let ty = self.peek_at(offset).ty;
590 if !ty.is_schema_name() {
591 return false;
592 }
593 match ty {
594 TokenType::WHERE => matches!(
595 self.peek_at(offset + 1).ty,
596 TokenType::RightParen
597 | TokenType::RightBracket
598 | TokenType::Colon
599 | TokenType::IS
600 | TokenType::Parameter
601 | TokenType::Dash
602 | TokenType::ArrowLeft
603 | TokenType::WHERE
604 ),
605 TokenType::IS => !self.peek_can_start_label_expr_at(offset + 1),
606 _ => true,
607 }
608 }
609
610 /// Parses the tail shared by node and relationship elements: an optional
611 /// property spec -- a `{...}` map literal, or a bare `$param` (the
612 /// whole-map shorthand) -- followed by an optional element `WHERE`.
613 fn parse_element_property_and_where(&mut self) -> ParseResult<ElementTail> {
614 let mut tail = ElementTail::default();
615 if self.peek_type() == TokenType::LeftBrace {
616 tail.has_properties = true;
617 let pairs = self.parse_map_literal()?;
618 tail.properties = pairs.into_iter().map(|p| (p.key, p.value)).collect();
619 } else if self.peek_type() == TokenType::Parameter {
620 tail.has_properties = true;
621 let tok = self.next_token();
622 tail.properties_param = Some(Expr::Parameter(tok.literal.into_owned()));
623 }
624 if self.peek_type() == TokenType::WHERE {
625 self.next_token();
626 tail.where_expr = Some(self.parse_expression()?);
627 }
628 Ok(tail)
629 }
630
631 pub(super) fn parse_node_pattern(&mut self) -> ParseResult<NodePattern> {
632 // The probe's tree cache: a tree parked at this `(` position by
633 // a speculative probe is taken instead of re-parsed — the kit's
634 // take replays the position-after and the side-effect delta (see
635 // `parser/speculation.rs` for the insert/take policy; this is
636 // what keeps the reader-driven gate linear on adversarial
637 // nested shapes: the probe's descent builds each nested tree
638 // once and every enclosing parse moves it up, instead of each
639 // gate re-descending its whole subtree).
640 if let Some(node) = self.take_cached_node_pattern() {
641 return Ok(node);
642 }
643 let cache_pos = self.pos;
644 let flags_before = self.side_effects;
645
646 self.expect(TokenType::LeftParen)?;
647 let mut node = NodePattern {
648 variable: None,
649 label_expr: None,
650 properties: Vec::new(),
651 has_properties: false,
652 properties_param: None,
653 where_expr: None,
654 };
655
656 let tok = self.peek().clone();
657 // The element variable is a symbolic name (ADR-0191), so any
658 // keyword spelling works unquoted. `WHERE` and `IS` are read as the
659 // variable only when the one-token lookahead shows their other
660 // meaning cannot apply (`peek_pattern_name_is_variable`, which folds
661 // in the symbolic-name check): a leading `WHERE` otherwise starts
662 // the inline element predicate and a leading `IS` otherwise starts a
663 // variable-less GPM label spec (`(IS A&B)`).
664 if self.peek_pattern_name_is_variable(0) {
665 node.variable = Some(SmallName::from_name(&tok.literal));
666 self.next_token();
667 }
668
669 if matches!(self.peek_type(), TokenType::Colon | TokenType::IS) {
670 // An element's own label chain: a `{` after it is the
671 // element's inline property map, never a map projection, so
672 // the comprehension pipe-ambiguity rule must not treat it as
673 // a dead end here (see `chain_tail_ends_where`). The scoped
674 // guard keeps the depth balanced across the `?`.
675 let spec = self.with_pattern_element_depth(|p| p.parse_label_spec(false))?;
676 node.label_expr = Some(spec.expr);
677 }
678
679 // Property spec, then the element-pattern WHERE: `(var:LE {props} WHERE ...)`
680 // (CIP-17).
681 let tail = self.parse_element_property_and_where()?;
682 node.has_properties = tail.has_properties;
683 node.properties = tail.properties;
684 node.properties_param = tail.properties_param;
685 node.where_expr = tail.where_expr;
686
687 self.expect(TokenType::RightParen)?;
688 self.park_node_pattern(cache_pos, flags_before);
689 Ok(node)
690 }
691
692 /// Parses the legacy bracket-syntax variable-length hop bounds
693 /// (`*min..max`, including a bare `*`) of a relationship pattern; the
694 /// current token must be `Star`. Returns `(min, max)` -- an absent
695 /// upper bound is `None`, a bare `*` is `(1, None)`, and a single
696 /// number `*n` is the exact hop count `(n, Some(n))`. Sets
697 /// `quantifiers.legacy_bracket` for the clause-level
698 /// quantifier-mixing check.
699 fn parse_legacy_hop_bounds(&mut self) -> ParseResult<(u32, Option<u32>)> {
700 debug_assert_eq!(self.peek_type(), TokenType::Star);
701 self.side_effects.quantifiers.legacy_bracket = true;
702 self.next_token();
703 let lower = if self.peek_type() == TokenType::Integer {
704 let tok = self.next_token();
705 Some(self.parse_u32_bound(&tok, "relationship hop lower bound")?)
706 } else {
707 None
708 };
709 if self.peek_type() != TokenType::DotDot {
710 // `*` (unbounded) or `*n` (exact hop count).
711 return Ok(lower.map_or((1, None), |n| (n, Some(n))));
712 }
713 self.next_token();
714 let upper = if self.peek_type() == TokenType::Integer {
715 let tok = self.next_token();
716 Some(self.parse_u32_bound(&tok, "relationship hop upper bound")?)
717 } else {
718 None
719 };
720 Ok((lower.unwrap_or(1), upper))
721 }
722
723 pub(super) fn parse_rel_pattern(&mut self) -> ParseResult<RelPattern> {
724 let mut rel = RelPattern {
725 variable: None,
726 type_expr: None,
727 properties: Vec::new(),
728 has_properties: false,
729 properties_param: None,
730 direction: Direction::Both,
731 min_hops: None,
732 max_hops: None,
733 where_expr: None,
734 quantified: false,
735 };
736
737 let tok = self.next_token();
738 let left_arrow = tok.ty == TokenType::ArrowLeft;
739 if !left_arrow && tok.ty != TokenType::Dash {
740 return Err(
741 self.error_at_token(&tok, format!("expected - or <-, got {:?}", tok.literal))
742 );
743 }
744
745 if self.peek_type() == TokenType::LeftBracket {
746 self.next_token(); // consume [
747
748 // Variable. As with node patterns, a keyword spelling is a
749 // relationship variable too (ADR-0191); a bare `IS` here is the
750 // variable-less GPM label introducer (`-[IS R]->`) only when
751 // the lookahead does not prove it is the variable.
752 let peek = self.peek().clone();
753 if self.peek_pattern_name_is_variable(0) {
754 rel.variable = Some(SmallName::from_name(&peek.literal));
755 self.next_token();
756 }
757
758 // Types (relationship `|` disjunction predates CIP-14, so a
759 // bare top-level `|` here doesn't itself count as a GQL symbol
760 // for the clause-level mixing check).
761 // The legacy `:A|:B` separator is only legal for a bare type
762 // list; with a variable binding, an inline property map or a
763 // variable length Neo4j rejects it outright (HelpfulErrorMessages
764 // "should provide sensible error message when using colon in the
765 // separation of alternative relationship types in failing cases").
766 // The fact comes back from the type-spec parse itself, so a
767 // `HasLabel` or node-pattern parse of the same spelling cannot
768 // leave it set behind this element.
769 let mut legacy_pipe_colon = false;
770 if matches!(self.peek_type(), TokenType::Colon | TokenType::IS) {
771 // Same element-chain scope as the node arm above: the
772 // `{` of an inline rel property map is not a projection.
773 // The scoped guard keeps the depth balanced across the `?`.
774 let spec = self.with_pattern_element_depth(|p| p.parse_label_spec(true))?;
775 rel.type_expr = Some(spec.expr);
776 legacy_pipe_colon = spec.saw_legacy_pipe_colon;
777 }
778 // The element's variable, properties and hop bounds are read
779 // after the type spec, so the verdict waits until they are all
780 // known (below).
781
782 // Variable length *min..max
783 if self.peek_type() == TokenType::Star {
784 let (min, max) = self.parse_legacy_hop_bounds()?;
785 rel.min_hops = Some(min);
786 rel.max_hops = max;
787 // A negation/wildcard type expression on the legacy
788 // bracket-syntax variable-length form is accepted: it is
789 // the same AST the GPM postfix form `()-[:!A&!B]->*()`
790 // normalizes to (CIP-28 Form 5), so rejecting the bracket
791 // spelling alone is a syntax-gap, not a semantic rule
792 // (Neo4j GpmSyntaxMixingAcceptance "Var-length relationship
793 // with GPM relationship type expression - OK"; the CIP-40
794 // quantifier-mixing [12] DEVIATION row captured the older
795 // rejection and is retired with it).
796 }
797
798 // Property spec, then the element-pattern WHERE (CIP-18); the WHERE is
799 // accepted on the legacy bracket-syntax variable-length form
800 // (`[r*1..5 WHERE ...]`) too: that is the same AST the GPM postfix
801 // form `-[r WHERE ...]->{1,5}` normalizes to, so the old
802 // bracket-only rejection was a syntax-gap (Neo4j
803 // GpmSyntaxMixingAcceptance "Var-length relationship with inline
804 // predicate - OK"; the quantifier-mixing DEVIATION row
805 // captured the older rejection and is retired with it).
806 let tail = self.parse_element_property_and_where()?;
807 rel.has_properties = tail.has_properties;
808 rel.properties = tail.properties;
809 rel.properties_param = tail.properties_param;
810 rel.where_expr = tail.where_expr;
811
812 if legacy_pipe_colon
813 && (rel.variable.is_some() || rel.has_properties || rel.is_variable_length())
814 {
815 return Err(self.error(
816 "InvalidRelationshipPattern: the semantics of using colon in the separation of alternative relationship types in conjunction with the use of variable binding, inlined property predicates, or variable length is no longer supported. Please separate the relationship types with a single bar between them instead",
817 ));
818 }
819
820 // A malformed relationship bracket (a stray `..`/`-`/token where the
821 // closing `]` is expected — Match4 [9] `[:LIKES..]`, [10]
822 // `[:LIKES*-2]`) is `SyntaxError: InvalidRelationshipPattern`,
823 // not the generic `UnexpectedSyntax`.
824 self.expect_detail(TokenType::RightBracket, "InvalidRelationshipPattern")?;
825 }
826
827 // Right arrow or dash
828 let right_tok = self.next_token();
829 match right_tok.ty {
830 TokenType::ArrowRight => {
831 rel.direction = if left_arrow {
832 Direction::Both
833 } else {
834 Direction::Right
835 };
836 }
837 TokenType::Dash => {
838 rel.direction = if left_arrow {
839 Direction::Left
840 } else {
841 Direction::Both
842 };
843 }
844 _ => {
845 return Err(self.error_at_token(
846 &right_tok,
847 format!("expected -> or -, got {:?}", right_tok.literal),
848 ));
849 }
850 }
851
852 // A quantifier directly
853 // following the relationship pattern (`-[r]->*`, `-->+`,
854 // `-[]->{1,6}`, `<-[:R]-{1,3}`, `-[:R]-{2}`) normalizes to an
855 // ordinary variable-length relationship pattern with implicit
856 // boundary nodes: it declares no element variables of its own to
857 // expose as a group, so it reuses the existing var-length matcher
858 // rather than becoming a `Quantified` element. `quantified` marks
859 // this origin so the engine knows to honor an inline element-pattern
860 // WHERE per traversed edge (CIP-28 semantics), unlike the legacy
861 // `[r*min..max]` form which this grammar position never touches.
862 if matches!(
863 self.peek_type(),
864 TokenType::Star | TokenType::Plus | TokenType::LeftBrace
865 ) {
866 if rel.is_variable_length() {
867 return Err(self.error(
868 "NestedQuantification: a relationship pattern cannot be quantified twice",
869 ));
870 }
871 let quantifier = self.parse_quantifier()?;
872 rel.min_hops = Some(quantifier.min);
873 rel.max_hops = quantifier.max;
874 rel.quantified = true;
875 self.side_effects.quantifiers.gpm_form = true;
876 }
877
878 Ok(rel)
879 }
880}
881
882/// Whether a CIP-73 path selector is *selective* in Neo4j's sense: an
883/// explicit selector other than `ALL`. `None` (the implicit selector) and
884/// `ALL` are the non-selective spellings; `ANY`, `ANY SHORTEST`,
885/// `ALL SHORTEST` and `SHORTEST <n>` are selective. Neo4j 2026 accepts a
886/// named parenthesized sub-path only under a selective search (42N42).
887pub fn selector_is_selective(selector: Option<&PathSelector>) -> bool {
888 matches!(
889 selector,
890 Some(
891 PathSelector::Any(_)
892 | PathSelector::AnyShortest
893 | PathSelector::AllShortest
894 | PathSelector::Shortest { .. }
895 )
896 )
897}