Skip to main content

relate_parser/
token.rs

1use std::borrow::Cow;
2
3// The token-fact vocabulary (REL8-1423): the generic kind classification
4// (`ends_expression` / `introduces_operand`) the bracket classification
5// derives from — a submodule of the token module with the other kind
6// predicates (its file lives at `token/facts.rs`).
7mod facts;
8
9/// Token types for the Cypher lexer.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11pub enum TokenType {
12    // Special tokens
13    EOF,
14    Error,
15    Identifier,
16    Integer,
17    Float,
18    String,
19    /// CIP-261 interpolated string literal `s'...'` / `s"..."`. Payload is
20    /// the body between the quotes with standard escapes resolved; `\{` and
21    /// `\}` stay as two characters so the parser can tell an escaped literal
22    /// brace from an expression delimiter, and raw `{`/`}` are kept for the
23    /// parser to split into text/expression parts.
24    InterpString,
25    /// The Neo4j internal obfuscated literal `******` (exactly six stars),
26    /// lexed only under the `obfuscated-literals` preview gate: a dummy
27    /// `false` for semantic analysis, never meant to execute. Without the
28    /// gate the run lexes as ordinary `*` tokens and the query fails with
29    /// the parser's own syntax error, Neo4j's disabled-form behavior.
30    ObfuscatedLiteral,
31    /// The CIP-281 annotation introducer `@`, lexed only under the
32    /// `cypher-annotations` preview gate. Without the gate `@` is the
33    /// ordinary `unexpected character: @` error token.
34    At,
35    Parameter, // $param
36
37    // Punctuation
38    LeftParen,    // (
39    RightParen,   // )
40    LeftBracket,  // [
41    RightBracket, // ]
42    LeftBrace,    // {
43    RightBrace,   // }
44    Colon,        // :
45    DoubleColon,  // ::
46    Comma,        // ,
47    Dot,          // .
48    Semicolon,    // ;
49    Pipe,         // |
50    DoublePipe,   // ||
51    Dash,         // -
52    ArrowRight,   // ->
53    ArrowLeft,    // <-
54    FatArrow,     // => (CIP-176/CIP-187 graph type declaration syntax)
55    Star,         // *
56    Plus,         // +
57    Slash,        // /
58    Percent,      // %
59    Caret,        // ^
60    DotDot,       // ..
61    Bang,         // ! (CIP-102 NOT NULL type shorthand; also GQL label negation, CIP-14)
62    Ampersand,    // & (GQL label expression conjunction, CIP-14)
63
64    // Comparison operators
65    Equals,       // =
66    NotEquals,    // <>
67    LessThan,     // <
68    GreaterThan,  // >
69    LessEqual,    // <=
70    GreaterEqual, // >=
71    RegexMatch,   // =~
72
73    // Keywords
74    MATCH,
75    OPTIONAL,
76    CREATE,
77    INSERT,
78    MERGE,
79    DELETE,
80    DETACH,
81    SET,
82    REMOVE,
83    RETURN,
84    WITH,
85    UNWIND,
86    WHERE,
87    ORDER,
88    BY,
89    ASC,
90    DESC,
91    LIMIT,
92    SKIP,
93    AS,
94    DISTINCT,
95    AND,
96    OR,
97    NOT,
98    XOR,
99    IN,
100    STARTS,
101    ENDS,
102    CONTAINS,
103    IS,
104    NULL,
105    TRUE,
106    FALSE,
107    CASE,
108    WHEN,
109    THEN,
110    ELSE,
111    END,
112    FOREACH,
113    CALL,
114    YIELD,
115    UNION,
116    ALL,
117    ON,
118    INDEX,
119    CONSTRAINT,
120    FOR,
121    REQUIRE,
122    UNIQUE,
123    EXISTS,
124    IF,
125    DROP,
126    VECTOR,
127    POINT,
128    OPTIONS,
129    NODE,
130    REL,
131    COUNT,
132    COLLECT,
133    LOAD,
134    FROM,
135    CSV,
136    REDUCE,
137    SPATIAL,
138    EXPLAIN,
139    PROFILE,
140    INFINITY, // Infinity/Inf literal (CIP-55)
141    NAN,      // NaN literal (CIP-55)
142}
143
144impl TokenType {
145    /// A relationship pattern's start after a node pattern's `)`: the `-`
146    /// of `-[…]`/`--` or the `<-` of an incoming edge — the token pair
147    /// that tells a pattern (a predicate, a comprehension) from a
148    /// parenthesized expression. Consulted by the node-pattern lookahead
149    /// gate and the schema reader's FOR-target discrimination; the
150    /// pattern-body element loops spell the pair inside their wider
151    /// element-alternations, where a standalone predicate does not fit.
152    ///
153    /// Three consumer classes, one deliberate split:
154    ///
155    /// - the expression-context gates (the pattern-predicate and
156    ///   comprehension lookaheads) consult this fused pair only: there a
157    ///   `<` after a `)` keeps its comparison meaning (`RETURN (a) < -1`
158    ///   is a comparison against a negated operand), so the spaced left
159    ///   head is never claimed in an expression;
160    /// - the schema DDL FOR-target lookaheads are deliberately fused-only
161    ///   too — a deferred acceptance, not an expression context: no
162    ///   verified behavior exists yet for a spaced `< -` head in
163    ///   `CREATE INDEX/CONSTRAINT … FOR () < - [r:R] - ()`, so they keep
164    ///   rejecting it until one does;
165    /// - the pattern-body element loops admit the full set through
166    ///   [`Self::is_pattern_body_relationship_start`], the documented
167    ///   superset.
168    pub(crate) fn is_relationship_start(self) -> bool {
169        matches!(self, Self::Dash | Self::ArrowLeft)
170    }
171
172    /// The pattern-body superset of [`Self::is_relationship_start`]:
173    /// every token that opens a relationship element arm inside a
174    /// pattern body -- the fused pair (derived, so the superset holds by
175    /// construction), the spaced left head `< -` (a LessThan whose head
176    /// dash follows), and the stranded `->` of the single-dash form,
177    /// which the loop routes into the relationship head error instead of
178    /// a generic clause error. Consulted by the pattern-body element
179    /// loops and the unquantified-group juxtaposition rejection; never
180    /// by an expression-context gate or a DDL lookahead (see
181    /// [`Self::is_relationship_start`] for the split).
182    pub(crate) fn is_pattern_body_relationship_start(self) -> bool {
183        matches!(self, Self::LessThan | Self::ArrowRight) || self.is_relationship_start()
184    }
185
186    /// The tokens that continue a pattern body after an element: a new
187    /// node or group's `(`, or any relationship head (derived). Consulted
188    /// by the pattern-body element loop's continuation guard and the
189    /// unquantified-group juxtaposition rejection, so "an element
190    /// follows" has one home instead of two token lists.
191    pub(crate) fn starts_pattern_element(self) -> bool {
192        self == Self::LeftParen || self.is_pattern_body_relationship_start()
193    }
194
195    /// The tokens that can begin a CIP-28 quantifier (`*`, `+`, `{m,n}`):
196    /// consulted by the two pattern-body guards that look ahead for one
197    /// (the parenthesized-subpath group and the relationship pattern's
198    /// postfix quantifier), and named by the quantifier reader's
199    /// contract (`Parser::parse_quantifier`).
200    pub(crate) fn is_quantifier_start(self) -> bool {
201        matches!(self, Self::Star | Self::Plus | Self::LeftBrace)
202    }
203
204    /// The equality comparison's spelling — the one comparison with a
205    /// build site that has no token to read the table from: simple-CASE's
206    /// plain-value default (`parse_when_operand_element`). The table's
207    /// own `Equals` row reads this constant, so the text has one owner.
208    pub(crate) const EQUALS: &str = "=";
209
210    /// The dialect's comparison operators and their ADR-0505 §2 spellings,
211    /// ONE table at the lowest shared module (the token layer owns text
212    /// policy — `quote_identifier`, `is_field_terminator_word`): the set
213    /// and the spelling of every comparison variant live together. Its
214    /// readers: `Parser::take_comparison_spelling` (the cursor's
215    /// consuming read), the tokenless simple-CASE default
216    /// ([`Self::EQUALS`]), and the token-fact pin, which iterates
217    /// [`COMPARISON_SPELLINGS`].
218    pub(crate) fn comparison_spelling(self) -> Option<&'static str> {
219        COMPARISON_SPELLINGS
220            .iter()
221            .find(|(ty, _)| *ty == self)
222            .map(|(_, spelling)| *spelling)
223    }
224
225    /// Returns true if this token type is a keyword (MATCH..PROFILE range).
226    pub fn is_keyword(self) -> bool {
227        matches!(
228            self,
229            TokenType::MATCH
230                | TokenType::OPTIONAL
231                | TokenType::CREATE
232                | TokenType::INSERT
233                | TokenType::MERGE
234                | TokenType::DELETE
235                | TokenType::DETACH
236                | TokenType::SET
237                | TokenType::REMOVE
238                | TokenType::RETURN
239                | TokenType::WITH
240                | TokenType::UNWIND
241                | TokenType::WHERE
242                | TokenType::ORDER
243                | TokenType::BY
244                | TokenType::ASC
245                | TokenType::DESC
246                | TokenType::LIMIT
247                | TokenType::SKIP
248                | TokenType::AS
249                | TokenType::DISTINCT
250                | TokenType::AND
251                | TokenType::OR
252                | TokenType::NOT
253                | TokenType::XOR
254                | TokenType::IN
255                | TokenType::STARTS
256                | TokenType::ENDS
257                | TokenType::CONTAINS
258                | TokenType::IS
259                | TokenType::NULL
260                | TokenType::TRUE
261                | TokenType::FALSE
262                | TokenType::CASE
263                | TokenType::WHEN
264                | TokenType::THEN
265                | TokenType::ELSE
266                | TokenType::END
267                | TokenType::FOREACH
268                | TokenType::CALL
269                | TokenType::YIELD
270                | TokenType::UNION
271                | TokenType::ALL
272                | TokenType::ON
273                | TokenType::INDEX
274                | TokenType::CONSTRAINT
275                | TokenType::FOR
276                | TokenType::REQUIRE
277                | TokenType::UNIQUE
278                | TokenType::EXISTS
279                | TokenType::IF
280                | TokenType::DROP
281                | TokenType::VECTOR
282                | TokenType::POINT
283                | TokenType::OPTIONS
284                | TokenType::NODE
285                | TokenType::REL
286                | TokenType::COUNT
287                | TokenType::COLLECT
288                | TokenType::LOAD
289                | TokenType::FROM
290                | TokenType::CSV
291                | TokenType::REDUCE
292                | TokenType::SPATIAL
293                | TokenType::EXPLAIN
294                | TokenType::PROFILE
295                | TokenType::INFINITY
296                | TokenType::NAN
297        )
298    }
299
300    /// Returns true if the token can be used as an identifier (variable,
301    /// alias, map key, ...): `Identifier` or any keyword except the
302    /// [`CLAUSE_KEYWORDS`].
303    pub fn is_ident_like(self) -> bool {
304        self.is_schema_name() && !CLAUSE_KEYWORDS.contains(&self)
305    }
306
307    /// Returns true if the token is `Identifier` or any keyword: openCypher's
308    /// `SchemaName ::= SymbolicName | ReservedWord`, for positions where the
309    /// grammar already requires a name, so no keyword there starts a clause
310    /// -- property keys after `.`, the LET binding variable, and label and
311    /// relationship-type names. ADR-0169: a strict superset of
312    /// `is_ident_like()`, so `(o:Order)` and `-[:ORDER]->` parse unquoted
313    /// with the name kept as written.
314    ///
315    /// This token class is unrelated to, and deliberately wider than, the
316    /// narrower thing this crate also calls a schema name: the
317    /// index/constraint name `ast::SchemaName` that
318    /// `parse_optional_schema_name` / `parse_required_schema_name` read
319    /// (the command-name readers' admissible set — see
320    /// `Parser::parse_optional_schema_name` — plus a `$param`).
321    pub fn is_schema_name(self) -> bool {
322        self == TokenType::Identifier || self.is_keyword()
323    }
324}
325
326/// The comparison family's variants and their ADR-0505 §2 spellings — the
327/// one enumerable home of the set: [`TokenType::comparison_spelling`]
328/// consults it, and the token-fact pin iterates it, so "every variant
329/// with a spelling introduces an operand" is asserted over the table
330/// itself, never over a hand-copied list.
331pub(crate) const COMPARISON_SPELLINGS: [(TokenType, &str); 7] = [
332    (TokenType::Equals, TokenType::EQUALS),
333    (TokenType::NotEquals, "<>"),
334    (TokenType::LessThan, "<"),
335    (TokenType::GreaterThan, ">"),
336    (TokenType::LessEqual, "<="),
337    (TokenType::GreaterEqual, ">="),
338    (TokenType::RegexMatch, "=~"),
339];
340
341/// The clause keywords: keyword tokens that start or continue a clause
342/// (`MATCH`, `ORDER BY`, `AS`, `DISTINCT`, ...). `is_ident_like()` rejects
343/// them as variables, aliases and map keys, so `(WHERE ...)` does not read
344/// `WHERE` as the element variable. ADR-0169: they are still label and
345/// relationship-type names (`is_schema_name()`).
346///
347/// `RETURN` is not one of them. Verified
348/// against live Neo4j 2026.05 (both CYPHER 5 and CYPHER 25): `RETURN` is a
349/// non-reserved word usable as an ordinary variable/alias name (e.g.
350/// `WITH 1 AS RETURN RETURN RETURN AS r`) -- `is_ident_like()` is only
351/// checked in positions the grammar already knows unambiguously expect an
352/// identifier (after AS, as a pattern/FOREACH variable, ...), so it never
353/// shadows RETURN's role starting a new clause.
354pub const CLAUSE_KEYWORDS: [TokenType; 22] = [
355    TokenType::MATCH,
356    TokenType::OPTIONAL,
357    TokenType::CREATE,
358    TokenType::INSERT,
359    TokenType::MERGE,
360    TokenType::DELETE,
361    TokenType::DETACH,
362    TokenType::SET,
363    TokenType::REMOVE,
364    TokenType::WITH,
365    TokenType::UNWIND,
366    TokenType::WHERE,
367    TokenType::ORDER,
368    TokenType::BY,
369    TokenType::LIMIT,
370    TokenType::SKIP,
371    TokenType::AS,
372    TokenType::DISTINCT,
373    TokenType::FOREACH,
374    TokenType::UNION,
375    TokenType::REQUIRE,
376    TokenType::DROP,
377];
378
379/// The contextual `FIELDTERMINATOR` word of LOAD CSV: an identifier-spelled
380/// keyword the clause parser discriminates on by spelling. The one
381/// constant, shared with the statement normalizer's grammar guard (a
382/// `String` after this word is a literal-only position there) — the
383/// spelling is a centralized fact, never re-derived at a second site.
384pub(crate) const FIELDTERMINATOR_WORD: &str = "FIELDTERMINATOR";
385
386/// Whether an identifier's literal spells the LOAD CSV
387/// [`FIELDTERMINATOR_WORD`] (case-insensitively, as the clause grammar
388/// reads it).
389pub(crate) fn is_field_terminator_word(literal: &str) -> bool {
390    literal.eq_ignore_ascii_case(FIELDTERMINATOR_WORD)
391}
392
393/// The reserved-keyword clause-starter tokens: the keyword tokens that
394/// start a new clause at clause position (`MATCH`, `CREATE`, `UNWIND`,
395/// `FOR` (CIP-250), ...). The grammar authority is the clause dispatch
396/// (`Parser::parse_clause_inner`); this table is the derived vocabulary
397/// every *lookahead* over the same fact consults instead of re-spelling a
398/// second hand-maintained list -- through [`is_clause_boundary`], by
399/// `Parser::group_by_ends_clause` (whose round-5 comment records the
400/// LOAD/DROP drift that motivated it) and the simple-CASE lookahead -- and
401/// the dispatch-coverage pin test. A new clause-start dispatch arm
402/// extends this one table. `OPTIONAL` is a member: it starts a clause
403/// only immediately before `MATCH`/`CALL` (the arm that checks what
404/// follows). The contextual (identifier-spelled) starters are the
405/// separate [`CONTEXTUAL_CLAUSE_WORDS`] below.
406pub const CLAUSE_STARTER_TOKENS: &[TokenType] = &[
407    TokenType::MATCH,
408    TokenType::OPTIONAL,
409    TokenType::CREATE,
410    TokenType::INSERT,
411    TokenType::MERGE,
412    TokenType::DELETE,
413    TokenType::DETACH,
414    TokenType::SET,
415    TokenType::REMOVE,
416    TokenType::UNWIND,
417    // `FOR <variable> IN <expression>`.
418    TokenType::FOR,
419    TokenType::FOREACH,
420    TokenType::CALL,
421    TokenType::UNION,
422    TokenType::LOAD,
423    TokenType::DROP,
424];
425
426/// The one derived "this token ends the enclosing clause" predicate: a
427/// reserved clause keyword ([`CLAUSE_KEYWORDS`]) or a reserved clause
428/// starter ([`CLAUSE_STARTER_TOKENS`]). Every lookahead that must stop at a
429/// clause boundary consults this instead of re-spelling the vocabulary —
430/// `Parser::group_by_ends_clause` and the simple-CASE lookahead
431/// (`ends_case_test_scan`), each adding only its own statement/item
432/// terminals.
433pub(crate) fn is_clause_boundary(ty: TokenType) -> bool {
434    CLAUSE_KEYWORDS.contains(&ty) || CLAUSE_STARTER_TOKENS.contains(&ty)
435}
436
437/// The contextual (non-reserved, identifier-spelled) clause keywords:
438/// words that start or continue a clause when they appear as a plain
439/// `Identifier` at clause position, recognized by spelling -- the same
440/// role as [`CLAUSE_KEYWORDS`], but these stay usable as ordinary
441/// variable/label names everywhere else (`MATCH (show) RETURN show`).
442/// Single-sourced here so the clause dispatcher
443/// (`Parser::parse_clause_inner`) and the `SHOW SETTINGS`-style
444/// filter-expression starter (`Parser::peek_starts_show_filter_expr`,
445/// which excludes exactly this set so a following composed clause is not
446/// swallowed as a filter expression) can never drift apart.
447///
448/// `NEXT` (CIP-213) and `CYPHER` (preamble) are members even though they
449/// never start a clause inside `parse_clause_inner` -- they are
450/// recognized at statement-block boundaries and in the pre-parser
451/// preamble respectively. `START`/`STOP`/`NODETACH`/`OFFSET` are
452/// deliberately *not* members: they only act clause-like before a
453/// specific following word (`DATABASE`/`DELETE`/paging), so a bare
454/// `SHOW SETTINGS start` still reads `start` as a name filter.
455pub const CONTEXTUAL_CLAUSE_WORDS: [&str; 9] = [
456    "alter",
457    "cypher",
458    "filter",
459    "finish",
460    "let",
461    "next",
462    "show",
463    "terminate",
464    "use",
465];
466
467/// True if `literal` (any case) spells one of the
468/// [`CONTEXTUAL_CLAUSE_WORDS`].
469pub fn is_contextual_clause_keyword(literal: &str) -> bool {
470    CONTEXTUAL_CLAUSE_WORDS
471        .iter()
472        .any(|w| literal.eq_ignore_ascii_case(w))
473}
474
475/// A lexical token with its type, literal value, and source position.
476///
477/// The literal text borrows from the lexer's input (`'a`): identifiers,
478/// keywords, numbers, parameters and escape-free string literals are slices
479/// of the query text, and punctuation/operators and fixed error texts are
480/// `&'static str` (which coerces to `'a`). Only synthesized text is owned —
481/// escape-decoded string literals and `format!`-built error messages — so
482/// the token stream costs no heap allocation per token beyond the
483/// `Vec<Token>` itself (ADR-0505). Tokens never outlive the input: the only
484/// consumer is the [`crate::parser::Parser`], built and dropped inside the
485/// parse entry points.
486#[derive(Debug, Clone, PartialEq)]
487pub struct Token<'a> {
488    pub ty: TokenType,
489    pub literal: Cow<'a, str>,
490    pub line: usize,
491    pub col: usize,
492    /// Optional symbolic openCypher-TCK error-*detail* name carried by a
493    /// [`TokenType::Error`] token (e.g. `"InvalidNumberLiteral"`,
494    /// `"InvalidUnicodeLiteral"`). The parser propagates it onto the
495    /// [`crate::ParseError`] it raises when it surfaces the error token, so a
496    /// malformed number/unicode literal reports its specific TCK detail rather
497    /// than the generic `UnexpectedSyntax`. `None` for every non-error token.
498    pub detail: Option<&'static str>,
499}
500
501impl<'a> Token<'a> {
502    /// The `$(expr)` dynamic-opener sentinel: a Parameter token with the
503    /// empty literal — the reserved encoding the lexer emits for the `(`
504    /// glued to the `$`, the parser expands
505    /// (`dynamic_label_quantifier_at`'s Default arm) and the normalizer
506    /// declines to render (the empty literal is an encoding, never a
507    /// name — see `cache_insert_eligible` for the separate
508    /// dynamic-operand uncacheability rule). The one home of the
509    /// encoding: no call site re-tests the raw literal. `pub(crate)`: both
510    /// consumers are in-crate (the normalizer, the parser's quantifier) —
511    /// widen only when a crate outside `relate-parser` must decode the
512    /// sentinel.
513    pub(crate) fn is_dynamic_opener_sentinel(&self) -> bool {
514        matches!(self.ty, TokenType::Parameter) && self.literal.is_empty()
515    }
516
517    /// Build a token whose text is borrowed (`&'a str` / `&'static str`) or
518    /// owned (`String`), per the ADR-0505 literal rule — `Into<Cow>` accepts
519    /// all three without a hidden copy.
520    pub fn new(ty: TokenType, literal: impl Into<Cow<'a, str>>, line: usize, col: usize) -> Self {
521        Token {
522            ty,
523            literal: literal.into(),
524            line,
525            col,
526            detail: None,
527        }
528    }
529
530    /// Build a [`TokenType::Error`] token tagged with a TCK error-detail name
531    /// (see [`Token::detail`]).
532    pub fn error_with_detail(
533        literal: impl Into<Cow<'a, str>>,
534        line: usize,
535        col: usize,
536        detail: &'static str,
537    ) -> Self {
538        Token {
539            ty: TokenType::Error,
540            literal: literal.into(),
541            line,
542            col,
543            detail: Some(detail),
544        }
545    }
546}
547
548/// The one declaration of the keyword vocabulary [`lookup_keyword`]
549/// accepts: each `spelling => variant` pair (aliases included) generates
550/// the stack-buffer match cascade, the derived [`LONGEST_KEYWORD_BYTES`]
551/// bound, the test's spelling table and the [`keyword_spellings`]
552/// iterator over it, so the cascade, the bound, the table and the
553/// iterator can never drift apart — a spelling added here is classified,
554/// bounded and exercised in the same change, and a spelling forgotten
555/// cannot exist (there is no second list to forget it from).
556macro_rules! declare_keywords {
557    ($( $spelling:literal => $variant:expr ),+ $(,)?) => {
558        /// The longest keyword spelling accepted by [`lookup_keyword`] in
559        /// bytes (`CONSTRAINT`, `DESCENDING`) — derived from the one
560        /// vocabulary declaration below, never re-spelled at the
561        /// short-circuit or the stack buffer size, so no arm can fall
562        /// outside the bound.
563        const LONGEST_KEYWORD_BYTES: usize = {
564            let lengths = [$($spelling.len()),+];
565            let mut longest = 0;
566            let mut i = 0;
567            while i < lengths.len() {
568                if lengths[i] > longest {
569                    longest = lengths[i];
570                }
571                i += 1;
572            }
573            longest
574        };
575
576        /// Look up a keyword from an identifier string (case-insensitive
577        /// uppercase).
578        ///
579        /// No heap copy (ADR-0505): identifiers longer than
580        /// [`LONGEST_KEYWORD_BYTES`] short-circuit to `Identifier`; shorter
581        /// ones are ASCII-uppercased into a fixed stack buffer and matched
582        /// against byte literals. Non-ASCII bytes pass through untouched
583        /// (only `make_ascii_uppercase` is applied), so a Unicode
584        /// identifier (ADR-0182) never matches a keyword — the same
585        /// behavior `to_ascii_uppercase` gave.
586        pub fn lookup_keyword(ident: &str) -> TokenType {
587            if ident.len() > LONGEST_KEYWORD_BYTES {
588                return TokenType::Identifier;
589            }
590            let mut buf = [0u8; LONGEST_KEYWORD_BYTES];
591            let bytes = ident.as_bytes();
592            buf[..bytes.len()].copy_from_slice(bytes);
593            buf[..bytes.len()].make_ascii_uppercase();
594            match &buf[..bytes.len()] {
595                $( $spelling => $variant, )+
596                _ => TokenType::Identifier,
597            }
598        }
599
600        /// Every `(spelling, variant)` pair of the vocabulary, aliases
601        /// included — generated from the same declaration as the cascade,
602        /// so the test below pins the cascade itself, not a hand-copied
603        /// twin of it. The tests' one spelling iterator
604        /// ([`keyword_spellings`], directly below) derives from this same
605        /// single vocabulary home; the const itself stays private to the
606        /// module, so every consumer goes through the iterator and no
607        /// site decodes the byte-literal table inline.
608        #[cfg(test)]
609        const KEYWORD_SPELLINGS: &[(&[u8], TokenType)] = &[$(($spelling, $variant)),+];
610
611        /// [`KEYWORD_SPELLINGS`] as `&'static str` spellings — the one
612        /// decode of the byte-literal table, kept beside the table it
613        /// iterates so no test site converts inline. The declaration's
614        /// match patterns force byte-literal spellings, so every one is
615        /// ASCII by construction and the conversion is infallible.
616        /// `pub(crate)`: the token module's own tests and the parser's
617        /// schema tests share it.
618        #[cfg(test)]
619        pub(crate) fn keyword_spellings() -> impl Iterator<Item = (&'static str, TokenType)> {
620            KEYWORD_SPELLINGS.iter().map(|&(spelling, ty)| {
621                (
622                    std::str::from_utf8(spelling).expect("keyword spellings are ASCII"),
623                    ty,
624                )
625            })
626        }
627    };
628}
629
630declare_keywords! {
631    b"MATCH" => TokenType::MATCH,
632    b"OPTIONAL" => TokenType::OPTIONAL,
633    b"CREATE" => TokenType::CREATE,
634    b"INSERT" => TokenType::INSERT,
635    b"MERGE" => TokenType::MERGE,
636    b"DELETE" => TokenType::DELETE,
637    b"DETACH" => TokenType::DETACH,
638    b"SET" => TokenType::SET,
639    b"REMOVE" => TokenType::REMOVE,
640    b"RETURN" => TokenType::RETURN,
641    b"WITH" => TokenType::WITH,
642    b"UNWIND" => TokenType::UNWIND,
643    b"WHERE" => TokenType::WHERE,
644    b"ORDER" => TokenType::ORDER,
645    b"BY" => TokenType::BY,
646    b"ASC" => TokenType::ASC,
647    b"ASCENDING" => TokenType::ASC,
648    b"DESC" => TokenType::DESC,
649    b"DESCENDING" => TokenType::DESC,
650    b"LIMIT" => TokenType::LIMIT,
651    b"SKIP" => TokenType::SKIP,
652    b"AS" => TokenType::AS,
653    b"DISTINCT" => TokenType::DISTINCT,
654    b"AND" => TokenType::AND,
655    b"OR" => TokenType::OR,
656    b"NOT" => TokenType::NOT,
657    b"XOR" => TokenType::XOR,
658    b"IN" => TokenType::IN,
659    b"STARTS" => TokenType::STARTS,
660    b"ENDS" => TokenType::ENDS,
661    b"CONTAINS" => TokenType::CONTAINS,
662    b"IS" => TokenType::IS,
663    b"NULL" => TokenType::NULL,
664    b"TRUE" => TokenType::TRUE,
665    b"FALSE" => TokenType::FALSE,
666    b"CASE" => TokenType::CASE,
667    b"WHEN" => TokenType::WHEN,
668    b"THEN" => TokenType::THEN,
669    b"ELSE" => TokenType::ELSE,
670    b"END" => TokenType::END,
671    b"FOREACH" => TokenType::FOREACH,
672    b"CALL" => TokenType::CALL,
673    b"YIELD" => TokenType::YIELD,
674    b"UNION" => TokenType::UNION,
675    b"ALL" => TokenType::ALL,
676    b"ON" => TokenType::ON,
677    b"INDEX" => TokenType::INDEX,
678    b"CONSTRAINT" => TokenType::CONSTRAINT,
679    b"FOR" => TokenType::FOR,
680    b"REQUIRE" => TokenType::REQUIRE,
681    b"UNIQUE" => TokenType::UNIQUE,
682    b"EXISTS" => TokenType::EXISTS,
683    b"IF" => TokenType::IF,
684    b"DROP" => TokenType::DROP,
685    b"VECTOR" => TokenType::VECTOR,
686    b"POINT" => TokenType::POINT,
687    b"OPTIONS" => TokenType::OPTIONS,
688    b"NODE" => TokenType::NODE,
689    b"REL" => TokenType::REL,
690    b"COUNT" => TokenType::COUNT,
691    b"COLLECT" => TokenType::COLLECT,
692    b"LOAD" => TokenType::LOAD,
693    b"FROM" => TokenType::FROM,
694    b"CSV" => TokenType::CSV,
695    b"REDUCE" => TokenType::REDUCE,
696    b"SPATIAL" => TokenType::SPATIAL,
697    b"EXPLAIN" => TokenType::EXPLAIN,
698    b"PROFILE" => TokenType::PROFILE,
699    b"INFINITY" => TokenType::INFINITY,
700    b"INF" => TokenType::INFINITY,
701    b"NAN" => TokenType::NAN,
702}
703
704/// True when `name` must be backtick-quoted to round-trip as a Cypher name.
705///
706/// The DDL / canonical identifier-quoting policy: a name is bare only when it
707/// has the plain identifier shape
708/// ([`relate_model::identifier::has_plain_identifier_shape`]) **and**
709/// [`lookup_keyword`] does not classify it as a keyword.
710///
711/// Keyword names need quotes even in positions that accept them bare (a
712/// property key after `.`, a label or relationship type per ADR-0169) because
713/// the same spelling is a keyword in the positions that call
714/// [`TokenType::is_ident_like`] — a variable, alias, map key, or the
715/// `ON (n.prop)` property name of `CREATE INDEX` — so the unquoted form
716/// would not parse everywhere. Quoting every keyword keeps one rendered
717/// statement runnable in every position instead of deciding per site.
718pub fn identifier_needs_quotes(name: &str) -> bool {
719    !relate_model::identifier::has_plain_identifier_shape(name) || lookup_keyword(name).is_keyword()
720}
721
722/// Renders `name` as a Cypher identifier for generated Cypher text: bare
723/// when [`identifier_needs_quotes`] is false, otherwise through
724/// [`relate_model::identifier::quote_identifier_always`] (the one
725/// spelling of the quoting escape).
726pub fn quote_identifier(name: &str) -> String {
727    if identifier_needs_quotes(name) {
728        relate_model::identifier::quote_identifier_always(name)
729    } else {
730        name.to_string()
731    }
732}
733
734/// Byte offset of the first byte of each 1-based line; O(source) once.
735/// The one spelling of the line table, shared by the parser's
736/// `token_byte_offset` and the statement normalizer (ADR-0503).
737pub(crate) fn line_starts_of(source: &str) -> Vec<usize> {
738    let mut starts = vec![0];
739    for (i, b) in source.bytes().enumerate() {
740        if b == b'\n' {
741            starts.push(i + 1);
742        }
743    }
744    starts
745}
746
747/// The byte offset of `tok`'s first byte in its source, given that
748/// source's [`line_starts_of`] table and its byte length: the lexer
749/// counts columns in bytes (`Lexer::advance` does `col += 1` per byte),
750/// so `line_start + col - 1` is exactly the token's byte offset — no
751/// per-token source rescan, and no char/byte-column mismatch after
752/// non-ASCII text. `None` when the position does not land inside the
753/// source — the one spelling of that half of the contract, so no caller
754/// re-checks it.
755pub(crate) fn token_start_byte(
756    tok: &Token<'_>,
757    line_starts: &[usize],
758    source_len: usize,
759) -> Option<usize> {
760    let line_idx = tok.line.checked_sub(1)?;
761    let col_bytes = tok.col.checked_sub(1)?;
762    let offset = line_starts.get(line_idx)? + col_bytes;
763    (offset <= source_len).then_some(offset)
764}
765
766#[cfg(test)]
767#[path = "token_tests.rs"]
768mod tests;