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