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 /// The one consuming read of the comparison table
482 /// ([`TokenType::comparison_spelling`], set and spelling together in
483 /// the token layer): the spelling of a comparison operator at the
484 /// cursor, consuming its token, or `None` leaving the cursor alone —
485 /// every comparison build site with an operator token at the cursor
486 /// reads the table through this, never a hand-rolled
487 /// peek-then-consume pair. (The one site without a token to read —
488 /// simple-CASE's plain-value default, `parse_when_operand_element` —
489 /// builds from the table's own [`TokenType::EQUALS`] constant.)
490 fn take_comparison_spelling(&mut self) -> Option<&'static str> {
491 let spelling = self.peek_type().comparison_spelling()?;
492 self.next_token();
493 Some(spelling)
494 }
495
496 /// Looks ahead `offset` tokens past the current position (0 == `peek`)
497 /// without consuming anything.
498 fn peek_at(&self, offset: usize) -> &Token<'a> {
499 let idx = self.pos + offset;
500 if idx >= self.tokens.len() {
501 Self::eof_token()
502 } else {
503 &self.tokens[idx]
504 }
505 }
506
507 /// True if the current token is a case-insensitive identifier matching
508 /// `word` — the generic probe for the many contextual keywords that are
509 /// not reserved words in the lexer: type grammar words (`VALUE`,
510 /// `PROPERTY`, `MAP`) and schema/administration words (`DEFAULT`,
511 /// `KEY`, ...).
512 pub(super) fn peek_is_ident(&self, word: &str) -> bool {
513 self.peek_at_is_ident(0, word)
514 }
515
516 /// Like `peek_is_ident`, but `offset` tokens ahead (0 == `peek_is_ident`).
517 pub(super) fn peek_at_is_ident(&self, offset: usize, word: &str) -> bool {
518 Self::token_is_ident(self.peek_at(offset), word)
519 }
520
521 /// `<keyword> <non-reserved word>` lookahead: `lead` is the keyword
522 /// token (`AS`, `WITH`), the second token an ident-like non-reserved
523 /// word spelled `word` (`ANALYZER`, `CONSTANT`, `CONSOLIDATED` -- the
524 /// set grows with the grammar, so the shape lives once).
525 pub(super) fn peek_keyword_word(&self, lead: TokenType, word: &str) -> bool {
526 self.peek_type() == lead
527 && self.peek_at(1).ty.is_ident_like()
528 && self.peek_at(1).literal.eq_ignore_ascii_case(word)
529 }
530
531 /// True if `tok` is a case-insensitive identifier matching `word` — the
532 /// token-level core of [`Self::peek_at_is_ident`], for call sites that
533 /// already hold the token.
534 pub(super) fn token_is_ident(tok: &Token, word: &str) -> bool {
535 tok.ty == TokenType::Identifier && tok.literal.eq_ignore_ascii_case(word)
536 }
537
538 /// Whether the token at absolute index `i` is the identifier `PATH`
539 /// directly followed by `[` -- the one spelling of the constructor's
540 /// opener, shared by the parse-time peek and the whole-statement scan.
541 pub(super) fn is_path_opener_at(&self, i: usize) -> bool {
542 self.tokens
543 .get(i)
544 .is_some_and(|tok| Self::token_is_ident(tok, "PATH"))
545 && self
546 .tokens
547 .get(i + 1)
548 .is_some_and(|next| next.ty == TokenType::LeftBracket)
549 }
550
551 /// Whether every identifier spelled `path` (any case) in the whole
552 /// statement is directly followed by `[`. A variable is introduced and
553 /// used by tokens that are never followed by `[` (`path = ...`, `AS
554 /// path`, `RETURN path`), so when this holds `path` is bound nowhere and
555 /// a `PATH [x]` cannot be a subscript of it: the one-element path
556 /// constructor (ADR-0637). Conservative by construction -- any other use
557 /// of the name keeps the subscript reading.
558 pub(super) fn path_ident_never_bound(&self) -> bool {
559 *self.path_ident_never_bound_memo.get_or_init(|| {
560 self.tokens
561 .iter()
562 .enumerate()
563 .all(|(i, tok)| !Self::token_is_ident(tok, "PATH") || self.is_path_opener_at(i))
564 })
565 }
566
567 /// True when the cursor is on the `ALL` set-quantifier spelling
568 /// (`count(ALL x)`, `collect(ALL x)`, `RETURN ALL`, `GROUP BY ALL`),
569 /// false for the `all(x IN list WHERE predicate)` list-predicate
570 /// function: `ALL` immediately followed by `(` is always the function,
571 /// the same priority the RETURN/WITH/GROUP-BY modifier readers apply.
572 /// The one spelling of that rule, shared by every set-quantifier site so
573 /// a nested `all(...)` inside an argument list cannot be swallowed as
574 /// the aggregate's quantifier.
575 pub(super) fn all_is_set_quantifier(&self) -> bool {
576 self.peek_type() == TokenType::ALL && self.peek_at(1).ty != TokenType::LeftParen
577 }
578
579 /// Consume and return the current token. The value is cloned out of the
580 /// stream because `backup`/`restore_pos` re-read tokens from
581 /// `self.tokens` after they have been consumed; with ADR-0505's borrowed
582 /// literals that clone is a pointer copy, not a heap allocation (only
583 /// the rare owned literal — an escaped string, a formatted error — pays
584 /// a String clone here).
585 fn next_token(&mut self) -> Token<'a> {
586 if self.pos >= self.tokens.len() {
587 Self::eof_token().clone()
588 } else {
589 let tok = self.tokens[self.pos].clone();
590 self.pos += 1;
591 tok
592 }
593 }
594
595 fn backup(&mut self) {
596 if self.pos > 0 {
597 self.pos -= 1;
598 }
599 }
600
601 fn save_pos(&self) -> usize {
602 self.pos
603 }
604
605 fn restore_pos(&mut self, pos: usize) {
606 self.pos = pos;
607 }
608
609 /// Extract a namespace string from an expression.
610 /// Returns Some("name") for Variable("name"), or Some("a.b") for nested property accesses
611 /// on variables that look like namespace paths.
612 fn extract_namespace(expr: &Expr) -> Option<String> {
613 match expr {
614 Expr::Variable(name) => Some(name.with_str(str::to_owned)),
615 Expr::Property(prop) => {
616 Self::extract_namespace(&prop.expr).map(|ns| format!("{}.{}", ns, prop.property))
617 }
618 _ => None,
619 }
620 }
621
622 fn expect(&mut self, ty: TokenType) -> ParseResult<Token<'a>> {
623 let tok = self.next_token();
624 if tok.ty != ty {
625 return Err(self.expected_token_error(ty, &tok));
626 }
627 Ok(tok)
628 }
629
630 /// The `expected <ty>, got <tok>` error at `tok`, shared by every
631 /// single-token expectation.
632 fn expected_token_error(&self, ty: TokenType, tok: &Token) -> ParseError {
633 self.error_at_token(
634 tok,
635 format!("expected {:?}, got {:?} ({:?})", ty, tok.literal, tok.ty),
636 )
637 }
638
639 /// Like [`Parser::expect`] but tags the raised error with a specific
640 /// openCypher-TCK error *detail* name. Used at grammar positions
641 /// where a mismatch has a more precise classification than the generic
642 /// `UnexpectedSyntax` — e.g. the closing `]` of a relationship pattern
643 /// (`InvalidRelationshipPattern`).
644 fn expect_detail(&mut self, ty: TokenType, detail: &'static str) -> ParseResult<Token<'a>> {
645 let tok = self.next_token();
646 if tok.ty != ty {
647 return Err(self.expected_token_error(ty, &tok).with_detail(detail));
648 }
649 Ok(tok)
650 }
651
652 fn error(&self, msg: impl Into<String>) -> ParseError {
653 let tok = self.peek();
654 self.error_at_token(tok, msg)
655 }
656
657 fn error_at_token(&self, tok: &Token, msg: impl Into<String>) -> ParseError {
658 let err = ParseError::new(msg, tok.line, tok.col).with_source(self.source);
659 // A lexer error token (malformed number/unicode literal) carries the
660 // specific openCypher-TCK error *detail* it should surface — propagate
661 // it so the raised parse error reports e.g. `InvalidNumberLiteral`
662 // instead of the generic `UnexpectedSyntax`. Non-error
663 // tokens carry no detail, so this is a no-op for the common case.
664 match tok.detail {
665 Some(detail) => err.with_detail(detail),
666 None => err,
667 }
668 }
669
670 /// A violated parser-internal invariant (e.g. the `parse_postfix`
671 /// namespace-call state machine reaching a state the memoized scan's
672 /// verdict rules out). The query engine's contract is typed errors,
673 /// never panics, so even a "cannot happen" state surfaces as a typed
674 /// parse error whose message marks it as an internal bug rather than a
675 /// user-syntax problem.
676 fn internal_error(&self, msg: impl Into<String>) -> ParseError {
677 self.error(format!("internal parser error: {}", msg.into()))
678 }
679
680 // ---- Top level ----
681
682 depth_guard_family! {
683 field = expr_depth,
684 enter = enter_expr_depth,
685 exit = exit_expr_depth,
686 with = with_expr_depth,
687 enter_doc = "ADR-0257: enter one level of expression nesting. \
688 Returns a typed error naming the limit once [`MAX_NESTING_DEPTH`] \
689 levels are already active, instead of recursing until the process \
690 aborts (LABS-69). On error the counter is left unchanged, so a \
691 speculative re-parse at a shallower position is not poisoned.",
692 exit_doc = "Pairs with [`Parser::enter_expr_depth`]; must run on \
693 every exit path (including error propagation) so \
694 backtracking/speculative parses keep the counter balanced.",
695 with_doc = "Runs `f` one expression-nesting level deep: the only \
696 sanctioned way to guard a recursive expression-shaped parse with \
697 `expr_depth`. The enter/exit pair is balanced by construction -- \
698 `f`'s result (including error propagation) is captured, the \
699 counter is decremented, and only then is the result returned, so \
700 no `?` can ever sit between enter and exit.",
701 }
702
703 depth_guard_family! {
704 field = clause_depth,
705 enter = enter_clause_depth,
706 exit = exit_clause_depth,
707 with = with_clause_depth,
708 enter_doc = "ADR-0257: enter one level of clause nesting. Returns a \
709 typed error naming the limit once [`MAX_NESTING_DEPTH`] levels \
710 are already active, instead of recursing until the process aborts \
711 (LABS-69: nested FOREACH bodies recurse through `parse_clause` \
712 without passing through `parse_statement`). On error the counter \
713 is left unchanged, so a speculative re-parse at a shallower \
714 position is not poisoned.",
715 exit_doc = "Pairs with [`Parser::enter_clause_depth`]; must run on \
716 every exit path (including error propagation) so sequential \
717 clauses in one statement/FOREACH body do not accumulate.",
718 with_doc = "[`Parser::with_expr_depth`] for `clause_depth`.",
719 }
720
721 depth_guard_family! {
722 field = statement_depth,
723 enter = enter_statement_depth,
724 exit = exit_statement_depth,
725 with = with_statement_depth,
726 enter_doc = "ADR-0257: enter one level of statement nesting. Returns \
727 a typed error naming the limit once [`MAX_NESTING_DEPTH`] levels \
728 are already active, instead of recursing until the process aborts \
729 (LABS-69). On error the counter is left unchanged, so a \
730 speculative re-parse at a shallower position is not poisoned.",
731 exit_doc = "Pairs with [`Parser::enter_statement_depth`]; must run on \
732 every exit path (including error propagation) so \
733 backtracking/speculative parses keep the counter balanced.",
734 with_doc = "[`Parser::with_expr_depth`] for `statement_depth`.",
735 }
736
737 depth_guard_family! {
738 field = block_depth,
739 enter = enter_block_depth,
740 exit = exit_block_depth,
741 with = with_block_depth,
742 enter_doc = "ADR-0257: enter one level of statement-block nesting. \
743 Returns a typed error naming the limit once \
744 [`MAX_NESTING_DEPTH`] levels are already active, instead of \
745 recursing until the process aborts (LABS-69: braced single \
746 queries and WHEN/ELSE bodies recurse through \
747 `parse_statement_block` without passing through \
748 `parse_statement`, `parse_clause`, or `parse_expression`). On \
749 error the counter is left unchanged, so a speculative re-parse \
750 at a shallower position is not poisoned.",
751 exit_doc = "Pairs with [`Parser::enter_block_depth`]; must run on \
752 every exit path (including error propagation) so sequential NEXT \
753 stages in one block and backtracking/speculative parses keep the \
754 counter balanced.",
755 with_doc = "[`Parser::with_expr_depth`] for `block_depth`.",
756 }
757
758 depth_guard_family! {
759 field = pattern_element_depth,
760 enter = enter_pattern_element_depth,
761 exit = exit_pattern_element_depth,
762 with = with_pattern_element_depth,
763 enter_doc = "Enter one level of pattern-element label/type chain \
764 nesting (a node pattern's labels, a relationship pattern's \
765 types). Scoped by the element parsers around their \
766 `parse_label_spec` calls so the comprehension pipe-ambiguity \
767 rule's `{` dead end stays suppressed for exactly that chain \
768 (see `chain_tail_ends_where`).",
769 exit_doc = "Pairs with [`Parser::enter_pattern_element_depth`]; \
770 balanced by construction through \
771 [`Parser::with_pattern_element_depth`].",
772 with_doc = "Runs `f` one pattern-element chain level deep: the \
773 element parsers' one way to scope a `parse_label_spec` call, \
774 so the depth is balanced by construction and no `?` can sit \
775 between enter and exit.",
776 }
777
778 /// Parses an `Integer` token as a `u32` bound (relationship hop count,
779 /// path quantifier bound, number of paths/groups) via the checked
780 /// [`parse_int_literal`] path. Literals that don't fit are a typed parse
781 /// error naming the bound -- never a silent clamp (LABS-81:
782 /// `[*99999999999..2]` used to parse as `min_hops = 1`).
783 fn parse_u32_bound(&self, tok: &Token, what: &str) -> ParseResult<u32> {
784 // Both failures render through the one integer-literal error path,
785 // naming the bound.
786 let site = IntLiteralSite::Bounded {
787 what,
788 max: u64::from(u32::MAX),
789 };
790 let value = parse_int_literal(&tok.literal)
791 .map_err(|error| self.int_literal_error(tok, error, site))?;
792 u32::try_from(value)
793 .map_err(|_| self.int_literal_error(tok, IntLiteralError::Overflow, site))
794 }
795 /// Type of the token at absolute index `pos` (`EOF` past the end) --
796 /// the absolute-index counterpart of [`Self::peek_at`] for
797 /// token-level scans, in the idiom of `scan_dot_chain_for_call`.
798 fn token_type_at(&self, pos: usize) -> TokenType {
799 match self.tokens.get(pos) {
800 Some(t) => t.ty,
801 None => TokenType::EOF,
802 }
803 }
804
805 /// Lookahead from `self.pos` without consuming tokens: true when
806 /// `target` appears at depth 0 before the closer that ends the
807 /// construct opened just before `self.pos` (the caller has already
808 /// consumed the opener). Only the bracket kinds in [`BracketSet`]
809 /// count toward the depth, so a paren-only scan (inside a call's
810 /// argument list) and an all-bracket scan (inside a comprehension
811 /// brace, whose source expression can nest brackets and parens) are
812 /// explicit per-site choices. The one scan behind
813 /// [`Parser::trim_args_have_top_level_from`],
814 /// [`Parser::pipe_before_closing_paren`], and
815 /// [`Parser::has_pipe_before_matching_brace`].
816 fn top_level_token_before_matching_close(
817 &self,
818 target: TokenType,
819 brackets: BracketSet,
820 ) -> bool {
821 let mut depth = 0usize;
822 let mut pos = self.pos;
823 loop {
824 match self.token_type_at(pos) {
825 TokenType::EOF => return false,
826 ty if brackets.opens(ty) => depth += 1,
827 ty if brackets.closes(ty) => {
828 if depth == 0 {
829 return false; // the construct's own closer
830 }
831 depth -= 1;
832 }
833 ty if ty == target && depth == 0 => return true,
834 _ => {}
835 }
836 pos += 1;
837 }
838 }
839}
840
841/// The bracket kinds a
842/// [`Parser::top_level_token_before_matching_close`] scan counts toward
843/// its depth — the per-site choice of which groups are transparent,
844/// declared beside the scan it parameterizes.
845#[derive(Clone, Copy)]
846enum BracketSet {
847 /// Only `(` / `)` nest: the scan runs inside a call's argument list.
848 Parens,
849 /// `{`, `[`, and `(` all nest: the scan runs inside a comprehension
850 /// brace, whose source expression can contain brackets and parens.
851 AllBrackets,
852}
853
854impl BracketSet {
855 /// True when `ty` is an opening bracket of one of this set's kinds.
856 fn opens(self, ty: TokenType) -> bool {
857 match self {
858 BracketSet::Parens => ty == TokenType::LeftParen,
859 BracketSet::AllBrackets => matches!(
860 ty,
861 TokenType::LeftBrace | TokenType::LeftBracket | TokenType::LeftParen
862 ),
863 }
864 }
865
866 /// True when `ty` is a closing bracket of one of this set's kinds.
867 fn closes(self, ty: TokenType) -> bool {
868 match self {
869 BracketSet::Parens => ty == TokenType::RightParen,
870 BracketSet::AllBrackets => matches!(
871 ty,
872 TokenType::RightBrace | TokenType::RightBracket | TokenType::RightParen
873 ),
874 }
875 }
876}
877
878mod annotations;
879mod case;
880mod clauses;
881mod definitions;
882mod expressions;
883mod interp;
884mod is_predicate;
885mod labels;
886mod literals;
887mod names;
888// The operator spellings (ADR-0505 §2) — imported explicitly by the
889// submodules that use them (`case`, `expressions`, `is_predicate`,
890// `annotations`).
891mod operators;
892mod patterns;
893
894pub use definitions::literal_argument_mismatch;
895pub use patterns::selector_is_selective;
896mod schema;
897mod search;
898mod show;
899mod statement;
900mod types;
901
902#[cfg(test)]
903mod tests;
904
905/// True if any element of a quantified path pattern's operand is itself
906/// quantified -- directly (`PatternElement::Quantified`) or via a
907/// variable-length/quantified relationship (`RelPattern` with hop bounds,
908/// whether legacy `*min..max` or the CIP-28 postfix form) -- which CIP-28
909/// forbids (no nested quantification).
910fn contains_quantification(elements: &[PatternElement]) -> bool {
911 elements.iter().any(|e| match e {
912 PatternElement::Quantified(_) => true,
913 PatternElement::Relationship(rp) => rp.is_variable_length(),
914 PatternElement::Node(_) => false,
915 })
916}
917
918/// True if `elements` contains a *GPM-syntax* quantification -- a
919/// quantified path pattern (`((...))+`) or a CIP-28 Form-5 postfix-quantified
920/// relationship (`-->+`, `-[]->{1,5}`) -- but *not* the legacy bracket
921/// variable-length form (`-[*1..5]->`), which remains legal inside
922/// `shortestPath(...)`/`allShortestPaths(...)` (CIP-40 path-selector-mixing
923/// scenario 7). Used to reject `QuantifiedPathPatternInShortestPath`
924/// (scenario 6).
925fn contains_gpm_quantification(elements: &[PatternElement]) -> bool {
926 elements.iter().any(|e| match e {
927 PatternElement::Quantified(_) => true,
928 PatternElement::Relationship(rp) => rp.quantified,
929 PatternElement::Node(_) => false,
930 })
931}
932
933// Test-only probe for the CIP-272 map-comprehension lookahead: counts the
934// speculative full parses entered for a `{` in expression position. A brace
935// with no top-level `|` must never reach that parse (the exponential
936// parse-time regression), so the regression test asserts on this count rather
937// than on wall-clock time. Thread-local: the test harness runs every test on
938// its own thread.
939#[cfg(test)]
940std::thread_local! {
941 static SPECULATIVE_COMPREHENSION_PARSES: std::cell::Cell<usize> =
942 const { std::cell::Cell::new(0) };
943}