Skip to main content

relate_parser/
lexer.rs

1use std::borrow::Cow;
2
3use crate::token::{lookup_keyword, Token, TokenType};
4use crate::unicode_identifier;
5
6mod ascii;
7mod number;
8mod string;
9// The interpolation pattern's escape resolution shares the lexer's one
10// `\uXXXX` window reader (ADR-0619's consolidation) and the string
11// grammar's one-character escape table, so those names — not the whole
12// `string` module — cross the sibling module boundary.
13pub(crate) use string::{
14    decode_escape_char, unicode_escape_window, unicode_surrogate_pair, UNICODE_ESCAPE_SPAN,
15};
16
17/// Parse-affecting preview options: the ADR-0371 preview gates that widen
18/// what the parser accepts (the lexer's token stream and the parser's own
19/// grammar), resolved by the caller (the front derives them from the
20/// store's `RELATE_PREVIEW` set). The default is every gate closed --
21/// the dialect floor. One struct so a speculative or nested parse inherits
22/// its caller's dialect by plain field copy; the flags are `Copy`, never
23/// re-derived per site.
24#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
25pub struct ParseOptions {
26    /// The `obfuscated-literals` gate: a run of exactly six `*` lexes as
27    /// one [`TokenType::ObfuscatedLiteral`] instead of six `Star` tokens.
28    pub obfuscated_literals: bool,
29    /// The `mixed-label-syntax` gate (Neo4j's
30    /// mixed-label-syntax extra semantic feature):
31    /// legacy colon-conjunction (`:A:B`), GQL label-expression symbols
32    /// (`|`, `&`, `!`, `%`) and the `IS` introducer may mix within one
33    /// clause and within one label expression (`(n:A|B:C)`,
34    /// `(n IS S:R)`), with `:` parsed as an `&`-level conjunction
35    /// operator. Off (the floor), every CIP-40/CIP-14 mixing rejection
36    /// keeps firing.
37    pub mixed_label_syntax: bool,
38    /// The `cypher-annotations` gate (CIP-281): `@` lexes as
39    /// [`TokenType::At`], the clause-level annotation introducer, instead of
40    /// the `unexpected character: @` error token.
41    pub cypher_annotations: bool,
42    /// The `path-construction` gate: a one-element `PATH [x]` reads as the
43    /// path constructor when no identifier spelled `path` appears in the
44    /// statement outside such a `PATH [` opener (ADR-0637). Off, it stays
45    /// the subscript it has always been.
46    pub path_construction: bool,
47}
48
49/// Tokenizes a Cypher query string into a list of tokens.
50///
51/// The tokens borrow `input` (ADR-0505): they stay valid exactly as long as
52/// the query text does.
53pub fn tokenize(input: &str) -> Vec<Token<'_>> {
54    tokenize_with_options(input, ParseOptions::default())
55}
56
57/// Tokenizes with explicit [`ParseOptions`]; [`tokenize`] is the same call
58/// with every gate closed.
59pub fn tokenize_with_options(input: &str, options: ParseOptions) -> Vec<Token<'_>> {
60    let mut lexer = Lexer::new(input, options);
61    lexer.tokenize();
62    lexer.tokens
63}
64
65/// What [`skip_comment`] found at a position in the input.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum CommentSkip {
68    /// No comment starts here.
69    NotComment,
70    /// A comment ended just before this byte position.
71    Skipped(usize),
72    /// A block comment opened without a closing `*/` — the lexer's error
73    /// case.
74    Unterminated,
75}
76
77/// The Cypher comment starting at `input[pos..]` — the one spelling of the
78/// comment rule, shared by the lexer and by callers that re-read a literal
79/// token's text through the same grammar.
80///
81/// A `//` line comment runs through (and includes) its terminating newline;
82/// a `/* */` block comment does not nest and ends at the first `*/`.
83pub fn skip_comment(input: &[u8], pos: usize) -> CommentSkip {
84    if input.get(pos) == Some(&b'/') {
85        if input.get(pos + 1) == Some(&b'/') {
86            let mut end = pos + 2;
87            while end < input.len() && input[end] != b'\n' {
88                end += 1;
89            }
90            return CommentSkip::Skipped((end + 1).min(input.len()));
91        }
92        if input.get(pos + 1) == Some(&b'*') {
93            let mut end = pos + 2;
94            while end < input.len() {
95                if input[end] == b'*' && input.get(end + 1) == Some(&b'/') {
96                    return CommentSkip::Skipped(end + 2);
97                }
98                end += 1;
99            }
100            return CommentSkip::Unterminated;
101        }
102    }
103    CommentSkip::NotComment
104}
105
106struct Lexer<'a> {
107    /// The input as `&str` — the borrowed-literal slice source (ADR-0505).
108    /// Slicing it costs one O(1) character-boundary check, where
109    /// `from_utf8` over the byte view would re-validate the whole token
110    /// text; an all-ASCII run classified by the fast path is valid by
111    /// construction and never re-validated.
112    text: &'a str,
113    /// `text` as bytes — the scanning view. One input, two immutable
114    /// borrowed views of the same data, created together in [`Lexer::new`].
115    input: &'a [u8],
116    pos: usize,
117    line: usize,
118    col: usize,
119    tokens: Vec<Token<'a>>,
120    options: ParseOptions,
121}
122
123/// One classified run of whitespace between tokens, in the shape the
124/// ASCII batch's `ascii::ws_run_summary` reports: the byte span, the
125/// newline count, and the bytes after the last newline (zero when there
126/// is none). A decoded non-ASCII character and a `\uXXXX` escape whose
127/// character is whitespace (ADR-0619) are one-character runs of the same
128/// shape — only a decoded `\n` counts as a newline (the ASCII batch
129/// consumes a literal one before the decoded path is reached) — so every
130/// spelling takes the same consume step, [`Lexer::advance_ws_span`].
131struct WhitespaceRun {
132    bytes: usize,
133    newlines: usize,
134    after_last_newline: usize,
135}
136
137impl<'a> Lexer<'a> {
138    fn new(input: &'a str, options: ParseOptions) -> Self {
139        Lexer {
140            text: input,
141            input: input.as_bytes(),
142            pos: 0,
143            line: 1,
144            col: 1,
145            tokens: Vec::new(),
146            options,
147        }
148    }
149
150    fn tokenize(&mut self) {
151        while self.pos < self.input.len() {
152            self.skip_whitespace();
153            if self.pos >= self.input.len() {
154                break;
155            }
156
157            let ch = self.peek();
158
159            let line = self.line;
160            let col = self.col;
161
162            match ch {
163                b'(' => {
164                    self.advance();
165                    self.emit(TokenType::LeftParen, "(", line, col);
166                }
167                b')' => {
168                    self.advance();
169                    self.emit(TokenType::RightParen, ")", line, col);
170                }
171                b'[' => {
172                    self.advance();
173                    self.emit(TokenType::LeftBracket, "[", line, col);
174                }
175                b']' => {
176                    self.advance();
177                    self.emit(TokenType::RightBracket, "]", line, col);
178                }
179                b'{' => {
180                    self.advance();
181                    self.emit(TokenType::LeftBrace, "{", line, col);
182                }
183                b'}' => {
184                    self.advance();
185                    self.emit(TokenType::RightBrace, "}", line, col);
186                }
187                b':' => {
188                    if self.peek_at(1) == Some(b':') {
189                        self.advance();
190                        self.advance();
191                        self.emit(TokenType::DoubleColon, "::", line, col);
192                    } else {
193                        self.advance();
194                        self.emit(TokenType::Colon, ":", line, col);
195                    }
196                }
197                b',' => {
198                    self.advance();
199                    self.emit(TokenType::Comma, ",", line, col);
200                }
201                b';' => {
202                    self.advance();
203                    self.emit(TokenType::Semicolon, ";", line, col);
204                }
205                b'@' if self.options.cypher_annotations => {
206                    self.advance();
207                    self.emit(TokenType::At, "@", line, col);
208                }
209                b'|' => {
210                    if self.peek_at(1) == Some(b'|') {
211                        self.advance();
212                        self.advance();
213                        self.emit(TokenType::DoublePipe, "||", line, col);
214                    } else {
215                        self.advance();
216                        self.emit(TokenType::Pipe, "|", line, col);
217                    }
218                }
219                b'*' => {
220                    // The obfuscated literal is the one gated spelling:
221                    // exactly six stars under the preview gate lexes as one
222                    // dummy literal; any other run (or the gate closed)
223                    // keeps the ordinary `*` tokens.
224                    if self.options.obfuscated_literals && self.star_run() == 6 {
225                        for _ in 0..6 {
226                            self.advance();
227                        }
228                        self.emit(TokenType::ObfuscatedLiteral, "******", line, col);
229                    } else {
230                        self.advance();
231                        self.emit(TokenType::Star, "*", line, col);
232                    }
233                }
234                b'+' => {
235                    self.advance();
236                    self.emit(TokenType::Plus, "+", line, col);
237                }
238                b'/' => {
239                    // The comment rule lives once in `skip_comment`.
240                    // `Unterminated` must not silently swallow the rest of
241                    // the input (which could hide trailing statements such
242                    // as `RETURN 1 /* DETACH DELETE n`).
243                    match skip_comment(self.input, self.pos) {
244                        CommentSkip::Skipped(end) => self.advance_by(end - self.pos),
245                        CommentSkip::Unterminated => {
246                            self.advance_by(self.input.len() - self.pos);
247                            self.emit(TokenType::Error, "unterminated block comment", line, col);
248                        }
249                        CommentSkip::NotComment => {
250                            self.advance();
251                            self.emit(TokenType::Slash, "/", line, col);
252                        }
253                    }
254                }
255                b'%' => {
256                    self.advance();
257                    self.emit(TokenType::Percent, "%", line, col);
258                }
259                b'^' => {
260                    self.advance();
261                    self.emit(TokenType::Caret, "^", line, col);
262                }
263                b'=' => {
264                    if self.peek_at(1) == Some(b'~') {
265                        self.advance();
266                        self.advance();
267                        self.emit(TokenType::RegexMatch, "=~", line, col);
268                    } else if self.peek_at(1) == Some(b'>') {
269                        self.advance();
270                        self.advance();
271                        self.emit(TokenType::FatArrow, "=>", line, col);
272                    } else {
273                        self.advance();
274                        self.emit(TokenType::Equals, "=", line, col);
275                    }
276                }
277                b'.' => {
278                    if self.peek_at(1) == Some(b'.') {
279                        self.advance();
280                        self.advance();
281                        self.emit(TokenType::DotDot, "..", line, col);
282                    } else if matches!(self.peek_at(1), Some(b'0'..=b'9')) {
283                        self.read_number(line, col);
284                    } else {
285                        self.advance();
286                        self.emit(TokenType::Dot, ".", line, col);
287                    }
288                }
289                b'-' => {
290                    if self.peek_at(1) == Some(b'>') {
291                        self.advance();
292                        self.advance();
293                        self.emit(TokenType::ArrowRight, "->", line, col);
294                    } else {
295                        self.advance();
296                        self.emit(TokenType::Dash, "-", line, col);
297                    }
298                }
299                b'<' => {
300                    if self.peek_at(1) == Some(b'-') {
301                        self.advance();
302                        self.advance();
303                        self.emit(TokenType::ArrowLeft, "<-", line, col);
304                    } else if self.peek_at(1) == Some(b'>') {
305                        self.advance();
306                        self.advance();
307                        self.emit(TokenType::NotEquals, "<>", line, col);
308                    } else if self.peek_at(1) == Some(b'=') {
309                        self.advance();
310                        self.advance();
311                        self.emit(TokenType::LessEqual, "<=", line, col);
312                    } else {
313                        self.advance();
314                        self.emit(TokenType::LessThan, "<", line, col);
315                    }
316                }
317                b'>' => {
318                    if self.peek_at(1) == Some(b'=') {
319                        self.advance();
320                        self.advance();
321                        self.emit(TokenType::GreaterEqual, ">=", line, col);
322                    } else {
323                        self.advance();
324                        self.emit(TokenType::GreaterThan, ">", line, col);
325                    }
326                }
327                b'$' => {
328                    self.advance();
329                    self.read_parameter(line, col);
330                }
331                b'!' => {
332                    self.advance();
333                    self.emit(TokenType::Bang, "!", line, col);
334                }
335                b'&' => {
336                    self.advance();
337                    self.emit(TokenType::Ampersand, "&", line, col);
338                }
339                b'\'' | b'"' => {
340                    self.read_string(line, col);
341                }
342                b'`' => {
343                    // The one canonical backtick scan (string.rs): it
344                    // returns the decoded name and owns the
345                    // unterminated-backtick error; this arm owns the token
346                    // type. An empty backtick-quoted name (` `` `) emits an
347                    // Identifier with an empty literal — the historical
348                    // behavior, unchanged here and pinned by
349                    // `test_empty_backtick_identifier_lexes_as_today` —
350                    // unlike the parameter path, whose empty literal is the
351                    // reserved `$(expr)` sentinel and therefore rejected.
352                    if let Some(name) = self.read_backtick_name(line, col) {
353                        self.emit(TokenType::Identifier, name, line, col);
354                    }
355                }
356                b'0'..=b'9' => {
357                    self.read_number(line, col);
358                }
359                // The remaining bytes open either an identifier or one
360                // invalid character; the decoded-character decision lives
361                // in `at_ident_start`, widened for the source-escape
362                // spelling (ADR-0619) by `at_widened_ident_start`, so
363                // `read_identifier` has exactly this one call site
364                // (ADR-0182). Parameters keep the plain predicate — that
365                // split is how the escape's rejection boundary
366                // (ADR-0619) is encoded in code.
367                _ if self.at_widened_ident_start() => {
368                    self.read_identifier(line, col);
369                }
370                _ => {
371                    // A decoded non-ASCII character that is not an identifier
372                    // start is ONE invalid Unicode character, not one mojibake
373                    // error per UTF-8 byte (LABS-188).
374                    self.read_invalid_char(line, col);
375                }
376            }
377        }
378    }
379
380    fn peek(&self) -> u8 {
381        if self.pos >= self.input.len() {
382            0
383        } else {
384            self.input[self.pos]
385        }
386    }
387
388    fn peek_at(&self, offset: usize) -> Option<u8> {
389        let p = self.pos + offset;
390        if p >= self.input.len() {
391            None
392        } else {
393            Some(self.input[p])
394        }
395    }
396
397    fn advance(&mut self) -> u8 {
398        if self.pos >= self.input.len() {
399            return 0;
400        }
401        let ch = self.input[self.pos];
402        self.pos += 1;
403        if ch == b'\n' {
404            self.line += 1;
405            self.col = 1;
406        } else {
407            self.col += 1;
408        }
409        ch
410    }
411
412    /// Decode the character at the cursor as `(char, byte_len)` without
413    /// consuming it; `None` only on malformed UTF-8. ASCII is decided on the
414    /// byte; a byte >= 0x80 decodes its full sequence (via the string
415    /// module's [`string::decode_char`]).
416    fn peek_char(&self) -> Option<(char, usize)> {
417        string::decode_char(&self.input[self.pos..])
418    }
419
420    /// Consume `len` bytes — the byte length [`Lexer::peek_char`] reported for
421    /// the character at the cursor — so a multi-byte character is never split.
422    fn advance_by(&mut self, len: usize) {
423        for _ in 0..len {
424            self.advance();
425        }
426    }
427
428    /// The input slice `[start, end)` as `&'a str` — the borrowed-literal
429    /// source of ADR-0505. Both bounds sit on character boundaries by
430    /// construction (token starts, and ends at an ASCII delimiter or a
431    /// decoded-character edge), and the input itself came from a `&str`,
432    /// so slicing it is an O(1) boundary check that panics on a broken
433    /// invariant — never a fallback, and never a re-validation of the
434    /// bytes between the bounds (interior bytes are valid UTF-8 because
435    /// the input is).
436    fn slice(&self, start: usize, end: usize) -> &'a str {
437        &self.text[start..end]
438    }
439
440    /// The eight bytes at the cursor as one little-endian `u64` word for
441    /// the `ascii` fast path, zero-padded past the end of the input. The
442    /// padding bytes classify as none of the ASCII classes, so an
443    /// overhanging word never claims bytes the input does not have.
444    fn load_word(&self) -> u64 {
445        let end = (self.pos + 8).min(self.input.len());
446        let mut buf = [0u8; 8];
447        buf[..end - self.pos].copy_from_slice(&self.input[self.pos..end]);
448        u64::from_le_bytes(buf)
449    }
450
451    /// Emit a token. `literal` follows the ADR-0505 rule: an input slice
452    /// (identifiers, numbers, parameters, escape-free strings), a
453    /// `&'static str` (punctuation, fixed error texts), or an owned `String`
454    /// (escape-decoded / synthesized text) — `Into<Cow>` takes each without
455    /// a hidden copy, so nothing here allocates on the borrowed paths.
456    fn emit(&mut self, ty: TokenType, literal: impl Into<Cow<'a, str>>, line: usize, col: usize) {
457        self.tokens.push(Token::new(ty, literal, line, col));
458    }
459
460    /// Emit a [`TokenType::Error`] token carrying a symbolic openCypher-TCK
461    /// error-*detail* name (see [`Token::detail`]). The parser propagates the
462    /// detail onto the raised `ParseError` so a malformed literal reports its
463    /// specific TCK detail (`InvalidNumberLiteral`, `InvalidUnicodeLiteral`)
464    /// instead of the generic `UnexpectedSyntax`. `literal` takes the same
465    /// borrowed/owned forms as [`Lexer::emit`]; the error path is the one
466    /// place owned text is expected (`format!`-built messages).
467    fn emit_error_detail(
468        &mut self,
469        literal: impl Into<Cow<'a, str>>,
470        line: usize,
471        col: usize,
472        detail: &'static str,
473    ) {
474        self.tokens
475            .push(Token::error_with_detail(literal, line, col, detail));
476    }
477
478    fn skip_whitespace(&mut self) {
479        while self.pos < self.input.len() {
480            // ASCII whitespace (CIP-88 adds vertical tab and form feed to
481            // the previous \t \n \r + space set; verified on 2026.09.0) is
482            // consumed eight bytes per classification step (`ascii`,
483            // ADR-0505), the batch settling line/column exactly as
484            // byte-at-a-time `advance` would.
485            let w = self.load_word();
486            let n = ascii::ws_prefix(w);
487            if n > 0 {
488                self.advance_ws_run(w, n);
489                continue;
490            }
491            // CIP-88: the GQL/Java Unicode whitespace set (Zs + Zl + Zp
492            // categories plus separators, i.e. Rust's char::is_whitespace)
493            // is also accepted between tokens — e.g. NBSP U+00A0. Verified
494            // against Neo4j 2026.09.0. A source-level `\uXXXX` escape
495            // whose character is whitespace (ADR-0619) — the reference
496            // server's own spelling for the separators its documentation
497            // cannot write as characters — is that whitespace too. The
498            // byte at the cursor is not ASCII whitespace, so only a
499            // non-ASCII character or an escape can still qualify; the
500            // one classification point decides both spellings, and the
501            // one consume step settles either.
502            if let Some(run) = self.peek_whitespace() {
503                self.advance_ws_span(run);
504                continue;
505            }
506            break;
507        }
508    }
509
510    /// The whitespace run at the cursor — a decoded non-ASCII character,
511    /// or a `\uXXXX` escape whose character is whitespace (ADR-0619) —
512    /// or `None` when the cursor opens no whitespace. The one
513    /// classification point for the character-at-a-time spellings: one
514    /// selection (the escape first, the raw character otherwise), one
515    /// decision. The ASCII run is classified in bulk by the `ascii` word
516    /// path before this is consulted, and reaches the same consume step.
517    ///
518    /// An escape's run spans its six source bytes and counts no newline,
519    /// whatever character it decoded to: `line` and `col` stay *source*
520    /// positions, so the byte offset `token_start_byte` derives from them
521    /// still indexes the source (ADR-0503).
522    fn peek_whitespace(&self) -> Option<WhitespaceRun> {
523        if let Some(c) = self.peek_source_escape() {
524            return c.is_whitespace().then_some(WhitespaceRun {
525                bytes: string::UNICODE_ESCAPE_SPAN,
526                newlines: 0,
527                after_last_newline: 0,
528            });
529        }
530        let (c, bytes) = self.peek_char()?;
531        c.is_whitespace().then_some(WhitespaceRun {
532            bytes,
533            newlines: usize::from(c == '\n'),
534            after_last_newline: 0,
535        })
536    }
537
538    /// A well-formed source-level `\uXXXX` escape at the cursor
539    /// (ADR-0619): backslash, `u`, four hex digits, a scalar value —
540    /// a surrogate or out-of-range value is not an escape and keeps
541    /// the historical `unexpected character: \` rejection. Returns the
542    /// decoded character without consuming anything; the spelling's
543    /// byte span is [`string::UNICODE_ESCAPE_SPAN`]. The window decode
544    /// is the one the string-literal escapes share
545    /// (`string::unicode_escape_value`); consulted only where the
546    /// escape widens acceptance (whitespace, identifier text) — every
547    /// other position rejects it, the boundary ADR-0619 records.
548    fn peek_source_escape(&self) -> Option<char> {
549        string::unicode_escape_value(self.input.get(self.pos..)?).and_then(char::from_u32)
550    }
551
552    /// Settle the cursor past one whitespace run: the line advances by
553    /// the run's newline count, the column by its byte span — the
554    /// position one [`Lexer::advance`] per source byte would leave, moved
555    /// in one step. A decoded `\uXXXX` escape is whitespace by its
556    /// character but still six source bytes on the line it is spelled on,
557    /// so it advances the column by six and never the line. The one
558    /// consume step for every spelling whitespace can take between
559    /// tokens; the ASCII batch and the decoded/escape path both end here.
560    fn advance_ws_span(&mut self, run: WhitespaceRun) {
561        self.line += run.newlines;
562        if run.newlines == 0 {
563            self.col += run.bytes;
564        } else {
565            // The column after the last newline is the run's bytes past
566            // it, +1.
567            self.col = run.after_last_newline + 1;
568        }
569        self.pos += run.bytes;
570    }
571
572    /// Consume the `n`-byte ASCII whitespace run `[0, n)` of word `w`'s
573    /// lanes through the one whitespace consume step,
574    /// [`Lexer::advance_ws_span`]. The `ascii` module hands back the
575    /// settled run summary; the per-lane bit layout never crosses the
576    /// module boundary.
577    fn advance_ws_run(&mut self, w: u64, n: usize) {
578        let (newlines, after_last_newline) = ascii::ws_run_summary(w, n);
579        self.advance_ws_span(WhitespaceRun {
580            bytes: n,
581            newlines,
582            after_last_newline,
583        });
584    }
585
586    /// The length of the run of consecutive `*` starting at the cursor.
587    /// The obfuscated-literal gate asks for exactly six.
588    fn star_run(&self) -> usize {
589        let mut n = 0usize;
590        while self.peek_at(n) == Some(b'*') {
591            n += 1;
592        }
593        n
594    }
595
596    /// The one cursor classification both identifier predicates share: an
597    /// ASCII byte decided from the class table with no decoding, or (only
598    /// for a byte >= 0x80) a decoded `char` asked of the hand-written
599    /// Unicode predicate (ADR-0182) — one decode-or-classify step, so the
600    /// two classes below can never diverge on how a character is read.
601    fn at_ident_class(&self, ascii: fn(u8) -> bool, unicode: fn(char) -> bool) -> bool {
602        let b = self.peek();
603        if b < 0x80 {
604            return ascii(b);
605        }
606        self.peek_char().is_some_and(|(c, _)| unicode(c))
607    }
608
609    /// True when the character at the cursor is an identifier start: an
610    /// ASCII `[A-Za-z_]` byte, decided from the class table with no
611    /// decoding, or a non-ASCII `char` accepted by the hand-written
612    /// Unicode predicate (ADR-0182).
613    fn at_ident_start(&self) -> bool {
614        self.at_ident_class(
615            ascii::ascii_ident_start,
616            unicode_identifier::is_identifier_start,
617        )
618    }
619
620    /// True when the character at the cursor continues an identifier: an
621    /// ASCII `[A-Za-z0-9_]` byte from the class table, or a non-ASCII
622    /// `char` accepted by the hand-written Unicode predicate's *part*
623    /// class (ADR-0182) — the ident-part image of
624    /// [`Lexer::at_ident_start`], a sibling predicate rather than a
625    /// widening of it. The one consumer is
626    /// [`Self::number_has_trailing_ident`], the number scanner's glue
627    /// policy.
628    fn at_ident_part(&self) -> bool {
629        self.at_ident_class(
630            ascii::ascii_ident_part,
631            unicode_identifier::is_identifier_part,
632        )
633    }
634
635    /// True when the cursor opens an identifier: a plain identifier-start
636    /// character ([`Lexer::at_ident_start`]), or a `\uXXXX` escape whose
637    /// character is one (ADR-0619) — the escape is a spelling of the
638    /// character, not a distinct token class. Deliberately a second
639    /// predicate rather than a widening of `at_ident_start`:
640    /// `read_parameter` keeps the plain form, so an escape cannot spell
641    /// a parameter name — ADR-0619's boundary, encoded at the call site.
642    fn at_widened_ident_start(&self) -> bool {
643        self.at_ident_start()
644            || self
645                .peek_source_escape()
646                .is_some_and(unicode_identifier::is_identifier_start)
647    }
648
649    /// Consume the remaining identifier-part run from `start` and return it
650    /// as the run's literal — the one canonical consume-and-derive for
651    /// identifier runs, consulted by `emit_malformed_number`,
652    /// `read_parameter`'s pass-through, and its part-only-start error block
653    /// (which differ only in message and detail tag). The run is a slice of
654    /// the input (borrowed, ADR-0505) — the decoded text never differs from
655    /// the raw bytes, so [`Lexer::slice`]'s O(1) boundary-checked slice is
656    /// the literal for ASCII and non-ASCII runs alike, and the one place
657    /// the text view is indexed.
658    ///
659    /// Pure-ASCII runs are consumed eight bytes per classification step
660    /// (`ascii`, ADR-0505); the first byte >= 0x80 hands the scan back to
661    /// the decoded-character path, which stays authoritative for the whole
662    /// non-ASCII stretch (ADR-0182).
663    fn take_ident_run(&mut self, start: usize) -> &'a str {
664        loop {
665            let n = ascii::ident_part_prefix(self.load_word());
666            if n > 0 {
667                // No identifier-part byte is a newline, so the batch
668                // advance only moves the column.
669                self.pos += n;
670                self.col += n;
671            }
672            if n == 8 {
673                continue;
674            }
675            // The byte at the cursor is not an ASCII identifier part: the
676            // run's terminator, or a non-ASCII character — the decoded
677            // path decides which, consuming a whole character if it
678            // continues the run.
679            if !self.take_ident_part() {
680                break;
681            }
682        }
683        self.slice(start, self.pos)
684    }
685
686    /// If the character at the current position is an identifier part,
687    /// consume it — all of its UTF-8 bytes — and return true. The character
688    /// is decoded through [`Lexer::peek_char`] (ASCII on the byte; a byte at
689    /// or above 0x80 as its full sequence) and classified with the
690    /// hand-written Unicode predicate, so a multi-byte character is never
691    /// split (ADR-0182).
692    fn take_ident_part(&mut self) -> bool {
693        let Some((c, len)) = self.peek_char() else {
694            return false;
695        };
696        if !unicode_identifier::is_identifier_part(c) {
697            return false;
698        }
699        self.advance_by(len);
700        true
701    }
702
703    /// Consume and report one character that opens neither a token nor an
704    /// identifier: a decoded non-ASCII character is ONE
705    /// `InvalidUnicodeCharacter` error token covering all of its UTF-8 bytes
706    /// (LABS-188); an ASCII byte keeps the historical untagged
707    /// `unexpected character:` error.
708    fn read_invalid_char(&mut self, line: usize, col: usize) {
709        if let Some((c, len)) = self.peek_char() {
710            if !c.is_ascii() {
711                self.advance_by(len);
712                self.emit_error_detail(
713                    format!("invalid unicode character: {c}"),
714                    line,
715                    col,
716                    "InvalidUnicodeCharacter",
717                );
718                return;
719            }
720        }
721        // An ASCII byte and a malformed byte take the same path: one byte
722        // consumed, one untagged `unexpected character:` token. For ASCII the
723        // decoded `char` and `char::from(byte)` are the same thing; malformed
724        // UTF-8 cannot occur in `&str` input — every cursor sits on a complete
725        // sequence — but keep the historical byte-wise report for the
726        // defensive branch.
727        let byte = self.advance();
728        // The one formatted (owned) form of the untagged ASCII error text.
729        self.emit(
730            TokenType::Error,
731            format!("unexpected character: {}", char::from(byte)),
732            line,
733            col,
734        );
735    }
736
737    /// The identifier text from the cursor: the escape-free run,
738    /// borrowed whole (ADR-0505) — or, when the run carries a
739    /// source-level `\uXXXX` escape (ADR-0619), owned text synthesized
740    /// from the borrowed prefix, each decoded character, and the
741    /// escape-free run that follows it. `take_ident_run` stops at the
742    /// backslash, so the diversion begins with the borrowed prefix
743    /// already in hand. An escape continues the identifier exactly when
744    /// its character is an identifier part — the predicate
745    /// [`Lexer::take_ident_part`] applies to a decoded character,
746    /// stated once, at the loop head.
747    fn take_ident_text(&mut self) -> Cow<'a, str> {
748        let borrowed = self.take_ident_run(self.pos);
749        let mut owned: Option<String> = None;
750        while let Some(c) = self.peek_source_escape() {
751            if !unicode_identifier::is_identifier_part(c) {
752                break;
753            }
754            let text = owned.get_or_insert_with(|| borrowed.to_string());
755            text.push(c);
756            self.advance_by(string::UNICODE_ESCAPE_SPAN);
757            text.push_str(self.take_ident_run(self.pos));
758        }
759        match owned {
760            Some(text) => Cow::Owned(text),
761            None => Cow::Borrowed(borrowed),
762        }
763    }
764
765    fn read_identifier(&mut self, line: usize, col: usize) {
766        let literal = self.take_ident_text();
767        // CIP-261: a lone `s`/`S` immediately followed by a quote starts an
768        // interpolated string literal (`s'...'` / `s"..."`). Anything else
769        // stays a normal identifier/keyword.
770        if literal.len() == 1
771            && literal.as_bytes()[0].eq_ignore_ascii_case(&b's')
772            && matches!(self.peek(), b'\'' | b'"')
773        {
774            self.read_interpolation(line, col);
775            return;
776        }
777        let tok_type = lookup_keyword(&literal);
778        self.emit(tok_type, literal, line, col);
779    }
780
781    fn read_parameter(&mut self, line: usize, col: usize) {
782        // A parameter's first character is an identifier start or an ASCII
783        // digit — ADR-0182's Consequences prose, confirmed against the live
784        // Neo4j reference (LABS-209): a part-only character such as `€` is
785        // rejected with the reference's error shape; an arbitrary name (spaces,
786        // part-only characters) is spelled through the backtick form
787        // $`name`, offered through the shared backtick scan below (LABS-1602
788        // delivering LABS-209's acceptance criteria).
789        // `(` glued to the `$` is the dynamic-expression opener (`$(expr)`,
790        // e.g. `n IS LABELED $('A')`): it lexes as an intentionally empty
791        // Parameter token whose expansion the parser owns. Glued only —
792        // whitespace between the sigil and the `(` is not this opener (the
793        // empty-literal sentinel keeps exactly the shape it had before
794        // LABS-1612's whitespace skip existed). The `$all(...)`/`$any(...)`
795        // quantifier openers are names followed by `(` — they follow the
796        // name rule, whitespace-transparent like any parameter name
797        // (pinned in the label-expression quantifier table).
798        if self.peek() == b'(' {
799            self.emit(TokenType::Parameter, "", line, col);
800            return;
801        }
802        // Whitespace may sit between the `$` and the name (LABS-1612): a
803        // space, tab or newline — `$ p2` names `p2` — so the whitespace
804        // skip runs before the start rules; whatever follows it still faces
805        // them (`$ €`, or whitespace to end of input, keeps the rejection).
806        self.skip_whitespace();
807        if self.peek() == b'`' {
808            // The backtick form: the one canonical backtick scan, emitted
809            // as a Parameter token with the unescaped name (a doubled
810            // backtick collapses to one), so a name that is not
811            // identifier-shaped at all — $`p 1` — is one Parameter token.
812            // An empty backtick-quoted name ($``) is rejected: the empty
813            // Parameter literal is the reserved sentinel of the `$(expr)`
814            // dynamic opener, never a parameter's name.
815            if let Some(name) = self.read_backtick_name(line, col) {
816                if name.is_empty() {
817                    self.reject_parameter_name("", line, col);
818                } else {
819                    self.emit(TokenType::Parameter, name, line, col);
820                }
821            }
822            return;
823        }
824        let start_ok =
825            self.at_ident_start() || self.peek_char().is_some_and(|(c, _)| c.is_ascii_digit());
826        // One consume-and-derive for both outcomes: the accepted name and
827        // the rejected run are the same identifier-part run from the same
828        // position; the guard above only classifies its first character.
829        let start = self.pos;
830        let run = self.take_ident_run(start);
831        if !start_ok {
832            self.reject_parameter_name(run, line, col);
833            return;
834        }
835        self.emit(TokenType::Parameter, run, line, col);
836    }
837
838    /// The one InvalidParameterName rejection (LABS-209's reference error
839    /// shape): the offending run — empty for a bare `$` or an empty
840    /// backtick-quoted name — becomes one error token, not a cascade (the
841    /// `emit_malformed_number` shape). The message's two spellings (the
842    /// bare-`$` and the run-naming one) and the detail code live here, so
843    /// every rejection path in `read_parameter` emits the same shape.
844    fn reject_parameter_name(&mut self, offending: &str, line: usize, col: usize) {
845        const EXPECTED: &str = "expected an identifier or an integer value";
846        let literal = if offending.is_empty() {
847            format!("Invalid input after '$': {EXPECTED}")
848        } else {
849            format!("Invalid input '{offending}': {EXPECTED}")
850        };
851        self.emit_error_detail(Cow::Owned(literal), line, col, "InvalidParameterName");
852    }
853}
854
855#[cfg(test)]
856mod tests;