Skip to main content

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        self.expect(TokenType::LeftParen)?;
633        let mut node = NodePattern {
634            variable: None,
635            label_expr: None,
636            properties: Vec::new(),
637            has_properties: false,
638            properties_param: None,
639            where_expr: None,
640        };
641
642        let tok = self.peek().clone();
643        // The element variable is a symbolic name (ADR-0191), so any
644        // keyword spelling works unquoted. `WHERE` and `IS` are read as the
645        // variable only when the one-token lookahead shows their other
646        // meaning cannot apply (`peek_pattern_name_is_variable`, which folds
647        // in the symbolic-name check): a leading `WHERE` otherwise starts
648        // the inline element predicate and a leading `IS` otherwise starts a
649        // variable-less GPM label spec (`(IS A&B)`).
650        if self.peek_pattern_name_is_variable(0) {
651            node.variable = Some(SmallName::from_name(&tok.literal));
652            self.next_token();
653        }
654
655        if matches!(self.peek_type(), TokenType::Colon | TokenType::IS) {
656            node.label_expr = Some(self.parse_label_spec(false)?.expr);
657        }
658
659        // Property spec, then the element-pattern WHERE: `(var:LE {props} WHERE ...)`
660        // (CIP-17).
661        let tail = self.parse_element_property_and_where()?;
662        node.has_properties = tail.has_properties;
663        node.properties = tail.properties;
664        node.properties_param = tail.properties_param;
665        node.where_expr = tail.where_expr;
666
667        self.expect(TokenType::RightParen)?;
668        Ok(node)
669    }
670
671    /// Parses the legacy bracket-syntax variable-length hop bounds
672    /// (`*min..max`, including a bare `*`) of a relationship pattern; the
673    /// current token must be `Star`. Returns `(min, max)` -- an absent
674    /// upper bound is `None`, a bare `*` is `(1, None)`, and a single
675    /// number `*n` is the exact hop count `(n, Some(n))`. Sets
676    /// `quantifiers.legacy_bracket` for the clause-level
677    /// quantifier-mixing check.
678    fn parse_legacy_hop_bounds(&mut self) -> ParseResult<(u32, Option<u32>)> {
679        debug_assert_eq!(self.peek_type(), TokenType::Star);
680        self.side_effects.quantifiers.legacy_bracket = true;
681        self.next_token();
682        let lower = if self.peek_type() == TokenType::Integer {
683            let tok = self.next_token();
684            Some(self.parse_u32_bound(&tok, "relationship hop lower bound")?)
685        } else {
686            None
687        };
688        if self.peek_type() != TokenType::DotDot {
689            // `*` (unbounded) or `*n` (exact hop count).
690            return Ok(lower.map_or((1, None), |n| (n, Some(n))));
691        }
692        self.next_token();
693        let upper = if self.peek_type() == TokenType::Integer {
694            let tok = self.next_token();
695            Some(self.parse_u32_bound(&tok, "relationship hop upper bound")?)
696        } else {
697            None
698        };
699        Ok((lower.unwrap_or(1), upper))
700    }
701
702    pub(super) fn parse_rel_pattern(&mut self) -> ParseResult<RelPattern> {
703        let mut rel = RelPattern {
704            variable: None,
705            type_expr: None,
706            properties: Vec::new(),
707            has_properties: false,
708            properties_param: None,
709            direction: Direction::Both,
710            min_hops: None,
711            max_hops: None,
712            where_expr: None,
713            quantified: false,
714        };
715
716        let tok = self.next_token();
717        let left_arrow = tok.ty == TokenType::ArrowLeft;
718        if !left_arrow && tok.ty != TokenType::Dash {
719            return Err(
720                self.error_at_token(&tok, format!("expected - or <-, got {:?}", tok.literal))
721            );
722        }
723
724        if self.peek_type() == TokenType::LeftBracket {
725            self.next_token(); // consume [
726
727            // Variable. As with node patterns, a keyword spelling is a
728            // relationship variable too (ADR-0191); a bare `IS` here is the
729            // variable-less GPM label introducer (`-[IS R]->`) only when
730            // the lookahead does not prove it is the variable.
731            let peek = self.peek().clone();
732            if self.peek_pattern_name_is_variable(0) {
733                rel.variable = Some(SmallName::from_name(&peek.literal));
734                self.next_token();
735            }
736
737            // Types (relationship `|` disjunction predates CIP-14, so a
738            // bare top-level `|` here doesn't itself count as a GQL symbol
739            // for the clause-level mixing check).
740            // The legacy `:A|:B` separator is only legal for a bare type
741            // list; with a variable binding, an inline property map or a
742            // variable length Neo4j rejects it outright (HelpfulErrorMessages
743            // "should provide sensible error message when using colon in the
744            // separation of alternative relationship types in failing cases").
745            // The fact comes back from the type-spec parse itself, so a
746            // `HasLabel` or node-pattern parse of the same spelling cannot
747            // leave it set behind this element.
748            let mut legacy_pipe_colon = false;
749            if matches!(self.peek_type(), TokenType::Colon | TokenType::IS) {
750                let spec = self.parse_label_spec(true)?;
751                rel.type_expr = Some(spec.expr);
752                legacy_pipe_colon = spec.saw_legacy_pipe_colon;
753            }
754            // The element's variable, properties and hop bounds are read
755            // after the type spec, so the verdict waits until they are all
756            // known (below).
757
758            // Variable length *min..max
759            if self.peek_type() == TokenType::Star {
760                let (min, max) = self.parse_legacy_hop_bounds()?;
761                rel.min_hops = Some(min);
762                rel.max_hops = max;
763                // A negation/wildcard type expression on the legacy
764                // bracket-syntax variable-length form is accepted: it is
765                // the same AST the GPM postfix form `()-[:!A&!B]->*()`
766                // normalizes to (CIP-28 Form 5), so rejecting the bracket
767                // spelling alone is a syntax-gap, not a semantic rule
768                // (Neo4j GpmSyntaxMixingAcceptance "Var-length relationship
769                // with GPM relationship type expression - OK"; the CIP-40
770                // quantifier-mixing [12] DEVIATION row captured the older
771                // rejection and is retired with it).
772            }
773
774            // Property spec, then the element-pattern WHERE (CIP-18); the WHERE is
775            // accepted on the legacy bracket-syntax variable-length form
776            // (`[r*1..5 WHERE ...]`) too: that is the same AST the GPM postfix
777            // form `-[r WHERE ...]->{1,5}` normalizes to, so the old
778            // bracket-only rejection was a syntax-gap (Neo4j
779            // GpmSyntaxMixingAcceptance "Var-length relationship with inline
780            // predicate - OK"; the quantifier-mixing DEVIATION row
781            // captured the older rejection and is retired with it).
782            let tail = self.parse_element_property_and_where()?;
783            rel.has_properties = tail.has_properties;
784            rel.properties = tail.properties;
785            rel.properties_param = tail.properties_param;
786            rel.where_expr = tail.where_expr;
787
788            if legacy_pipe_colon
789                && (rel.variable.is_some() || rel.has_properties || rel.min_hops.is_some())
790            {
791                return Err(self.error(
792                    "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",
793                ));
794            }
795
796            // A malformed relationship bracket (a stray `..`/`-`/token where the
797            // closing `]` is expected — Match4 [9] `[:LIKES..]`, [10]
798            // `[:LIKES*-2]`) is `SyntaxError: InvalidRelationshipPattern`,
799            // not the generic `UnexpectedSyntax`.
800            self.expect_detail(TokenType::RightBracket, "InvalidRelationshipPattern")?;
801        }
802
803        // Right arrow or dash
804        let right_tok = self.next_token();
805        match right_tok.ty {
806            TokenType::ArrowRight => {
807                rel.direction = if left_arrow {
808                    Direction::Both
809                } else {
810                    Direction::Right
811                };
812            }
813            TokenType::Dash => {
814                rel.direction = if left_arrow {
815                    Direction::Left
816                } else {
817                    Direction::Both
818                };
819            }
820            _ => {
821                return Err(self.error_at_token(
822                    &right_tok,
823                    format!("expected -> or -, got {:?}", right_tok.literal),
824                ));
825            }
826        }
827
828        // A quantifier directly
829        // following the relationship pattern (`-[r]->*`, `-->+`,
830        // `-[]->{1,6}`, `<-[:R]-{1,3}`, `-[:R]-{2}`) normalizes to an
831        // ordinary variable-length relationship pattern with implicit
832        // boundary nodes: it declares no element variables of its own to
833        // expose as a group, so it reuses the existing var-length matcher
834        // rather than becoming a `Quantified` element. `quantified` marks
835        // this origin so the engine knows to honor an inline element-pattern
836        // WHERE per traversed edge (CIP-28 semantics), unlike the legacy
837        // `[r*min..max]` form which this grammar position never touches.
838        if matches!(
839            self.peek_type(),
840            TokenType::Star | TokenType::Plus | TokenType::LeftBrace
841        ) {
842            if rel.is_variable_length() {
843                return Err(self.error(
844                    "NestedQuantification: a relationship pattern cannot be quantified twice",
845                ));
846            }
847            let quantifier = self.parse_quantifier()?;
848            rel.min_hops = Some(quantifier.min);
849            rel.max_hops = quantifier.max;
850            rel.quantified = true;
851            self.side_effects.quantifiers.gpm_form = true;
852        }
853
854        Ok(rel)
855    }
856}
857
858/// Whether a CIP-73 path selector is *selective* in Neo4j's sense: an
859/// explicit selector other than `ALL`. `None` (the implicit selector) and
860/// `ALL` are the non-selective spellings; `ANY`, `ANY SHORTEST`,
861/// `ALL SHORTEST` and `SHORTEST <n>` are selective. Neo4j 2026 accepts a
862/// named parenthesized sub-path only under a selective search (42N42).
863pub fn selector_is_selective(selector: Option<&PathSelector>) -> bool {
864    matches!(
865        selector,
866        Some(
867            PathSelector::Any(_)
868                | PathSelector::AnyShortest
869                | PathSelector::AllShortest
870                | PathSelector::Shortest { .. }
871        )
872    )
873}