Skip to main content

relate_parser/
token.rs

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