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