Skip to main content

relate_parser/parser/
mod.rs

1use crate::ast::*;
2use crate::error::{ParseError, ParseResult, SUPPORTED_CYPHER_VERSION};
3use crate::lexer::tokenize_with_options;
4use crate::token::{is_clause_boundary, is_contextual_clause_keyword, Token, TokenType};
5use relate_names::SmallName;
6mod comprehension_where;
7mod side_effects;
8mod speculation;
9
10use comprehension_where::BracketProof;
11use side_effects::{LabelMixFlags, LabelMixTarget, PatternSideEffectFlags, QuantifierForms};
12use speculation::{ProbeGate, Speculation};
13
14// `pub(crate)` beyond the parser module for the statement normalizer
15// (ADR-0503), which extracts the same values the parser would bind.
16use interp::parse_interp_body;
17use is_predicate::{IsLabelPolicy, Suffix};
18pub(crate) use literals::parse_int_literal;
19use literals::{IntLiteralError, IntLiteralSite};
20
21/// `parse_constraint_for_target_ext`'s result: the `FOR <pattern>` target of
22/// a `CREATE CONSTRAINT`.
23struct ConstraintForTarget {
24    entity_type: SchemaEntityType,
25    /// The flat label/relationship-type list (empty for a label-less
26    /// target).
27    labels: Vec<SmallName>,
28    /// The FOR pattern's own variable, `""` when it has none (the shape
29    /// `CreateConstraintClause::variable` stores).
30    variable: SmallName,
31    /// A relationship pattern's source endpoint alias (CIP-177); `None`
32    /// for a node target or an alias-less endpoint.
33    source_alias: Option<SmallName>,
34    /// A relationship pattern's target endpoint alias, like `source_alias`.
35    target_alias: Option<SmallName>,
36}
37
38/// `parse_graph_type_constraint_verb`'s return shape: the constraint kind,
39/// the parsed `<value type>` for a `PropertyType` kind, and the `OPTIONS`
40/// tail.
41struct GraphTypeConstraintVerbSpec {
42    kind: GraphTypeConstraintVerb,
43    /// The `<value type>` of a `PropertyType` kind, `None` otherwise.
44    property_type: Option<TypeExpr>,
45    options: OptionsForm,
46}
47
48/// ADR-0257: maximum size of a Cypher query text accepted by [`parse`], in
49/// bytes (4 MiB). Enforced *before lexing* so that adversarial inputs cannot
50/// amplify into unbounded token allocations (LABS-81: 8 MiB of commas used to
51/// become >=520 MB of tokens). Every query path -- the Rust API, the C ABI,
52/// the CLI, the TCK, and Bolt -- funnels through the parser's entry points,
53/// each of which constructs through `Parser::new`, the one site the cap is
54/// enforced, so this single check covers them all.
55pub const MAX_QUERY_BYTES: usize = 4 * 1024 * 1024; // 4 MiB = 4 194 304
56
57/// ADR-0257: maximum nesting depth accepted while parsing. Enforced on
58/// expression nesting (every nested expression -- parenthesized constructs,
59/// list/map literals, function-call arguments, subqueries, ... -- descends
60/// through [`Parser::parse_expression`]; `NOT` chains recurse through
61/// [`Parser::parse_not`]) and on statement nesting (subquery bodies).
62/// Recursive-descent parsing beyond this depth risks a stack-overflow abort,
63/// which -- when the engine is embedded via the C ABI -- kills the host
64/// process instead of surfacing a recoverable error (LABS-69). The front-end
65/// lowering boundary enforces the same limit on its own walkers.
66pub const MAX_NESTING_DEPTH: u32 = 500;
67
68/// ADR-0116 §2: the [`ParseError::detail`] tag on a parse failure for a
69/// recognized-but-unsupported database administration command (everything
70/// outside CE's supported set on Relate's fixed namespaces). The
71/// error's `message` carries the verbatim statement text (without a leading
72/// `CYPHER n` preamble), so `relate-front` can raise CE's
73/// `UnsupportedAdministrationCommand` (51N27) echoing it. The tag name
74/// matches `ErrorKind::UnsupportedAdministrationCommand` in
75/// `relate-error`, so even an unmapped parse error keeps the right TCK
76/// kind/class.
77pub const UNSUPPORTED_ADMINISTRATION_DETAIL: &str = "UnsupportedAdministrationCommand";
78
79/// The [`ParseError::detail`] tag naming the undefined-variable condition
80/// (Neo4j 42N62): every parser site that rejects an unbound name carries it,
81/// so `EngineError::kind()` surfaces `UndefinedVariable` instead of the
82/// generic `UnexpectedSyntax` fallback. The tag name matches
83/// `ErrorKind::UndefinedVariable` in `relate-error`.
84pub const UNDEFINED_VARIABLE_DETAIL: &str = "UndefinedVariable";
85
86/// Parse a Cypher query string into a Statement AST.
87pub fn parse(input: &str) -> ParseResult<Statement> {
88    parse_with_options(input, crate::lexer::ParseOptions::default())
89}
90
91/// Parse a Cypher query string into a Statement AST under
92/// parse-affecting preview opt-ins ([`crate::lexer::ParseOptions`]: the
93/// ADR-0371 gate set the caller's store resolved from
94/// `RELATE_PREVIEW`, threaded here by `relate-front`'s preview
95/// admission). [`crate::lexer::ParseOptions::default`] is the dialect
96/// floor: every option widens acceptance of a form the floor rejects,
97/// never narrows it, so the ungated [`parse`] is exactly
98/// `parse_with_options` with all options off. The ADR-0257 size cap rides
99/// the constructor (`Parser::new`'s first statement), the parser's one
100/// tokenizing site -- not this entry point.
101pub fn parse_with_options(
102    input: &str,
103    options: crate::lexer::ParseOptions,
104) -> ParseResult<Statement> {
105    let mut parser = Parser::new(input, "query text", options)?;
106    parser.parse()
107}
108
109/// Parse a bare value expression under explicit parse-affecting preview
110/// opt-ins ([`crate::lexer::ParseOptions`]). Used for CIP-261 interpolation
111/// embeds: the `{...}` body of an interpolated string literal is a full
112/// expression, sub-parsed by [`parse_interp_body`] with the options of the
113/// parse that lexed the enclosing statement, so an embed observes the
114/// caller's dialect gates instead of silently re-parsing under the floor.
115/// `pub(crate)`: its only callers are in this crate (the public floor
116/// wrapper [`parse_expression_str`] and the embed sub-parse); it is
117/// promoted to `pub` -- with a root re-export beside
118/// [`parse`]/[`parse_with_options`] -- when a second crate needs gated
119/// expression parsing. The ADR-0257 size cap rides the constructor
120/// (`Parser::new`'s first statement), the parser's one tokenizing site --
121/// not this entry point.
122pub(crate) fn parse_expression_str_with_options(
123    input: &str,
124    options: crate::lexer::ParseOptions,
125) -> ParseResult<Expr> {
126    let mut parser = Parser::new(input, "expression text", options)?;
127    let expr = parser.parse_expression()?;
128    if parser.peek().ty != TokenType::EOF {
129        return Err(parser
130            .error_at_token(parser.peek(), "unexpected trailing input in expression")
131            .with_detail("UnexpectedSyntax"));
132    }
133    Ok(expr)
134}
135
136/// Parse a bare value expression on the dialect floor
137/// ([`crate::lexer::ParseOptions::default`]) -- the public wrapper for
138/// callers with no preview gates to thread; gated callers (and the
139/// interpolation-embed sub-parse) use `parse_expression_str_with_options`.
140pub fn parse_expression_str(input: &str) -> ParseResult<Expr> {
141    parse_expression_str_with_options(input, crate::lexer::ParseOptions::default())
142}
143
144/// Parse a bare `<graph type specification body>` -- the `{ ... }` grammar
145/// shared by `CREATE GRAPH TYPE`/`ALTER CURRENT GRAPH TYPE`, without the
146/// surrounding statement (`canonical` is wrapped in braces here, so callers
147/// pass the CIP-180 canonical form's comma-joined contents, no braces of
148/// their own). Used by `relate-executor`'s `Graph` to reconstruct a
149/// persisted `current_graph_type` model from the snapshot manifest on load
150/// -- see `Graph::restore_graph_type_spec`. The ADR-0257 size cap rides the
151/// constructor (`Parser::new`'s first statement) and checks the wrapped
152/// string -- the exact text this entry point lexes.
153pub fn parse_graph_type_body(canonical: &str) -> ParseResult<GraphTypeBody> {
154    let wrapped = format!("{{{canonical}}}");
155    let mut parser = Parser::new(
156        &wrapped,
157        "graph type body",
158        crate::lexer::ParseOptions::default(),
159    )?;
160    let (open, body) = parser.parse_graph_type_spec_body()?;
161    parser.reject_bare_constraint_drops(&open, &body)?;
162    Ok(body)
163}
164
165/// CIP-150: the pre-parser option keys Relate recognizes after a
166/// `CYPHER [<version>]` clause (besides the version itself). These mirror
167/// Neo4j's own pre-parser option vocabulary; Relate validates that a
168/// key is recognized and internally consistent but -- since it implements
169/// only one query-execution engine/runtime -- doesn't act on any of their
170/// values.
171const CYPHER_OPTION_KEYS: &[&str] = &[
172    "planner",
173    "runtime",
174    "updatestrategy",
175    "expressionengine",
176    "replan",
177    "connectcomponentsplanner",
178    "debug",
179    "operatorengine",
180];
181
182/// CIP-150 / Neo4j 2026.10: the pre-parser option keys whose *values*
183/// carry a constrained vocabulary, with each key's valid values -- the
184/// value-side twin of [`CYPHER_OPTION_KEYS`]' 22N07 key check. The one
185/// key with a vocabulary today is `runtime`, mirroring the three runtimes
186/// of Neo4j's current line (slotted, pipelined, parallel; the CIP-150
187/// corpus's accepted `runtime=slotted` examples pin the Cypher-5 side of
188/// that set). Relate implements a single engine, so every listed
189/// value is accepted-and-ignored; any other value fails with an authored
190/// 22N10 error naming the valid set.
191const CYPHER_OPTION_VALUES: &[(&str, &[&str])] =
192    &[("runtime", &["slotted", "pipelined", "parallel"])];
193
194/// The recursive-descent parser over a borrowed token stream. `'a` is the
195/// input query text's lifetime: the [`Token`] literals and [`Self::source`]
196/// borrow it (ADR-0505), and the parser — built and dropped inside the
197/// parse entry points — never outlives it. The AST it produces stays
198/// `'static` (owned strings).
199struct Parser<'a> {
200    source: &'a str,
201    tokens: Vec<Token<'a>>,
202    pos: usize,
203    /// Byte offset of the first byte of each 1-based source line
204    /// (`line_starts[0] == 0` is line 1's start). Precomputed once per parse
205    /// so `token_byte_offset` is O(1) instead of rescanning the whole source
206    /// per projection item. The lexer counts columns in *bytes* (see
207    /// `Lexer::advance`), so a token's byte offset is exactly
208    /// `line_starts[line - 1] + col - 1` — this also fixes the old
209    /// char-counted scan, which mismatched the lexer's byte-counted columns
210    /// (and returned `None`) as soon as any non-ASCII char preceded the
211    /// token.
212    line_starts: Vec<usize>,
213    /// The clause-level pattern side-effect flags (label/quantifier mixing
214    /// state); see [`PatternSideEffectFlags`]. One field so a speculative
215    /// parse can snapshot/restore it by plain assignment.
216    side_effects: PatternSideEffectFlags,
217    /// Nesting depth of `parse_when_query` branch/ELSE bodies currently
218    /// being parsed -- 0 outside any such body. While positive, a bare
219    /// (non-brace) body's own clause loop (`parse_statement`) must stop at
220    /// a following `WHEN` too, not just `ELSE`/EOF/etc, so control returns
221    /// to `parse_when_query`'s own loop to see the next branch (CIP-213
222    /// `next_conditional_interactions.feature`: `WHEN a THEN RETURN
223    /// x WHEN b THEN RETURN y ELSE RETURN z`, no braces anywhere). Scoped
224    /// to *this* mechanism only -- a bare `WHEN` appearing after an
225    /// ordinary clause outside any WHEN-body context (e.g. `MATCH (n)
226    /// WHEN ...`) must remain a hard parse error (CIP-135
227    /// syntax_placement.feature [8]/[9]), so this must stay zero there.
228    in_when_branch_body: u32,
229    /// Nesting depth of `parse_statement` calls -- 0 outside any statement,
230    /// 1 while parsing the outermost statement, 2+ while parsing a nested
231    /// `EXISTS {}`/`COUNT {}`/`CALL {}` subquery's own statement body. Used
232    /// to scope the label-expression mixing flags to one top-level
233    /// statement; see `parse_statement`'s doc comment. Also capped at
234    /// [`MAX_NESTING_DEPTH`] (ADR-0257) so deeply nested subquery bodies
235    /// cannot overflow the stack via pure statement recursion.
236    statement_depth: u32,
237    /// Current statement-block nesting depth (ADR-0257): incremented on
238    /// entering `parse_statement_block`, decremented on exit. Every
239    /// statement-nesting cycle funnels through `parse_statement_block` --
240    /// CALL/EXISTS/COUNT/COLLECT subquery bodies, brace-enclosed nested
241    /// procedure specifications (`{ { ... } }`), and WHEN/ELSE bodies
242    /// (`WHEN ... THEN { WHEN ... }`) -- including the cycles that bypass
243    /// `parse_statement`, `parse_clause`, and `parse_expression` and so
244    /// never engage any other counter (LABS-69: ~3000 nested braces used
245    /// to SIGABRT on an 8 MiB release stack). Unlike `statement_depth`,
246    /// this counter is *not* consulted for label-mixing scoping, so a
247    /// top-level `{ ... }` body incrementing it cannot flip
248    /// `is_outer_clause`. Capped at [`MAX_NESTING_DEPTH`].
249    block_depth: u32,
250    /// Current expression nesting depth (ADR-0257): incremented on entering
251    /// `parse_expression` and on each recursive `parse_not` step, decremented
252    /// on exit. Every nested expression -- parenthesized constructs, list
253    /// literals, map literals, function-call arguments, CASE operands,
254    /// comprehension bodies, subquery WHERE/RETURN expressions -- descends
255    /// through `parse_expression`, so this one counter bounds all expression
256    /// recursion. Also counts recursion cycles that bypass
257    /// `parse_expression` but are expression-shaped: unary `-`/`!` chains,
258    /// nested label/subpath parens, and nested `LIST<...>`/`ANY<...>`
259    /// value-type brackets (see `parse_value_type`). Capped at
260    /// [`MAX_NESTING_DEPTH`] (LABS-69).
261    expr_depth: u32,
262    /// Current clause nesting depth (ADR-0257): incremented on entering
263    /// `parse_clause`, decremented on exit. Both callers of `parse_clause`
264    /// (`parse_statement`'s body loop and `parse_foreach`'s body loop) are
265    /// loops, so the counter returns to baseline after every clause and
266    /// only grows with *true* clause nesting. That nesting exists: nested
267    /// FOREACH bodies recurse `parse_clause` -> `parse_clause_inner` ->
268    /// `parse_foreach` -> `parse_clause`, bypassing `parse_statement`, so
269    /// the `statement_depth` cap never engages on that cycle (LABS-69).
270    /// Capped at [`MAX_NESTING_DEPTH`].
271    clause_depth: u32,
272    /// The comprehension-WHERE context currently active, if any: which
273    /// comprehension's `WHERE`-part expression (or `IN` source
274    /// expression) is being parsed — carrying the bracket proof that
275    /// decides the `]` arm of the label side's tail classification (see
276    /// [`BracketProof`]) — one state with one lifecycle
277    /// owner, [`Parser::with_comprehension_where`].
278    /// While a context is active a bare `|` is genuinely ambiguous: it
279    /// could continue a label-expression disjunction (`x:A|B`), continue
280    /// a `<value type>` union (`IS :: STRING | INTEGER`) or be the
281    /// comprehension's own map-expression separator (`WHERE x:A |
282    /// expr]`). `parse_label_or` and the type-union loop
283    /// (`parse_value_type_at_current_depth`) resolve that through the one
284    /// shared mechanism, [`Parser::ambiguous_pipe_continuation`], which
285    /// consults this state before committing to the disjunction/union
286    /// reading.
287    comprehension_where: Option<BracketProof>,
288    /// Depth of `EXISTS { … }` bodies currently being parsed. An unbounded
289    /// quantified path pattern under REPEATABLE ELEMENTS is safe inside an
290    /// existence probe (the probe stops at the first row) and is accepted
291    /// there, while a top-level match still rejects it (42N53).
292    exists_subquery_depth: u32,
293    /// The speculative-probe state — probe depth, the per-(position,
294    /// gate) verdict memo, and the node-pattern tree cache — one owner
295    /// with the policies documented on it (`parser/speculation.rs`).
296    speculation: Speculation,
297    /// Nesting depth of pattern-element label/type chain parses (a node
298    /// pattern's labels, a relationship pattern's types), guarded by the
299    /// `depth_guard_family!` registration below. Inside an element's own
300    /// chain a `{` is the element's inline property map, not a map
301    /// projection, so the comprehension pipe-ambiguity rule's `{` dead
302    /// end must not fire there — `chain_tail_ends_where` gates its
303    /// `{` and `]` arms through this; the element parsers scope their
304    /// `parse_label_spec` calls
305    /// through [`Parser::with_pattern_element_depth`].
306    pattern_element_depth: u32,
307    /// The parse-affecting preview opt-ins for this parse (see
308    /// [`crate::lexer::ParseOptions`]). Set once by `Parser::new` from the
309    /// entry point's options; never mutated mid-parse, so nested and
310    /// speculative parses all observe one dialect.
311    options: crate::lexer::ParseOptions,
312    /// Which label-mixing accumulator the clause being parsed feeds (see
313    /// [`LabelMixTarget`]). Saved and restored around each clause so a
314    /// nested subquery body's clauses choose their own side.
315    label_mix_target: LabelMixTarget,
316}
317
318/// A single postfix accessor (`.prop` or CIP-131's `[<expr>]`) parsed after
319/// a SET/REMOVE target's base expression by `Parser::parse_property_target_accessors`.
320enum PropertyTargetAccessor {
321    Static(SmallName),
322    Dynamic(Expr),
323}
324
325/// Generates the `enter_*_depth` / `exit_*_depth` / `with_*_depth` triple
326/// for one depth-guard counter field (ADR-0257, LABS-69). The four
327/// families (`expr_depth`, `clause_depth`, `statement_depth`,
328/// `block_depth`) share one mechanically identical shape; generating them
329/// from a single definition keeps the balanced-enter/exit property true by
330/// construction: `enter` leaves the counter unchanged on error, `exit` is
331/// a saturating decrement, and `with` captures `f`'s result (including
332/// error propagation), decrements, and only then returns, so no `?` can
333/// ever sit between enter and exit. The limit check and error message are
334/// byte-identical across families.
335macro_rules! depth_guard_family {
336    (
337        field = $field:ident,
338        enter = $enter:ident,
339        exit = $exit:ident,
340        with = $with:ident,
341        enter_doc = $enter_doc:expr,
342        exit_doc = $exit_doc:expr,
343        with_doc = $with_doc:expr $(,)?
344    ) => {
345        #[doc = $enter_doc]
346        fn $enter(&mut self) -> ParseResult<()> {
347            if self.$field >= MAX_NESTING_DEPTH {
348                return Err(self.error(format!(
349                    "maximum nesting depth of {MAX_NESTING_DEPTH} exceeded"
350                )));
351            }
352            self.$field += 1;
353            Ok(())
354        }
355
356        #[doc = $exit_doc]
357        fn $exit(&mut self) {
358            self.$field = self.$field.saturating_sub(1);
359        }
360
361        #[doc = $with_doc]
362        fn $with<T>(&mut self, f: impl FnOnce(&mut Self) -> ParseResult<T>) -> ParseResult<T> {
363            self.$enter()?;
364            let result = f(self);
365            self.$exit();
366            result
367        }
368    };
369}
370
371/// The running base of [`Parser::parse_postfix`]'s postfix chain, making
372/// the namespace-call accumulation invariant structural instead of
373/// comment-held.
374///
375/// While a dot-chain the memoized `scan_dot_chain_for_call` classified as
376/// ending in `(` is being accumulated, the base is [`PostfixBase::NsPath`]
377/// — a bare namespace-path string with *no* `Expr` — so no postfix arm can
378/// observe or rebuild a stale intermediate expression (materializing one
379/// per segment cost Θ(n²) in string clones, a parse-time DoS on maximal
380/// inputs). Everywhere else the base is [`PostfixBase::Built`].
381enum PostfixBase {
382    /// A materialized expression, plus its namespace path while it is a
383    /// plain dotted path (a `Variable`, or a property chain over one) —
384    /// maintained incrementally so a long `a.b.c...` chain costs amortized
385    /// O(1) per segment instead of re-walking and re-`format!`ing the
386    /// whole chain per dot. `None` once any non-path postfix form
387    /// (subscript, map projection, function call) has been applied.
388    Built(Expr, Option<String>),
389    /// A call-bound dot-chain accumulated as a bare path string. Entered
390    /// only under the scan's ends-in-`(` verdict, so mid-chain the token
391    /// after each `.ident` is always `.` or `(`, and the chain's
392    /// terminating `(` arm — which builds the `FunctionCall` name from
393    /// this path — is the only way out.
394    NsPath(String),
395}
396
397impl<'a> Parser<'a> {
398    /// Builds a parser over `source` under one explicit dialect: the
399    /// constructor tokenizes the source itself via
400    /// [`tokenize_with_options`], so the token stream and the
401    /// [`crate::lexer::ParseOptions`] that lexed it are one fact, never two
402    /// independently supplied arguments that could disagree. Every entry
403    /// point (`parse_with_options`, `parse_expression_str_with_options`,
404    /// `parse_graph_type_body`) passes its options here -- the ungated floor
405    /// entry points pass [`crate::lexer::ParseOptions::default`] explicitly,
406    /// and `parse_with_options` forwards the caller's preview gates -- so a
407    /// `Parser` can never exist half-configured.
408    ///
409    /// The constructor is the parser's only tokenizing site, so the
410    /// ADR-0257 admission cap ([`MAX_QUERY_BYTES`]) is structural here, not
411    /// a convention each entry point must remember to enforce: the first
412    /// statement checks `source.len()` *before* lexing, so adversarial
413    /// input cannot amplify into unbounded token allocations (LABS-81: 8
414    /// MiB of commas used to become over 520 MB of tokens). `subject` only
415    /// labels the input kind in the over-cap error message.
416    fn new(
417        source: &'a str,
418        subject: &str,
419        options: crate::lexer::ParseOptions,
420    ) -> Result<Self, ParseError> {
421        if source.len() > MAX_QUERY_BYTES {
422            return Err(ParseError::new(
423                format!(
424                    "{subject} of {} bytes exceeds the maximum query size of {MAX_QUERY_BYTES} bytes",
425                    source.len()
426                ),
427                1,
428                1,
429            ));
430        }
431        let tokens = tokenize_with_options(source, options);
432        Ok(Parser {
433            source,
434            line_starts: crate::token::line_starts_of(source),
435            tokens,
436            pos: 0,
437            side_effects: PatternSideEffectFlags::default(),
438            label_mix_target: LabelMixTarget::None,
439            in_when_branch_body: 0,
440            statement_depth: 0,
441            block_depth: 0,
442            expr_depth: 0,
443            clause_depth: 0,
444            comprehension_where: None,
445            exists_subquery_depth: 0,
446            speculation: Speculation::default(),
447            pattern_element_depth: 0,
448            options,
449        })
450    }
451
452    // ---- Token access ----
453
454    /// The synthetic past-the-end EOF sentinel — the one spelling of the
455    /// token every out-of-range probe returns. `Token<'static>` covariantly
456    /// subtypes to any `Token<'a>`, so one shared empty-literal instance
457    /// serves every parse.
458    fn eof_token() -> &'static Token<'static> {
459        static EOF: std::sync::OnceLock<Token<'static>> = std::sync::OnceLock::new();
460        EOF.get_or_init(|| Token::new(TokenType::EOF, "", 0, 0))
461    }
462
463    fn peek(&self) -> &Token<'a> {
464        self.peek_at(0)
465    }
466
467    fn peek_type(&self) -> TokenType {
468        self.peek().ty
469    }
470
471    /// Looks ahead `offset` tokens past the current position (0 == `peek`)
472    /// without consuming anything.
473    fn peek_at(&self, offset: usize) -> &Token<'a> {
474        let idx = self.pos + offset;
475        if idx >= self.tokens.len() {
476            Self::eof_token()
477        } else {
478            &self.tokens[idx]
479        }
480    }
481
482    /// True if the current token is a case-insensitive identifier matching
483    /// `word` — the generic probe for the many contextual keywords that are
484    /// not reserved words in the lexer: type grammar words (`VALUE`,
485    /// `PROPERTY`, `MAP`) and schema/administration words (`DEFAULT`,
486    /// `KEY`, ...).
487    pub(super) fn peek_is_ident(&self, word: &str) -> bool {
488        self.peek_at_is_ident(0, word)
489    }
490
491    /// Like `peek_is_ident`, but `offset` tokens ahead (0 == `peek_is_ident`).
492    pub(super) fn peek_at_is_ident(&self, offset: usize, word: &str) -> bool {
493        Self::token_is_ident(self.peek_at(offset), word)
494    }
495
496    /// True if `tok` is a case-insensitive identifier matching `word` — the
497    /// token-level core of [`Self::peek_at_is_ident`], for call sites that
498    /// already hold the token.
499    pub(super) fn token_is_ident(tok: &Token, word: &str) -> bool {
500        tok.ty == TokenType::Identifier && tok.literal.eq_ignore_ascii_case(word)
501    }
502
503    /// True when the cursor is on the `ALL` set-quantifier spelling
504    /// (`count(ALL x)`, `collect(ALL x)`, `RETURN ALL`, `GROUP BY ALL`),
505    /// false for the `all(x IN list WHERE predicate)` list-predicate
506    /// function: `ALL` immediately followed by `(` is always the function,
507    /// the same priority the RETURN/WITH/GROUP-BY modifier readers apply.
508    /// The one spelling of that rule, shared by every set-quantifier site so
509    /// a nested `all(...)` inside an argument list cannot be swallowed as
510    /// the aggregate's quantifier.
511    pub(super) fn all_is_set_quantifier(&self) -> bool {
512        self.peek_type() == TokenType::ALL && self.peek_at(1).ty != TokenType::LeftParen
513    }
514
515    /// Consume and return the current token. The value is cloned out of the
516    /// stream because `backup`/`restore_pos` re-read tokens from
517    /// `self.tokens` after they have been consumed; with ADR-0505's borrowed
518    /// literals that clone is a pointer copy, not a heap allocation (only
519    /// the rare owned literal — an escaped string, a formatted error — pays
520    /// a String clone here).
521    fn next_token(&mut self) -> Token<'a> {
522        if self.pos >= self.tokens.len() {
523            Self::eof_token().clone()
524        } else {
525            let tok = self.tokens[self.pos].clone();
526            self.pos += 1;
527            tok
528        }
529    }
530
531    fn backup(&mut self) {
532        if self.pos > 0 {
533            self.pos -= 1;
534        }
535    }
536
537    fn save_pos(&self) -> usize {
538        self.pos
539    }
540
541    fn restore_pos(&mut self, pos: usize) {
542        self.pos = pos;
543    }
544
545    /// Extract a namespace string from an expression.
546    /// Returns Some("name") for Variable("name"), or Some("a.b") for nested property accesses
547    /// on variables that look like namespace paths.
548    fn extract_namespace(expr: &Expr) -> Option<String> {
549        match expr {
550            Expr::Variable(name) => Some(name.with_str(str::to_owned)),
551            Expr::Property(prop) => {
552                Self::extract_namespace(&prop.expr).map(|ns| format!("{}.{}", ns, prop.property))
553            }
554            _ => None,
555        }
556    }
557
558    fn expect(&mut self, ty: TokenType) -> ParseResult<Token<'a>> {
559        let tok = self.next_token();
560        if tok.ty != ty {
561            return Err(self.expected_token_error(ty, &tok));
562        }
563        Ok(tok)
564    }
565
566    /// The `expected <ty>, got <tok>` error at `tok`, shared by every
567    /// single-token expectation.
568    fn expected_token_error(&self, ty: TokenType, tok: &Token) -> ParseError {
569        self.error_at_token(
570            tok,
571            format!("expected {:?}, got {:?} ({:?})", ty, tok.literal, tok.ty),
572        )
573    }
574
575    /// Like [`Parser::expect`] but tags the raised error with a specific
576    /// openCypher-TCK error *detail* name. Used at grammar positions
577    /// where a mismatch has a more precise classification than the generic
578    /// `UnexpectedSyntax` — e.g. the closing `]` of a relationship pattern
579    /// (`InvalidRelationshipPattern`).
580    fn expect_detail(&mut self, ty: TokenType, detail: &'static str) -> ParseResult<Token<'a>> {
581        let tok = self.next_token();
582        if tok.ty != ty {
583            return Err(self.expected_token_error(ty, &tok).with_detail(detail));
584        }
585        Ok(tok)
586    }
587
588    fn error(&self, msg: impl Into<String>) -> ParseError {
589        let tok = self.peek();
590        self.error_at_token(tok, msg)
591    }
592
593    fn error_at_token(&self, tok: &Token, msg: impl Into<String>) -> ParseError {
594        let err = ParseError::new(msg, tok.line, tok.col).with_source(self.source);
595        // A lexer error token (malformed number/unicode literal) carries the
596        // specific openCypher-TCK error *detail* it should surface — propagate
597        // it so the raised parse error reports e.g. `InvalidNumberLiteral`
598        // instead of the generic `UnexpectedSyntax`. Non-error
599        // tokens carry no detail, so this is a no-op for the common case.
600        match tok.detail {
601            Some(detail) => err.with_detail(detail),
602            None => err,
603        }
604    }
605
606    /// A violated parser-internal invariant (e.g. the `parse_postfix`
607    /// namespace-call state machine reaching a state the memoized scan's
608    /// verdict rules out). The query engine's contract is typed errors,
609    /// never panics, so even a "cannot happen" state surfaces as a typed
610    /// parse error whose message marks it as an internal bug rather than a
611    /// user-syntax problem.
612    fn internal_error(&self, msg: impl Into<String>) -> ParseError {
613        self.error(format!("internal parser error: {}", msg.into()))
614    }
615
616    // ---- Top level ----
617
618    depth_guard_family! {
619        field = expr_depth,
620        enter = enter_expr_depth,
621        exit = exit_expr_depth,
622        with = with_expr_depth,
623        enter_doc = "ADR-0257: enter one level of expression nesting. \
624            Returns a typed error naming the limit once [`MAX_NESTING_DEPTH`] \
625            levels are already active, instead of recursing until the process \
626            aborts (LABS-69). On error the counter is left unchanged, so a \
627            speculative re-parse at a shallower position is not poisoned.",
628        exit_doc = "Pairs with [`Parser::enter_expr_depth`]; must run on \
629            every exit path (including error propagation) so \
630            backtracking/speculative parses keep the counter balanced.",
631        with_doc = "Runs `f` one expression-nesting level deep: the only \
632            sanctioned way to guard a recursive expression-shaped parse with \
633            `expr_depth`. The enter/exit pair is balanced by construction -- \
634            `f`'s result (including error propagation) is captured, the \
635            counter is decremented, and only then is the result returned, so \
636            no `?` can ever sit between enter and exit.",
637    }
638
639    depth_guard_family! {
640        field = clause_depth,
641        enter = enter_clause_depth,
642        exit = exit_clause_depth,
643        with = with_clause_depth,
644        enter_doc = "ADR-0257: enter one level of clause nesting. Returns a \
645            typed error naming the limit once [`MAX_NESTING_DEPTH`] levels \
646            are already active, instead of recursing until the process aborts \
647            (LABS-69: nested FOREACH bodies recurse through `parse_clause` \
648            without passing through `parse_statement`). On error the counter \
649            is left unchanged, so a speculative re-parse at a shallower \
650            position is not poisoned.",
651        exit_doc = "Pairs with [`Parser::enter_clause_depth`]; must run on \
652            every exit path (including error propagation) so sequential \
653            clauses in one statement/FOREACH body do not accumulate.",
654        with_doc = "[`Parser::with_expr_depth`] for `clause_depth`.",
655    }
656
657    depth_guard_family! {
658        field = statement_depth,
659        enter = enter_statement_depth,
660        exit = exit_statement_depth,
661        with = with_statement_depth,
662        enter_doc = "ADR-0257: enter one level of statement nesting. Returns \
663            a typed error naming the limit once [`MAX_NESTING_DEPTH`] levels \
664            are already active, instead of recursing until the process aborts \
665            (LABS-69). On error the counter is left unchanged, so a \
666            speculative re-parse at a shallower position is not poisoned.",
667        exit_doc = "Pairs with [`Parser::enter_statement_depth`]; must run on \
668            every exit path (including error propagation) so \
669            backtracking/speculative parses keep the counter balanced.",
670        with_doc = "[`Parser::with_expr_depth`] for `statement_depth`.",
671    }
672
673    depth_guard_family! {
674        field = block_depth,
675        enter = enter_block_depth,
676        exit = exit_block_depth,
677        with = with_block_depth,
678        enter_doc = "ADR-0257: enter one level of statement-block nesting. \
679            Returns a typed error naming the limit once \
680            [`MAX_NESTING_DEPTH`] levels are already active, instead of \
681            recursing until the process aborts (LABS-69: braced single \
682            queries and WHEN/ELSE bodies recurse through \
683            `parse_statement_block` without passing through \
684            `parse_statement`, `parse_clause`, or `parse_expression`). On \
685            error the counter is left unchanged, so a speculative re-parse \
686            at a shallower position is not poisoned.",
687        exit_doc = "Pairs with [`Parser::enter_block_depth`]; must run on \
688            every exit path (including error propagation) so sequential NEXT \
689            stages in one block and backtracking/speculative parses keep the \
690            counter balanced.",
691        with_doc = "[`Parser::with_expr_depth`] for `block_depth`.",
692    }
693
694    depth_guard_family! {
695        field = pattern_element_depth,
696        enter = enter_pattern_element_depth,
697        exit = exit_pattern_element_depth,
698        with = with_pattern_element_depth,
699        enter_doc = "Enter one level of pattern-element label/type chain \
700            nesting (a node pattern's labels, a relationship pattern's \
701            types). Scoped by the element parsers around their \
702            `parse_label_spec` calls so the comprehension pipe-ambiguity \
703            rule's `{` dead end stays suppressed for exactly that chain \
704            (see `chain_tail_ends_where`).",
705        exit_doc = "Pairs with [`Parser::enter_pattern_element_depth`]; \
706            balanced by construction through \
707            [`Parser::with_pattern_element_depth`].",
708        with_doc = "Runs `f` one pattern-element chain level deep: the \
709            element parsers' one way to scope a `parse_label_spec` call, \
710            so the depth is balanced by construction and no `?` can sit \
711            between enter and exit.",
712    }
713
714    /// Parses an `Integer` token as a `u32` bound (relationship hop count,
715    /// path quantifier bound, number of paths/groups) via the checked
716    /// [`parse_int_literal`] path. Literals that don't fit are a typed parse
717    /// error naming the bound -- never a silent clamp (LABS-81:
718    /// `[*99999999999..2]` used to parse as `min_hops = 1`).
719    fn parse_u32_bound(&self, tok: &Token, what: &str) -> ParseResult<u32> {
720        // Both failures render through the one integer-literal error path,
721        // naming the bound.
722        let site = IntLiteralSite::Bounded {
723            what,
724            max: u64::from(u32::MAX),
725        };
726        let value = parse_int_literal(&tok.literal)
727            .map_err(|error| self.int_literal_error(tok, error, site))?;
728        u32::try_from(value)
729            .map_err(|_| self.int_literal_error(tok, IntLiteralError::Overflow, site))
730    }
731}
732
733mod case;
734mod clauses;
735mod definitions;
736mod expressions;
737mod interp;
738mod is_predicate;
739mod labels;
740mod literals;
741mod names;
742mod patterns;
743
744pub use patterns::selector_is_selective;
745mod schema;
746mod search;
747mod show;
748mod statement;
749mod types;
750
751#[cfg(test)]
752mod tests;
753
754/// True if any element of a quantified path pattern's operand is itself
755/// quantified -- directly (`PatternElement::Quantified`) or via a
756/// variable-length/quantified relationship (`RelPattern` with hop bounds,
757/// whether legacy `*min..max` or the CIP-28 postfix form) -- which CIP-28
758/// forbids (no nested quantification).
759fn contains_quantification(elements: &[PatternElement]) -> bool {
760    elements.iter().any(|e| match e {
761        PatternElement::Quantified(_) => true,
762        PatternElement::Relationship(rp) => rp.is_variable_length(),
763        PatternElement::Node(_) => false,
764    })
765}
766
767/// True if `elements` contains a *GPM-syntax* quantification -- a
768/// quantified path pattern (`((...))+`) or a CIP-28 Form-5 postfix-quantified
769/// relationship (`-->+`, `-[]->{1,5}`) -- but *not* the legacy bracket
770/// variable-length form (`-[*1..5]->`), which remains legal inside
771/// `shortestPath(...)`/`allShortestPaths(...)` (CIP-40 path-selector-mixing
772/// scenario 7). Used to reject `QuantifiedPathPatternInShortestPath`
773/// (scenario 6).
774fn contains_gpm_quantification(elements: &[PatternElement]) -> bool {
775    elements.iter().any(|e| match e {
776        PatternElement::Quantified(_) => true,
777        PatternElement::Relationship(rp) => rp.quantified,
778        PatternElement::Node(_) => false,
779    })
780}
781
782fn comparison_op(ty: TokenType) -> Option<&'static str> {
783    match ty {
784        TokenType::Equals => Some(EQUALS),
785        TokenType::NotEquals => Some("<>"),
786        TokenType::LessThan => Some("<"),
787        TokenType::GreaterThan => Some(">"),
788        TokenType::LessEqual => Some("<="),
789        TokenType::GreaterEqual => Some(">="),
790        TokenType::RegexMatch => Some("=~"),
791        _ => None,
792    }
793}
794
795/// The AST's one spelling table for operator text (ADR-0505 §2): the `op`
796/// fields of `BinaryExpr`, `UnaryExpr` and `StringMatchExpr` are
797/// `&'static str` drawn from these constants, so every producer consults
798/// the table and no spelling is re-spelled at a build site. The comparison
799/// family's spellings live in the `comparison_op` token-to-spelling table
800/// above — its own one table, consumed by every comparison build site —
801/// with one exception: the equality spelling is a named constant below,
802/// because simple-CASE's plain-value default (`parse_when_operand_element`)
803/// builds the same comparison without a token to read the table from.
804const EQUALS: &str = "=";
805const OR: &str = "OR";
806const XOR: &str = "XOR";
807const AND: &str = "AND";
808const NOT: &str = "NOT";
809/// `+`, shared by the unary and binary producers.
810const PLUS: &str = "+";
811/// `-`, shared by the unary and binary producers.
812const MINUS: &str = "-";
813const CONCAT: &str = "||";
814const MUL: &str = "*";
815const DIV: &str = "/";
816const MOD: &str = "%";
817const POW: &str = "^";
818const STARTS_WITH: &str = "STARTS WITH";
819const ENDS_WITH: &str = "ENDS WITH";
820const CONTAINS: &str = "CONTAINS";
821
822// Test-only probe for the CIP-272 map-comprehension lookahead: counts the
823// speculative full parses entered for a `{` in expression position. A brace
824// with no top-level `|` must never reach that parse (the exponential
825// parse-time regression), so the regression test asserts on this count rather
826// than on wall-clock time. Thread-local: the test harness runs every test on
827// its own thread.
828#[cfg(test)]
829std::thread_local! {
830    static SPECULATIVE_COMPREHENSION_PARSES: std::cell::Cell<usize> =
831        const { std::cell::Cell::new(0) };
832}