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