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::{ComprehensionWhereContext, PipeScan};
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    /// Memo for [`Parser::path_ident_never_bound`]: the token scan runs at
238    /// most once per parse.
239    path_ident_never_bound_memo: std::cell::OnceCell<bool>,
240    /// Current statement-block nesting depth (ADR-0257): incremented on
241    /// entering `parse_statement_block`, decremented on exit. Every
242    /// statement-nesting cycle funnels through `parse_statement_block` --
243    /// CALL/EXISTS/COUNT/COLLECT subquery bodies, brace-enclosed nested
244    /// procedure specifications (`{ { ... } }`), and WHEN/ELSE bodies
245    /// (`WHEN ... THEN { WHEN ... }`) -- including the cycles that bypass
246    /// `parse_statement`, `parse_clause`, and `parse_expression` and so
247    /// never engage any other counter (LABS-69: ~3000 nested braces used
248    /// to SIGABRT on an 8 MiB release stack). Unlike `statement_depth`,
249    /// this counter is *not* consulted for label-mixing scoping, so a
250    /// top-level `{ ... }` body incrementing it cannot flip
251    /// `is_outer_clause`. Capped at [`MAX_NESTING_DEPTH`].
252    block_depth: u32,
253    /// Current expression nesting depth (ADR-0257): incremented on entering
254    /// `parse_expression` and on each recursive `parse_not` step, decremented
255    /// on exit. Every nested expression -- parenthesized constructs, list
256    /// literals, map literals, function-call arguments, CASE operands,
257    /// comprehension bodies, subquery WHERE/RETURN expressions -- descends
258    /// through `parse_expression`, so this one counter bounds all expression
259    /// recursion. Also counts recursion cycles that bypass
260    /// `parse_expression` but are expression-shaped: unary `-`/`!` chains,
261    /// nested label/subpath parens, and nested `LIST<...>`/`ANY<...>`
262    /// value-type brackets (see `parse_value_type`). Capped at
263    /// [`MAX_NESTING_DEPTH`] (LABS-69).
264    expr_depth: u32,
265    /// Current clause nesting depth (ADR-0257): incremented on entering
266    /// `parse_clause`, decremented on exit. Both callers of `parse_clause`
267    /// (`parse_statement`'s body loop and `parse_foreach`'s body loop) are
268    /// loops, so the counter returns to baseline after every clause and
269    /// only grows with *true* clause nesting. That nesting exists: nested
270    /// FOREACH bodies recurse `parse_clause` -> `parse_clause_inner` ->
271    /// `parse_foreach` -> `parse_clause`, bypassing `parse_statement`, so
272    /// the `statement_depth` cap never engages on that cycle (LABS-69).
273    /// Capped at [`MAX_NESTING_DEPTH`].
274    clause_depth: u32,
275    /// The comprehension-WHERE context currently active, if any: which
276    /// comprehension's `WHERE`-part expression (or `IN` source
277    /// expression) is being parsed — carrying the construct's closer
278    /// token and opener index that the pipe classification's one-pass
279    /// scan reads (see [`ComprehensionWhereContext`]) — one state with
280    /// one lifecycle owner, [`Parser::with_comprehension_where`].
281    /// While a context is active a bare `|` is genuinely ambiguous: it
282    /// could continue a label-expression disjunction (`x:A|B`), continue
283    /// a `<value type>` union (`IS :: STRING | INTEGER`) or be the
284    /// comprehension's own map-expression separator (`WHERE x:A |
285    /// expr]`). `parse_label_or` and the type-union loop
286    /// (`parse_value_type_at_current_depth`) resolve that through the one
287    /// shared mechanism, [`Parser::ambiguous_pipe_continuation`], which
288    /// consults this state before committing to the disjunction/union
289    /// reading.
290    comprehension_where: Option<ComprehensionWhereContext>,
291    /// The one-pass pipe scan of the active comprehension-WHERE context
292    /// (see [`comprehension_where::PipeScan`]): computed at context entry,
293    /// restored with the context — the per-pipe classification is a
294    /// lookup into it.
295    comprehension_pipe_scan: Option<PipeScan>,
296    /// Depth of `EXISTS { … }` bodies currently being parsed. An unbounded
297    /// quantified path pattern under REPEATABLE ELEMENTS is safe inside an
298    /// existence probe (the probe stops at the first row) and is accepted
299    /// there, while a top-level match still rejects it (42N53).
300    exists_subquery_depth: u32,
301    /// The speculative-probe state — probe depth, the per-(position,
302    /// gate) verdict memo, and the node-pattern tree cache — one owner
303    /// with the policies documented on it (`parser/speculation.rs`).
304    speculation: Speculation,
305    /// Nesting depth of pattern-element label/type chain parses (a node
306    /// pattern's labels, a relationship pattern's types), guarded by the
307    /// `depth_guard_family!` registration below. Inside an element's own
308    /// chain a `{` is the element's inline property map, not a map
309    /// projection, so the comprehension pipe-ambiguity rule's `{` dead
310    /// end must not fire there — `chain_tail_ends_where` gates its
311    /// `{` and `]` arms through this; the element parsers scope their
312    /// `parse_label_spec` calls
313    /// through [`Parser::with_pattern_element_depth`].
314    pattern_element_depth: u32,
315    /// The parse-affecting preview opt-ins for this parse (see
316    /// [`crate::lexer::ParseOptions`]). Set once by `Parser::new` from the
317    /// entry point's options; never mutated mid-parse, so nested and
318    /// speculative parses all observe one dialect.
319    options: crate::lexer::ParseOptions,
320    /// Which label-mixing accumulator the clause being parsed feeds (see
321    /// [`LabelMixTarget`]). Saved and restored around each clause so a
322    /// nested subquery body's clauses choose their own side.
323    label_mix_target: LabelMixTarget,
324}
325
326/// A single postfix accessor (`.prop` or CIP-131's `[<expr>]`) parsed after
327/// a SET/REMOVE target's base expression by `Parser::parse_property_target_accessors`.
328enum PropertyTargetAccessor {
329    Static(SmallName),
330    Dynamic(Expr),
331}
332
333/// Generates the `enter_*_depth` / `exit_*_depth` / `with_*_depth` triple
334/// for one depth-guard counter field (ADR-0257, LABS-69). The four
335/// families (`expr_depth`, `clause_depth`, `statement_depth`,
336/// `block_depth`) share one mechanically identical shape; generating them
337/// from a single definition keeps the balanced-enter/exit property true by
338/// construction: `enter` leaves the counter unchanged on error, `exit` is
339/// a saturating decrement, and `with` captures `f`'s result (including
340/// error propagation), decrements, and only then returns, so no `?` can
341/// ever sit between enter and exit. The limit check and error message are
342/// byte-identical across families.
343macro_rules! depth_guard_family {
344    (
345        field = $field:ident,
346        enter = $enter:ident,
347        exit = $exit:ident,
348        with = $with:ident,
349        enter_doc = $enter_doc:expr,
350        exit_doc = $exit_doc:expr,
351        with_doc = $with_doc:expr $(,)?
352    ) => {
353        #[doc = $enter_doc]
354        fn $enter(&mut self) -> ParseResult<()> {
355            if self.$field >= MAX_NESTING_DEPTH {
356                return Err(self.error(format!(
357                    "maximum nesting depth of {MAX_NESTING_DEPTH} exceeded"
358                )));
359            }
360            self.$field += 1;
361            Ok(())
362        }
363
364        #[doc = $exit_doc]
365        fn $exit(&mut self) {
366            self.$field = self.$field.saturating_sub(1);
367        }
368
369        #[doc = $with_doc]
370        fn $with<T>(&mut self, f: impl FnOnce(&mut Self) -> ParseResult<T>) -> ParseResult<T> {
371            self.$enter()?;
372            let result = f(self);
373            self.$exit();
374            result
375        }
376    };
377}
378
379/// The running base of [`Parser::parse_postfix`]'s postfix chain, making
380/// the namespace-call accumulation invariant structural instead of
381/// comment-held.
382///
383/// While a dot-chain the memoized `scan_dot_chain_for_call` classified as
384/// ending in `(` is being accumulated, the base is [`PostfixBase::NsPath`]
385/// — a bare namespace-path string with *no* `Expr` — so no postfix arm can
386/// observe or rebuild a stale intermediate expression (materializing one
387/// per segment cost Θ(n²) in string clones, a parse-time DoS on maximal
388/// inputs). Everywhere else the base is [`PostfixBase::Built`].
389enum PostfixBase {
390    /// A materialized expression, plus its namespace path while it is a
391    /// plain dotted path (a `Variable`, or a property chain over one) —
392    /// maintained incrementally so a long `a.b.c...` chain costs amortized
393    /// O(1) per segment instead of re-walking and re-`format!`ing the
394    /// whole chain per dot. `None` once any non-path postfix form
395    /// (subscript, map projection, function call) has been applied.
396    Built(Expr, Option<String>),
397    /// A call-bound dot-chain accumulated as a bare path string. Entered
398    /// only under the scan's ends-in-`(` verdict, so mid-chain the token
399    /// after each `.ident` is always `.` or `(`, and the chain's
400    /// terminating `(` arm — which builds the `FunctionCall` name from
401    /// this path — is the only way out.
402    NsPath(String),
403}
404
405impl<'a> Parser<'a> {
406    /// Builds a parser over `source` under one explicit dialect: the
407    /// constructor tokenizes the source itself via
408    /// [`tokenize_with_options`], so the token stream and the
409    /// [`crate::lexer::ParseOptions`] that lexed it are one fact, never two
410    /// independently supplied arguments that could disagree. Every entry
411    /// point (`parse_with_options`, `parse_expression_str_with_options`,
412    /// `parse_graph_type_body`) passes its options here -- the ungated floor
413    /// entry points pass [`crate::lexer::ParseOptions::default`] explicitly,
414    /// and `parse_with_options` forwards the caller's preview gates -- so a
415    /// `Parser` can never exist half-configured.
416    ///
417    /// The constructor is the parser's only tokenizing site, so the
418    /// ADR-0257 admission cap ([`MAX_QUERY_BYTES`]) is structural here, not
419    /// a convention each entry point must remember to enforce: the first
420    /// statement checks `source.len()` *before* lexing, so adversarial
421    /// input cannot amplify into unbounded token allocations (LABS-81: 8
422    /// MiB of commas used to become over 520 MB of tokens). `subject` only
423    /// labels the input kind in the over-cap error message.
424    fn new(
425        source: &'a str,
426        subject: &str,
427        options: crate::lexer::ParseOptions,
428    ) -> Result<Self, ParseError> {
429        if source.len() > MAX_QUERY_BYTES {
430            return Err(ParseError::new(
431                format!(
432                    "{subject} of {} bytes exceeds the maximum query size of {MAX_QUERY_BYTES} bytes",
433                    source.len()
434                ),
435                1,
436                1,
437            ));
438        }
439        let tokens = tokenize_with_options(source, options);
440        Ok(Parser {
441            source,
442            line_starts: crate::token::line_starts_of(source),
443            tokens,
444            pos: 0,
445            side_effects: PatternSideEffectFlags::default(),
446            label_mix_target: LabelMixTarget::None,
447            in_when_branch_body: 0,
448            statement_depth: 0,
449            path_ident_never_bound_memo: std::cell::OnceCell::new(),
450            block_depth: 0,
451            expr_depth: 0,
452            clause_depth: 0,
453            comprehension_where: None,
454            comprehension_pipe_scan: None,
455            exists_subquery_depth: 0,
456            speculation: Speculation::default(),
457            pattern_element_depth: 0,
458            options,
459        })
460    }
461
462    // ---- Token access ----
463
464    /// The synthetic past-the-end EOF sentinel — the one spelling of the
465    /// token every out-of-range probe returns. `Token<'static>` covariantly
466    /// subtypes to any `Token<'a>`, so one shared empty-literal instance
467    /// serves every parse.
468    fn eof_token() -> &'static Token<'static> {
469        static EOF: std::sync::OnceLock<Token<'static>> = std::sync::OnceLock::new();
470        EOF.get_or_init(|| Token::new(TokenType::EOF, "", 0, 0))
471    }
472
473    fn peek(&self) -> &Token<'a> {
474        self.peek_at(0)
475    }
476
477    fn peek_type(&self) -> TokenType {
478        self.peek().ty
479    }
480
481    /// Looks ahead `offset` tokens past the current position (0 == `peek`)
482    /// without consuming anything.
483    fn peek_at(&self, offset: usize) -> &Token<'a> {
484        let idx = self.pos + offset;
485        if idx >= self.tokens.len() {
486            Self::eof_token()
487        } else {
488            &self.tokens[idx]
489        }
490    }
491
492    /// True if the current token is a case-insensitive identifier matching
493    /// `word` — the generic probe for the many contextual keywords that are
494    /// not reserved words in the lexer: type grammar words (`VALUE`,
495    /// `PROPERTY`, `MAP`) and schema/administration words (`DEFAULT`,
496    /// `KEY`, ...).
497    pub(super) fn peek_is_ident(&self, word: &str) -> bool {
498        self.peek_at_is_ident(0, word)
499    }
500
501    /// Like `peek_is_ident`, but `offset` tokens ahead (0 == `peek_is_ident`).
502    pub(super) fn peek_at_is_ident(&self, offset: usize, word: &str) -> bool {
503        Self::token_is_ident(self.peek_at(offset), word)
504    }
505
506    /// `<keyword> <non-reserved word>` lookahead: `lead` is the keyword
507    /// token (`AS`, `WITH`), the second token an ident-like non-reserved
508    /// word spelled `word` (`ANALYZER`, `CONSTANT`, `CONSOLIDATED` -- the
509    /// set grows with the grammar, so the shape lives once).
510    pub(super) fn peek_keyword_word(&self, lead: TokenType, word: &str) -> bool {
511        self.peek_type() == lead
512            && self.peek_at(1).ty.is_ident_like()
513            && self.peek_at(1).literal.eq_ignore_ascii_case(word)
514    }
515
516    /// True if `tok` is a case-insensitive identifier matching `word` — the
517    /// token-level core of [`Self::peek_at_is_ident`], for call sites that
518    /// already hold the token.
519    pub(super) fn token_is_ident(tok: &Token, word: &str) -> bool {
520        tok.ty == TokenType::Identifier && tok.literal.eq_ignore_ascii_case(word)
521    }
522
523    /// Whether the token at absolute index `i` is the identifier `PATH`
524    /// directly followed by `[` -- the one spelling of the constructor's
525    /// opener, shared by the parse-time peek and the whole-statement scan.
526    pub(super) fn is_path_opener_at(&self, i: usize) -> bool {
527        self.tokens
528            .get(i)
529            .is_some_and(|tok| Self::token_is_ident(tok, "PATH"))
530            && self
531                .tokens
532                .get(i + 1)
533                .is_some_and(|next| next.ty == TokenType::LeftBracket)
534    }
535
536    /// Whether every identifier spelled `path` (any case) in the whole
537    /// statement is directly followed by `[`. A variable is introduced and
538    /// used by tokens that are never followed by `[` (`path = ...`, `AS
539    /// path`, `RETURN path`), so when this holds `path` is bound nowhere and
540    /// a `PATH [x]` cannot be a subscript of it: the one-element path
541    /// constructor (ADR-0637). Conservative by construction -- any other use
542    /// of the name keeps the subscript reading.
543    pub(super) fn path_ident_never_bound(&self) -> bool {
544        *self.path_ident_never_bound_memo.get_or_init(|| {
545            self.tokens
546                .iter()
547                .enumerate()
548                .all(|(i, tok)| !Self::token_is_ident(tok, "PATH") || self.is_path_opener_at(i))
549        })
550    }
551
552    /// True when the cursor is on the `ALL` set-quantifier spelling
553    /// (`count(ALL x)`, `collect(ALL x)`, `RETURN ALL`, `GROUP BY ALL`),
554    /// false for the `all(x IN list WHERE predicate)` list-predicate
555    /// function: `ALL` immediately followed by `(` is always the function,
556    /// the same priority the RETURN/WITH/GROUP-BY modifier readers apply.
557    /// The one spelling of that rule, shared by every set-quantifier site so
558    /// a nested `all(...)` inside an argument list cannot be swallowed as
559    /// the aggregate's quantifier.
560    pub(super) fn all_is_set_quantifier(&self) -> bool {
561        self.peek_type() == TokenType::ALL && self.peek_at(1).ty != TokenType::LeftParen
562    }
563
564    /// Consume and return the current token. The value is cloned out of the
565    /// stream because `backup`/`restore_pos` re-read tokens from
566    /// `self.tokens` after they have been consumed; with ADR-0505's borrowed
567    /// literals that clone is a pointer copy, not a heap allocation (only
568    /// the rare owned literal — an escaped string, a formatted error — pays
569    /// a String clone here).
570    fn next_token(&mut self) -> Token<'a> {
571        if self.pos >= self.tokens.len() {
572            Self::eof_token().clone()
573        } else {
574            let tok = self.tokens[self.pos].clone();
575            self.pos += 1;
576            tok
577        }
578    }
579
580    fn backup(&mut self) {
581        if self.pos > 0 {
582            self.pos -= 1;
583        }
584    }
585
586    fn save_pos(&self) -> usize {
587        self.pos
588    }
589
590    fn restore_pos(&mut self, pos: usize) {
591        self.pos = pos;
592    }
593
594    /// Extract a namespace string from an expression.
595    /// Returns Some("name") for Variable("name"), or Some("a.b") for nested property accesses
596    /// on variables that look like namespace paths.
597    fn extract_namespace(expr: &Expr) -> Option<String> {
598        match expr {
599            Expr::Variable(name) => Some(name.with_str(str::to_owned)),
600            Expr::Property(prop) => {
601                Self::extract_namespace(&prop.expr).map(|ns| format!("{}.{}", ns, prop.property))
602            }
603            _ => None,
604        }
605    }
606
607    fn expect(&mut self, ty: TokenType) -> ParseResult<Token<'a>> {
608        let tok = self.next_token();
609        if tok.ty != ty {
610            return Err(self.expected_token_error(ty, &tok));
611        }
612        Ok(tok)
613    }
614
615    /// The `expected <ty>, got <tok>` error at `tok`, shared by every
616    /// single-token expectation.
617    fn expected_token_error(&self, ty: TokenType, tok: &Token) -> ParseError {
618        self.error_at_token(
619            tok,
620            format!("expected {:?}, got {:?} ({:?})", ty, tok.literal, tok.ty),
621        )
622    }
623
624    /// Like [`Parser::expect`] but tags the raised error with a specific
625    /// openCypher-TCK error *detail* name. Used at grammar positions
626    /// where a mismatch has a more precise classification than the generic
627    /// `UnexpectedSyntax` — e.g. the closing `]` of a relationship pattern
628    /// (`InvalidRelationshipPattern`).
629    fn expect_detail(&mut self, ty: TokenType, detail: &'static str) -> ParseResult<Token<'a>> {
630        let tok = self.next_token();
631        if tok.ty != ty {
632            return Err(self.expected_token_error(ty, &tok).with_detail(detail));
633        }
634        Ok(tok)
635    }
636
637    fn error(&self, msg: impl Into<String>) -> ParseError {
638        let tok = self.peek();
639        self.error_at_token(tok, msg)
640    }
641
642    fn error_at_token(&self, tok: &Token, msg: impl Into<String>) -> ParseError {
643        let err = ParseError::new(msg, tok.line, tok.col).with_source(self.source);
644        // A lexer error token (malformed number/unicode literal) carries the
645        // specific openCypher-TCK error *detail* it should surface — propagate
646        // it so the raised parse error reports e.g. `InvalidNumberLiteral`
647        // instead of the generic `UnexpectedSyntax`. Non-error
648        // tokens carry no detail, so this is a no-op for the common case.
649        match tok.detail {
650            Some(detail) => err.with_detail(detail),
651            None => err,
652        }
653    }
654
655    /// A violated parser-internal invariant (e.g. the `parse_postfix`
656    /// namespace-call state machine reaching a state the memoized scan's
657    /// verdict rules out). The query engine's contract is typed errors,
658    /// never panics, so even a "cannot happen" state surfaces as a typed
659    /// parse error whose message marks it as an internal bug rather than a
660    /// user-syntax problem.
661    fn internal_error(&self, msg: impl Into<String>) -> ParseError {
662        self.error(format!("internal parser error: {}", msg.into()))
663    }
664
665    // ---- Top level ----
666
667    depth_guard_family! {
668        field = expr_depth,
669        enter = enter_expr_depth,
670        exit = exit_expr_depth,
671        with = with_expr_depth,
672        enter_doc = "ADR-0257: enter one level of expression nesting. \
673            Returns a typed error naming the limit once [`MAX_NESTING_DEPTH`] \
674            levels are already active, instead of recursing until the process \
675            aborts (LABS-69). On error the counter is left unchanged, so a \
676            speculative re-parse at a shallower position is not poisoned.",
677        exit_doc = "Pairs with [`Parser::enter_expr_depth`]; must run on \
678            every exit path (including error propagation) so \
679            backtracking/speculative parses keep the counter balanced.",
680        with_doc = "Runs `f` one expression-nesting level deep: the only \
681            sanctioned way to guard a recursive expression-shaped parse with \
682            `expr_depth`. The enter/exit pair is balanced by construction -- \
683            `f`'s result (including error propagation) is captured, the \
684            counter is decremented, and only then is the result returned, so \
685            no `?` can ever sit between enter and exit.",
686    }
687
688    depth_guard_family! {
689        field = clause_depth,
690        enter = enter_clause_depth,
691        exit = exit_clause_depth,
692        with = with_clause_depth,
693        enter_doc = "ADR-0257: enter one level of clause nesting. Returns a \
694            typed error naming the limit once [`MAX_NESTING_DEPTH`] levels \
695            are already active, instead of recursing until the process aborts \
696            (LABS-69: nested FOREACH bodies recurse through `parse_clause` \
697            without passing through `parse_statement`). On error the counter \
698            is left unchanged, so a speculative re-parse at a shallower \
699            position is not poisoned.",
700        exit_doc = "Pairs with [`Parser::enter_clause_depth`]; must run on \
701            every exit path (including error propagation) so sequential \
702            clauses in one statement/FOREACH body do not accumulate.",
703        with_doc = "[`Parser::with_expr_depth`] for `clause_depth`.",
704    }
705
706    depth_guard_family! {
707        field = statement_depth,
708        enter = enter_statement_depth,
709        exit = exit_statement_depth,
710        with = with_statement_depth,
711        enter_doc = "ADR-0257: enter one level of statement nesting. Returns \
712            a typed error naming the limit once [`MAX_NESTING_DEPTH`] levels \
713            are already active, instead of recursing until the process aborts \
714            (LABS-69). On error the counter is left unchanged, so a \
715            speculative re-parse at a shallower position is not poisoned.",
716        exit_doc = "Pairs with [`Parser::enter_statement_depth`]; must run on \
717            every exit path (including error propagation) so \
718            backtracking/speculative parses keep the counter balanced.",
719        with_doc = "[`Parser::with_expr_depth`] for `statement_depth`.",
720    }
721
722    depth_guard_family! {
723        field = block_depth,
724        enter = enter_block_depth,
725        exit = exit_block_depth,
726        with = with_block_depth,
727        enter_doc = "ADR-0257: enter one level of statement-block nesting. \
728            Returns a typed error naming the limit once \
729            [`MAX_NESTING_DEPTH`] levels are already active, instead of \
730            recursing until the process aborts (LABS-69: braced single \
731            queries and WHEN/ELSE bodies recurse through \
732            `parse_statement_block` without passing through \
733            `parse_statement`, `parse_clause`, or `parse_expression`). On \
734            error the counter is left unchanged, so a speculative re-parse \
735            at a shallower position is not poisoned.",
736        exit_doc = "Pairs with [`Parser::enter_block_depth`]; must run on \
737            every exit path (including error propagation) so sequential NEXT \
738            stages in one block and backtracking/speculative parses keep the \
739            counter balanced.",
740        with_doc = "[`Parser::with_expr_depth`] for `block_depth`.",
741    }
742
743    depth_guard_family! {
744        field = pattern_element_depth,
745        enter = enter_pattern_element_depth,
746        exit = exit_pattern_element_depth,
747        with = with_pattern_element_depth,
748        enter_doc = "Enter one level of pattern-element label/type chain \
749            nesting (a node pattern's labels, a relationship pattern's \
750            types). Scoped by the element parsers around their \
751            `parse_label_spec` calls so the comprehension pipe-ambiguity \
752            rule's `{` dead end stays suppressed for exactly that chain \
753            (see `chain_tail_ends_where`).",
754        exit_doc = "Pairs with [`Parser::enter_pattern_element_depth`]; \
755            balanced by construction through \
756            [`Parser::with_pattern_element_depth`].",
757        with_doc = "Runs `f` one pattern-element chain level deep: the \
758            element parsers' one way to scope a `parse_label_spec` call, \
759            so the depth is balanced by construction and no `?` can sit \
760            between enter and exit.",
761    }
762
763    /// Parses an `Integer` token as a `u32` bound (relationship hop count,
764    /// path quantifier bound, number of paths/groups) via the checked
765    /// [`parse_int_literal`] path. Literals that don't fit are a typed parse
766    /// error naming the bound -- never a silent clamp (LABS-81:
767    /// `[*99999999999..2]` used to parse as `min_hops = 1`).
768    fn parse_u32_bound(&self, tok: &Token, what: &str) -> ParseResult<u32> {
769        // Both failures render through the one integer-literal error path,
770        // naming the bound.
771        let site = IntLiteralSite::Bounded {
772            what,
773            max: u64::from(u32::MAX),
774        };
775        let value = parse_int_literal(&tok.literal)
776            .map_err(|error| self.int_literal_error(tok, error, site))?;
777        u32::try_from(value)
778            .map_err(|_| self.int_literal_error(tok, IntLiteralError::Overflow, site))
779    }
780    /// Type of the token at absolute index `pos` (`EOF` past the end) --
781    /// the absolute-index counterpart of [`Self::peek_at`] for
782    /// token-level scans, in the idiom of `scan_dot_chain_for_call`.
783    fn token_type_at(&self, pos: usize) -> TokenType {
784        match self.tokens.get(pos) {
785            Some(t) => t.ty,
786            None => TokenType::EOF,
787        }
788    }
789
790    /// Lookahead from `self.pos` without consuming tokens: true when
791    /// `target` appears at depth 0 before the closer that ends the
792    /// construct opened just before `self.pos` (the caller has already
793    /// consumed the opener). Only the bracket kinds in [`BracketSet`]
794    /// count toward the depth, so a paren-only scan (inside a call's
795    /// argument list) and an all-bracket scan (inside a comprehension
796    /// brace, whose source expression can nest brackets and parens) are
797    /// explicit per-site choices. The one scan behind
798    /// [`Parser::trim_args_have_top_level_from`],
799    /// [`Parser::pipe_before_closing_paren`], and
800    /// [`Parser::has_pipe_before_matching_brace`].
801    fn top_level_token_before_matching_close(
802        &self,
803        target: TokenType,
804        brackets: BracketSet,
805    ) -> bool {
806        let mut depth = 0usize;
807        let mut pos = self.pos;
808        loop {
809            match self.token_type_at(pos) {
810                TokenType::EOF => return false,
811                ty if brackets.opens(ty) => depth += 1,
812                ty if brackets.closes(ty) => {
813                    if depth == 0 {
814                        return false; // the construct's own closer
815                    }
816                    depth -= 1;
817                }
818                ty if ty == target && depth == 0 => return true,
819                _ => {}
820            }
821            pos += 1;
822        }
823    }
824}
825
826/// The bracket kinds a
827/// [`Parser::top_level_token_before_matching_close`] scan counts toward
828/// its depth — the per-site choice of which groups are transparent,
829/// declared beside the scan it parameterizes.
830#[derive(Clone, Copy)]
831enum BracketSet {
832    /// Only `(` / `)` nest: the scan runs inside a call's argument list.
833    Parens,
834    /// `{`, `[`, and `(` all nest: the scan runs inside a comprehension
835    /// brace, whose source expression can contain brackets and parens.
836    AllBrackets,
837}
838
839impl BracketSet {
840    /// True when `ty` is an opening bracket of one of this set's kinds.
841    fn opens(self, ty: TokenType) -> bool {
842        match self {
843            BracketSet::Parens => ty == TokenType::LeftParen,
844            BracketSet::AllBrackets => matches!(
845                ty,
846                TokenType::LeftBrace | TokenType::LeftBracket | TokenType::LeftParen
847            ),
848        }
849    }
850
851    /// True when `ty` is a closing bracket of one of this set's kinds.
852    fn closes(self, ty: TokenType) -> bool {
853        match self {
854            BracketSet::Parens => ty == TokenType::RightParen,
855            BracketSet::AllBrackets => matches!(
856                ty,
857                TokenType::RightBrace | TokenType::RightBracket | TokenType::RightParen
858            ),
859        }
860    }
861}
862
863mod annotations;
864mod case;
865mod clauses;
866mod definitions;
867mod expressions;
868mod interp;
869mod is_predicate;
870mod labels;
871mod literals;
872mod names;
873mod patterns;
874
875pub use patterns::selector_is_selective;
876mod schema;
877mod search;
878mod show;
879mod statement;
880mod types;
881
882#[cfg(test)]
883mod tests;
884
885/// True if any element of a quantified path pattern's operand is itself
886/// quantified -- directly (`PatternElement::Quantified`) or via a
887/// variable-length/quantified relationship (`RelPattern` with hop bounds,
888/// whether legacy `*min..max` or the CIP-28 postfix form) -- which CIP-28
889/// forbids (no nested quantification).
890fn contains_quantification(elements: &[PatternElement]) -> bool {
891    elements.iter().any(|e| match e {
892        PatternElement::Quantified(_) => true,
893        PatternElement::Relationship(rp) => rp.is_variable_length(),
894        PatternElement::Node(_) => false,
895    })
896}
897
898/// True if `elements` contains a *GPM-syntax* quantification -- a
899/// quantified path pattern (`((...))+`) or a CIP-28 Form-5 postfix-quantified
900/// relationship (`-->+`, `-[]->{1,5}`) -- but *not* the legacy bracket
901/// variable-length form (`-[*1..5]->`), which remains legal inside
902/// `shortestPath(...)`/`allShortestPaths(...)` (CIP-40 path-selector-mixing
903/// scenario 7). Used to reject `QuantifiedPathPatternInShortestPath`
904/// (scenario 6).
905fn contains_gpm_quantification(elements: &[PatternElement]) -> bool {
906    elements.iter().any(|e| match e {
907        PatternElement::Quantified(_) => true,
908        PatternElement::Relationship(rp) => rp.quantified,
909        PatternElement::Node(_) => false,
910    })
911}
912
913fn comparison_op(ty: TokenType) -> Option<&'static str> {
914    match ty {
915        TokenType::Equals => Some(EQUALS),
916        TokenType::NotEquals => Some("<>"),
917        TokenType::LessThan => Some("<"),
918        TokenType::GreaterThan => Some(">"),
919        TokenType::LessEqual => Some("<="),
920        TokenType::GreaterEqual => Some(">="),
921        TokenType::RegexMatch => Some("=~"),
922        _ => None,
923    }
924}
925
926/// The AST's one spelling table for operator text (ADR-0505 §2): the `op`
927/// fields of `BinaryExpr`, `UnaryExpr` and `StringMatchExpr` are
928/// `&'static str` drawn from these constants, so every producer consults
929/// the table and no spelling is re-spelled at a build site. The comparison
930/// family's spellings live in the `comparison_op` token-to-spelling table
931/// above — its own one table, consumed by every comparison build site —
932/// with one exception: the equality spelling is a named constant below,
933/// because simple-CASE's plain-value default (`parse_when_operand_element`)
934/// builds the same comparison without a token to read the table from.
935const EQUALS: &str = "=";
936const OR: &str = "OR";
937const XOR: &str = "XOR";
938const AND: &str = "AND";
939const NOT: &str = "NOT";
940/// `+`, shared by the unary and binary producers.
941const PLUS: &str = "+";
942/// `-`, shared by the unary and binary producers.
943const MINUS: &str = "-";
944const CONCAT: &str = "||";
945const MUL: &str = "*";
946const DIV: &str = "/";
947const MOD: &str = "%";
948const POW: &str = "^";
949const STARTS_WITH: &str = "STARTS WITH";
950const ENDS_WITH: &str = "ENDS WITH";
951const CONTAINS: &str = "CONTAINS";
952
953// Test-only probe for the CIP-272 map-comprehension lookahead: counts the
954// speculative full parses entered for a `{` in expression position. A brace
955// with no top-level `|` must never reach that parse (the exponential
956// parse-time regression), so the regression test asserts on this count rather
957// than on wall-clock time. Thread-local: the test harness runs every test on
958// its own thread.
959#[cfg(test)]
960std::thread_local! {
961    static SPECULATIVE_COMPREHENSION_PARSES: std::cell::Cell<usize> =
962        const { std::cell::Cell::new(0) };
963}