Skip to main content

mago_syntax/lexer/
mod.rs

1#![allow(clippy::unreachable)]
2
3use core::hint::unreachable_unchecked;
4
5use std::collections::VecDeque;
6use std::fmt::Debug;
7
8use memchr::memchr2;
9use memchr::memmem;
10
11/// Lookup table for single-character tokens that are ALWAYS single-char
12/// (i.e., they can never be part of a multi-character token).
13/// Maps byte -> Option<TokenKind>
14const SIMPLE_TOKEN_TABLE: [Option<TokenKind>; 256] = {
15    let mut table: [Option<TokenKind>; 256] = [None; 256];
16    table[b';' as usize] = Some(TokenKind::Semicolon);
17    table[b',' as usize] = Some(TokenKind::Comma);
18    table[b')' as usize] = Some(TokenKind::RightParenthesis);
19    table[b'[' as usize] = Some(TokenKind::LeftBracket);
20    table[b']' as usize] = Some(TokenKind::RightBracket);
21    table[b'{' as usize] = Some(TokenKind::LeftBrace);
22    table[b'}' as usize] = Some(TokenKind::RightBrace);
23    table[b'~' as usize] = Some(TokenKind::Tilde);
24    table[b'@' as usize] = Some(TokenKind::At);
25    table
26};
27
28/// Lookup table for identifier start characters (a-z, A-Z, _, 0x80-0xFF)
29const IDENT_START_TABLE: [bool; 256] = {
30    let mut table = [false; 256];
31    let mut i = 0usize;
32    while i < 256 {
33        table[i] = matches!(i as u8, b'a'..=b'z' | b'A'..=b'Z' | b'_' | 0x80..=0xFF);
34        i += 1;
35    }
36
37    table
38};
39
40use mago_database::file::FileId;
41use mago_database::file::HasFileId;
42use mago_span::Position;
43use mago_syntax_core::float_exponent;
44use mago_syntax_core::float_separator;
45use mago_syntax_core::input::Input;
46use mago_syntax_core::number_sign;
47use mago_syntax_core::start_of_binary_number;
48use mago_syntax_core::start_of_float_number;
49use mago_syntax_core::start_of_hexadecimal_number;
50use mago_syntax_core::start_of_identifier;
51use mago_syntax_core::start_of_number;
52use mago_syntax_core::start_of_octal_number;
53use mago_syntax_core::start_of_octal_or_float_number;
54use mago_syntax_core::utils::is_part_of_identifier;
55use mago_syntax_core::utils::is_start_of_identifier;
56use mago_syntax_core::utils::read_digits_of_base;
57
58use crate::error::SyntaxError;
59use crate::lexer::internal::mode::HaltStage;
60use crate::lexer::internal::mode::Interpolation;
61use crate::lexer::internal::mode::LexerMode;
62use crate::lexer::internal::utils::NumberKind;
63use crate::settings::LexerSettings;
64use crate::token::DocumentKind;
65use crate::token::Token;
66use crate::token::TokenKind;
67
68mod internal;
69
70/// The `Lexer` struct is responsible for tokenizing input source code into discrete tokens
71/// based on PHP language syntax. It is designed to work with PHP code from version 7.0 up to 8.4.
72///
73/// The lexer reads through the provided input and processes it accordingly.
74///
75/// It identifies PHP-specific tokens, including operators, keywords, comments, strings, and other syntax elements,
76/// and produces a sequence of [`Token`] objects that are used in further stages of compilation or interpretation.
77///
78/// The lexer is designed to be used in a streaming fashion, where it reads the input source code in chunks
79/// and produces tokens incrementally. This allows for efficient processing of large source files and
80/// minimizes memory usage.
81#[derive(Debug)]
82pub struct Lexer<'input> {
83    input: Input<'input>,
84    settings: LexerSettings,
85    mode: LexerMode<'input>,
86    interpolating: bool,
87    brace_interpolating: bool,
88    var_offset_depth: u32,
89    expect_string_varname: bool,
90    interpolation_depth: u16,
91    /// Buffer for tokens during string interpolation.
92    buffer: VecDeque<Token<'input>>,
93}
94
95impl<'input> Lexer<'input> {
96    /// Nested interpolations recurse through `advance`; keep enough stack headroom for debug builds.
97    const MAX_INTERPOLATION_DEPTH: u16 = 64;
98
99    /// Creates a new `Lexer` instance.
100    ///
101    /// # Parameters
102    ///
103    /// - `input`: The input source code to tokenize.
104    /// - `settings`: The lexer settings.
105    ///
106    /// # Returns
107    ///
108    /// A new `Lexer` instance that reads from the provided byte slice.
109    #[must_use]
110    pub fn new(input: Input<'input>, settings: LexerSettings) -> Lexer<'input> {
111        Lexer {
112            input,
113            settings,
114            mode: LexerMode::Inline,
115            interpolating: false,
116            brace_interpolating: false,
117            var_offset_depth: 0,
118            expect_string_varname: false,
119            interpolation_depth: 0,
120            buffer: VecDeque::new(),
121        }
122    }
123
124    /// Creates a new `Lexer` instance for parsing a script block.
125    ///
126    /// # Parameters
127    ///
128    /// - `input`: The input source code to tokenize.
129    /// - `settings`: The lexer settings.
130    ///
131    /// # Returns
132    ///
133    /// A new `Lexer` instance that reads from the provided byte slice.
134    #[must_use]
135    pub fn scripting(input: Input<'input>, settings: LexerSettings) -> Lexer<'input> {
136        Lexer {
137            input,
138            settings,
139            mode: LexerMode::Script,
140            interpolating: false,
141            brace_interpolating: false,
142            var_offset_depth: 0,
143            expect_string_varname: false,
144            interpolation_depth: 0,
145            buffer: VecDeque::new(),
146        }
147    }
148
149    /// Check if the lexer has reached the end of the input.
150    ///
151    /// If this method returns `true`, the lexer will not produce any more tokens.
152    #[must_use]
153    pub fn has_reached_eof(&self) -> bool {
154        self.input.has_reached_eof()
155    }
156
157    /// Get the current position of the lexer in the input source code.
158    #[inline]
159    #[must_use]
160    pub const fn current_position(&self) -> Position {
161        self.input.current_position()
162    }
163
164    /// Tokenizes the next input from the source code.
165    ///
166    /// This method reads from the input and produces the next [`Token`] based on the current [`LexerMode`].
167    /// It handles various lexical elements such as inline text, script code, strings with interpolation,
168    /// comments, and different PHP-specific constructs.
169    ///
170    /// # Returns
171    ///
172    /// - `Some(Ok(Token))` if a token was successfully parsed.
173    /// - `Some(Err(SyntaxError))` if a syntax error occurred while parsing the next token.
174    /// - `None` if the end of the input has been reached.
175    ///
176    /// # Notes
177    ///
178    /// - It efficiently handles tokenization by consuming input based on patterns specific to PHP syntax.
179    /// - The lexer supports complex features like string interpolation and different numeric formats.
180    ///
181    /// # Errors
182    ///
183    /// Returns `Some(Err(SyntaxError))` in cases such as:
184    ///
185    /// - Unrecognized tokens that do not match any known PHP syntax.
186    /// - Unexpected tokens in a given context, such as an unexpected end of string.
187    ///
188    /// # Panics
189    ///
190    /// This method should not panic under normal operation. If it does, it indicates a bug in the lexer implementation.
191    ///
192    /// # See Also
193    ///
194    /// - [`Token`]: Represents a lexical token with its kind, value, and span.
195    /// - [`SyntaxError`]: Represents errors that can occur during lexing.
196    #[inline]
197    pub fn advance(&mut self) -> Option<Result<Token<'input>, SyntaxError>> {
198        // Check if there are buffered tokens from string interpolation.
199        if !self.interpolating
200            && let Some(token) = self.buffer.pop_front()
201        {
202            return Some(Ok(token));
203        }
204
205        if self.input.has_reached_eof() {
206            return None;
207        }
208
209        match self.mode {
210            LexerMode::Inline => {
211                let start = self.input.current_position();
212                let offset = self.input.current_offset();
213
214                // Shebang is only valid at the absolute start of the file (offset 0).
215                if offset == 0
216                    && self.input.len() >= 2
217                    // SAFETY: `self.input.len() >= 2` was just checked, so indices 0 and 1 are in bounds.
218                    && unsafe { *self.input.read_at_unchecked(0) } == b'#'
219                    // SAFETY: same as above.
220                    && unsafe { *self.input.read_at_unchecked(1) } == b'!'
221                {
222                    let buffer = self.input.consume_through(b'\n');
223                    let end = self.input.current_position();
224
225                    return Some(Ok(self.token(TokenKind::InlineShebang, buffer, start, end)));
226                }
227
228                // Get the remaining bytes to scan.
229                let bytes = self.input.read_remaining();
230
231                if self.settings.enable_short_tags {
232                    if let Some(pos) = memchr::memmem::find(bytes, b"<?") {
233                        if pos > 0 {
234                            let buffer = self.input.consume(pos);
235                            let end = self.input.current_position();
236
237                            return Some(Ok(self.token(TokenKind::InlineText, buffer, start, end)));
238                        }
239
240                        if self.input.is_at(b"<?php", true) {
241                            let buffer = self.input.consume(5);
242                            self.mode = LexerMode::Script;
243                            return Some(Ok(self.token(
244                                TokenKind::OpenTag,
245                                buffer,
246                                start,
247                                self.input.current_position(),
248                            )));
249                        }
250
251                        if self.input.is_at(b"<?=", false) {
252                            let buffer = self.input.consume(3);
253                            self.mode = LexerMode::Script;
254                            return Some(Ok(self.token(
255                                TokenKind::EchoTag,
256                                buffer,
257                                start,
258                                self.input.current_position(),
259                            )));
260                        }
261
262                        let buffer = self.input.consume(2);
263                        self.mode = LexerMode::Script;
264                        return Some(Ok(self.token(
265                            TokenKind::ShortOpenTag,
266                            buffer,
267                            start,
268                            self.input.current_position(),
269                        )));
270                    }
271                } else {
272                    let iter = memchr::memmem::find_iter(bytes, b"<?");
273
274                    for pos in iter {
275                        // SAFETY: `pos` is guaranteed to be within `bytes` by `find_iter`.
276                        let candidate = unsafe { bytes.get_unchecked(pos..) };
277
278                        if candidate.len() >= 5
279                            // SAFETY: `candidate.len() >= 5` was just checked, so indices 2, 3, 4 are in bounds.
280                            && (unsafe { *candidate.get_unchecked(2) } | 0x20) == b'p'
281                            // SAFETY: same as above.
282                            && (unsafe { *candidate.get_unchecked(3) } | 0x20) == b'h'
283                            // SAFETY: same as above.
284                            && (unsafe { *candidate.get_unchecked(4) } | 0x20) == b'p'
285                        {
286                            if pos > 0 {
287                                let buffer = self.input.consume(pos);
288                                let end = self.input.current_position();
289                                return Some(Ok(self.token(TokenKind::InlineText, buffer, start, end)));
290                            }
291
292                            let buffer = self.input.consume(5);
293                            self.mode = LexerMode::Script;
294                            return Some(Ok(self.token(
295                                TokenKind::OpenTag,
296                                buffer,
297                                start,
298                                self.input.current_position(),
299                            )));
300                        }
301
302                        // SAFETY: index 2 is in bounds because the right-hand side is only evaluated when
303                        // `candidate.len() >= 3` holds.
304                        if candidate.len() >= 3 && unsafe { *candidate.get_unchecked(2) } == b'=' {
305                            if pos > 0 {
306                                let buffer = self.input.consume(pos);
307                                let end = self.input.current_position();
308                                return Some(Ok(self.token(TokenKind::InlineText, buffer, start, end)));
309                            }
310
311                            let buffer = self.input.consume(3);
312                            self.mode = LexerMode::Script;
313                            return Some(Ok(self.token(
314                                TokenKind::EchoTag,
315                                buffer,
316                                start,
317                                self.input.current_position(),
318                            )));
319                        }
320                    }
321                }
322
323                if self.input.has_reached_eof() {
324                    return None;
325                }
326
327                let buffer = self.input.consume_remaining();
328                let end = self.input.current_position();
329                Some(Ok(self.token(TokenKind::InlineText, buffer, start, end)))
330            }
331            LexerMode::Script => {
332                let start = self.input.current_position();
333
334                if self.expect_string_varname {
335                    self.expect_string_varname = false;
336                    let (length, _) = self.input.scan_identifier(0);
337                    let buffer = self.input.consume(length);
338                    let end = self.input.current_position();
339
340                    return Some(Ok(self.token(TokenKind::StringVariableName, buffer, start, end)));
341                }
342
343                let whitespaces = self.input.consume_whitespaces();
344                if !whitespaces.is_empty() {
345                    return Some(Ok(self.token(
346                        TokenKind::Whitespace,
347                        whitespaces,
348                        start,
349                        self.input.current_position(),
350                    )));
351                }
352
353                let Some(&first_byte) = self.input.read(1).first() else {
354                    // SAFETY: we check for EOF before entering scripting section,
355                    unsafe { unreachable_unchecked() }
356                };
357
358                if let Some(kind) = SIMPLE_TOKEN_TABLE[first_byte as usize] {
359                    let buffer = self.input.consume(1);
360                    let end = self.input.current_position();
361                    return Some(Ok(self.token(kind, buffer, start, end)));
362                }
363
364                if self.var_offset_depth > 0 && IDENT_START_TABLE[first_byte as usize] {
365                    let (length, _) = self.input.scan_identifier(0);
366                    let buffer = self.input.consume(length);
367                    let end = self.input.current_position();
368                    return Some(Ok(self.token(TokenKind::OffsetString, buffer, start, end)));
369                }
370
371                if IDENT_START_TABLE[first_byte as usize] {
372                    let is_binary_string_prefix = !self.interpolating
373                        && matches!(first_byte, b'b' | b'B')
374                        && matches!(self.input.read(4), [_, b'\'' | b'"', ..] | [_, b'<', b'<', b'<']);
375
376                    if !is_binary_string_prefix {
377                        let (token_kind, len) = self.scan_identifier_or_keyword_info();
378
379                        if token_kind == TokenKind::HaltCompiler {
380                            self.mode = LexerMode::Halt(HaltStage::LookingForLeftParenthesis);
381                        }
382
383                        let buffer = self.input.consume(len);
384                        let end = self.input.current_position();
385                        return Some(Ok(self.token(token_kind, buffer, start, end)));
386                    }
387
388                    // Fall through to handle b-prefix strings in the match block below
389                }
390
391                if first_byte == b'$'
392                    && let Some(&next) = self.input.read(2).get(1)
393                    && IDENT_START_TABLE[next as usize]
394                {
395                    let (ident_len, _) = self.input.scan_identifier(1);
396                    let buffer = self.input.consume(1 + ident_len);
397                    let end = self.input.current_position();
398                    return Some(Ok(self.token(TokenKind::Variable, buffer, start, end)));
399                }
400
401                let mut document_label: &[u8] = &[];
402
403                let (token_kind, len) = match self.input.read(3) {
404                    [b'!', b'=', b'='] => (TokenKind::BangEqualEqual, 3),
405                    [b'?', b'?', b'='] => (TokenKind::QuestionQuestionEqual, 3),
406                    [b'?', b'-', b'>'] => (TokenKind::QuestionMinusGreaterThan, 3),
407                    [b'=', b'=', b'='] => (TokenKind::EqualEqualEqual, 3),
408                    [b'.', b'.', b'.'] => (TokenKind::DotDotDot, 3),
409                    [b'<', b'=', b'>'] => (TokenKind::LessThanEqualGreaterThan, 3),
410                    [b'<', b'<', b'='] => (TokenKind::LeftShiftEqual, 3),
411                    [b'>', b'>', b'='] => (TokenKind::RightShiftEqual, 3),
412                    [b'*', b'*', b'='] => (TokenKind::AsteriskAsteriskEqual, 3),
413                    [b'<', b'<', b'<'] if matches_start_of_heredoc_document(&self.input, 0) => {
414                        let (length, whitespaces, label_length) = read_start_of_heredoc_document(&self.input, false, 0);
415
416                        document_label = self.input.peek(3 + whitespaces, label_length);
417
418                        (TokenKind::DocumentStart(DocumentKind::Heredoc), length)
419                    }
420                    [b'<', b'<', b'<'] if matches_start_of_double_quote_heredoc_document(&self.input, 0) => {
421                        let (length, whitespaces, label_length) = read_start_of_heredoc_document(&self.input, true, 0);
422
423                        document_label = self.input.peek(4 + whitespaces, label_length);
424
425                        (TokenKind::DocumentStart(DocumentKind::Heredoc), length)
426                    }
427                    [b'<', b'<', b'<'] if matches_start_of_nowdoc_document(&self.input, 0) => {
428                        let (length, whitespaces, label_length) = read_start_of_nowdoc_document(&self.input, 0);
429
430                        document_label = self.input.peek(4 + whitespaces, label_length);
431
432                        (TokenKind::DocumentStart(DocumentKind::Nowdoc), length)
433                    }
434                    [b'!', b'=', ..] => (TokenKind::BangEqual, 2),
435                    [b'&', b'&', ..] => (TokenKind::AmpersandAmpersand, 2),
436                    [b'&', b'=', ..] => (TokenKind::AmpersandEqual, 2),
437                    [b'.', b'=', ..] => (TokenKind::DotEqual, 2),
438                    [b'?', b'?', ..] => (TokenKind::QuestionQuestion, 2),
439                    [b'?', b'>', ..] => (TokenKind::CloseTag, 2),
440                    [b'=', b'>', ..] => (TokenKind::EqualGreaterThan, 2),
441                    [b'=', b'=', ..] => (TokenKind::EqualEqual, 2),
442                    [b'+', b'+', ..] => (TokenKind::PlusPlus, 2),
443                    [b'+', b'=', ..] => (TokenKind::PlusEqual, 2),
444                    [b'%', b'=', ..] => (TokenKind::PercentEqual, 2),
445                    [b'-', b'-', ..] => (TokenKind::MinusMinus, 2),
446                    [b'-', b'>', ..] => (TokenKind::MinusGreaterThan, 2),
447                    [b'-', b'=', ..] => (TokenKind::MinusEqual, 2),
448                    [b'<', b'<', ..] => (TokenKind::LeftShift, 2),
449                    [b'<', b'=', ..] => (TokenKind::LessThanEqual, 2),
450                    [b'<', b'>', ..] => (TokenKind::LessThanGreaterThan, 2),
451                    [b'>', b'>', ..] => (TokenKind::RightShift, 2),
452                    [b'>', b'=', ..] => (TokenKind::GreaterThanEqual, 2),
453                    [b':', b':', ..] => (TokenKind::ColonColon, 2),
454                    [b'#', b'[', ..] => (TokenKind::HashLeftBracket, 2),
455                    [b'|', b'=', ..] => (TokenKind::PipeEqual, 2),
456                    [b'|', b'|', ..] => (TokenKind::PipePipe, 2),
457                    [b'/', b'=', ..] => (TokenKind::SlashEqual, 2),
458                    [b'^', b'=', ..] => (TokenKind::CaretEqual, 2),
459                    [b'*', b'*', ..] => (TokenKind::AsteriskAsterisk, 2),
460                    [b'*', b'=', ..] => (TokenKind::AsteriskEqual, 2),
461                    [b'|', b'>', ..] => (TokenKind::PipeGreaterThan, 2),
462                    [b'/', b'/', ..] => {
463                        let remaining = self.input.peek(2, self.input.len() - self.input.current_offset());
464                        let comment_len = scan_single_line_comment(remaining);
465                        (TokenKind::SingleLineComment, 2 + comment_len)
466                    }
467                    [b'/', b'*', asterisk] => {
468                        let remaining = self.input.peek(2, self.input.len() - self.input.current_offset());
469                        match scan_multi_line_comment(remaining) {
470                            Some(len) => {
471                                let is_docblock = asterisk == &b'*' && len > 2;
472                                if is_docblock {
473                                    (TokenKind::DocBlockComment, len + 2)
474                                } else {
475                                    (TokenKind::MultiLineComment, len + 2)
476                                }
477                            }
478                            None => {
479                                self.input.consume(remaining.len() + 2);
480                                return Some(Err(SyntaxError::UnexpectedEndOfFile(
481                                    self.file_id(),
482                                    self.input.current_position(),
483                                )));
484                            }
485                        }
486                    }
487                    [b'\\', start_of_identifier!(), ..] => {
488                        let mut length = 1;
489                        loop {
490                            let (ident_len, ends_with_ns) = self.input.scan_identifier(length);
491                            length += ident_len;
492                            if ends_with_ns {
493                                length += 1; // Include the backslash
494                            } else {
495                                break;
496                            }
497                        }
498
499                        (TokenKind::FullyQualifiedIdentifier, length)
500                    }
501                    [b'$', b'{', ..] => (TokenKind::DollarLeftBrace, 2),
502                    [b'$', ..] => (TokenKind::Dollar, 1),
503                    [b'!', ..] => (TokenKind::Bang, 1),
504                    [b'&', ..] => (TokenKind::Ampersand, 1),
505                    [b'?', ..] => (TokenKind::Question, 1),
506                    [b'=', ..] => (TokenKind::Equal, 1),
507                    [b'`', ..] => (TokenKind::Backtick, 1),
508                    [b'+', ..] => (TokenKind::Plus, 1),
509                    [b'%', ..] => (TokenKind::Percent, 1),
510                    [b'-', ..] => (TokenKind::Minus, 1),
511                    [b'<', ..] => (TokenKind::LessThan, 1),
512                    [b'>', ..] => (TokenKind::GreaterThan, 1),
513                    [b':', ..] => (TokenKind::Colon, 1),
514                    [b'|', ..] => (TokenKind::Pipe, 1),
515                    [b'^', ..] => (TokenKind::Caret, 1),
516                    [b'*', ..] => (TokenKind::Asterisk, 1),
517                    [b'/', ..] => (TokenKind::Slash, 1),
518                    [b'b' | b'B', b'\'', ..] => read_literal_string(&self.input, b'\'', 1),
519                    [b'b' | b'B', b'"', ..] => {
520                        read_literal_double_quote_string(&self.input, 1).unwrap_or((TokenKind::DoubleQuote, 2))
521                    }
522                    [b'b' | b'B', b'<', b'<']
523                        if self.input.read(4).len() == 4
524                            && self.input.read(4)[3] == b'<'
525                            && matches_start_of_heredoc_document(&self.input, 1) =>
526                    {
527                        let (length, whitespaces, label_length) = read_start_of_heredoc_document(&self.input, false, 1);
528
529                        document_label = self.input.peek(4 + whitespaces, label_length);
530
531                        (TokenKind::DocumentStart(DocumentKind::Heredoc), length)
532                    }
533                    [b'b' | b'B', b'<', b'<']
534                        if self.input.read(4).len() == 4
535                            && self.input.read(4)[3] == b'<'
536                            && matches_start_of_double_quote_heredoc_document(&self.input, 1) =>
537                    {
538                        let (length, whitespaces, label_length) = read_start_of_heredoc_document(&self.input, true, 1);
539
540                        document_label = self.input.peek(5 + whitespaces, label_length);
541
542                        (TokenKind::DocumentStart(DocumentKind::Heredoc), length)
543                    }
544                    [b'b' | b'B', b'<', b'<']
545                        if self.input.read(4).len() == 4
546                            && self.input.read(4)[3] == b'<'
547                            && matches_start_of_nowdoc_document(&self.input, 1) =>
548                    {
549                        let (length, whitespaces, label_length) = read_start_of_nowdoc_document(&self.input, 1);
550
551                        document_label = self.input.peek(5 + whitespaces, label_length);
552
553                        (TokenKind::DocumentStart(DocumentKind::Nowdoc), length)
554                    }
555                    // Regular string literals
556                    [quote @ b'\'', ..] => read_literal_string(&self.input, *quote, 0),
557                    [b'"', ..] => {
558                        read_literal_double_quote_string(&self.input, 0).unwrap_or((TokenKind::DoubleQuote, 1))
559                    }
560                    [b'(', ..] => 'parenthesis: {
561                        let mut peek_offset = 1;
562                        while let Some(&b) = self.input.read(peek_offset + 1).get(peek_offset) {
563                            if b.is_ascii_whitespace() {
564                                peek_offset += 1;
565                            } else {
566                                // Check if this byte could start a cast type (case-insensitive)
567                                let lower = b | 0x20; // ASCII lowercase
568                                if !matches!(lower, b'i' | b'b' | b'f' | b'd' | b'r' | b's' | b'a' | b'o' | b'u' | b'v')
569                                {
570                                    break 'parenthesis (TokenKind::LeftParenthesis, 1);
571                                }
572                                break;
573                            }
574                        }
575
576                        for (value, kind) in internal::consts::CAST_TYPES {
577                            if let Some(length) = self.input.match_sequence_ignore_whitespace(value, true) {
578                                break 'parenthesis (kind, length);
579                            }
580                        }
581
582                        (TokenKind::LeftParenthesis, 1)
583                    }
584                    [b'#', ..] => {
585                        let remaining = self.input.peek(1, self.input.len() - self.input.current_offset());
586                        let comment_len = scan_single_line_comment(remaining);
587                        (TokenKind::HashComment, 1 + comment_len)
588                    }
589                    [b'\\', ..] => (TokenKind::NamespaceSeparator, 1),
590                    [start_of_number!(), ..] if self.var_offset_depth > 0 => {
591                        let mut length = 1;
592                        let base = match self.input.read(2) {
593                            [b'0', b'x' | b'X'] => {
594                                length = 2;
595                                16
596                            }
597                            [b'0', b'b' | b'B'] => {
598                                length = 2;
599                                2
600                            }
601                            [b'0', b'o' | b'O'] => {
602                                length = 2;
603                                8
604                            }
605                            _ => 10,
606                        };
607
608                        (TokenKind::OffsetNumber, read_digits_of_base(&self.input, length, base))
609                    }
610                    [b'.', start_of_number!(), ..] if self.var_offset_depth == 0 => {
611                        let mut length = read_digits_of_base(&self.input, 2, 10);
612                        if let float_exponent!() = self.input.peek(length, 1) {
613                            let mut exp_length = length + 1;
614                            if let number_sign!() = self.input.peek(exp_length, 1) {
615                                exp_length += 1;
616                            }
617
618                            let after_exp = read_digits_of_base(&self.input, exp_length, 10);
619                            if after_exp > exp_length {
620                                length = after_exp;
621                            }
622                        }
623
624                        (TokenKind::LiteralFloat, length)
625                    }
626                    [start_of_number!(), ..] => 'number: {
627                        let mut length = 1;
628
629                        let (base, kind): (u8, NumberKind) = match self.input.read(3) {
630                            start_of_binary_number!() => {
631                                length += 1;
632
633                                (2, NumberKind::Integer)
634                            }
635                            start_of_octal_number!() => {
636                                length += 1;
637
638                                (8, NumberKind::Integer)
639                            }
640                            start_of_hexadecimal_number!() => {
641                                length += 1;
642
643                                (16, NumberKind::Integer)
644                            }
645                            start_of_octal_or_float_number!() => (10, NumberKind::OctalOrFloat),
646                            start_of_float_number!() => (10, NumberKind::Float),
647                            _ => (10, NumberKind::IntegerOrFloat),
648                        };
649
650                        if kind != NumberKind::Float {
651                            length = read_digits_of_base(&self.input, length, base);
652
653                            if kind == NumberKind::Integer {
654                                break 'number (TokenKind::LiteralInteger, length);
655                            }
656                        }
657
658                        let is_float = matches!(self.input.peek(length, 3), float_separator!());
659
660                        if !is_float {
661                            if kind == NumberKind::OctalOrFloat
662                                && let Some(invalid_idx) =
663                                    (1..length).find(|&i| matches!(self.input.peek(i, 1), [b'8' | b'9']))
664                            {
665                                let invalid_byte = self.input.peek(invalid_idx, 1)[0];
666                                let start = self.input.current_position();
667                                let invalid_position = Position { offset: start.offset + invalid_idx as u32 };
668                                self.input.consume(length);
669                                return Some(Err(SyntaxError::UnexpectedToken(
670                                    self.file_id(),
671                                    invalid_byte,
672                                    invalid_position,
673                                )));
674                            }
675                            break 'number (TokenKind::LiteralInteger, length);
676                        }
677
678                        if let [b'.'] = self.input.peek(length, 1) {
679                            length += 1;
680                            length = read_digits_of_base(&self.input, length, 10);
681                        }
682
683                        if let float_exponent!() = self.input.peek(length, 1) {
684                            // Only include exponent if there are digits after it
685                            let mut exp_length = length + 1;
686                            if let number_sign!() = self.input.peek(exp_length, 1) {
687                                exp_length += 1;
688                            }
689                            let after_exp = read_digits_of_base(&self.input, exp_length, 10);
690                            if after_exp > exp_length {
691                                // There are digits after the exponent marker
692                                length = after_exp;
693                            }
694                        }
695
696                        (TokenKind::LiteralFloat, length)
697                    }
698                    [b'.', ..] => (TokenKind::Dot, 1),
699                    [unknown_byte, ..] => {
700                        let position = self.input.current_position();
701                        self.input.consume(1);
702
703                        return Some(Err(SyntaxError::UnrecognizedToken(self.file_id(), *unknown_byte, position)));
704                    }
705                    [] => {
706                        // We check for EOF before entering scripting section, so this should be
707                        // unreachable. If we ever land here it means an upstream invariant broke,
708                        // so signal EOF gracefully rather than panicking inside the lexer.
709                        return None;
710                    }
711                };
712
713                self.mode = match token_kind {
714                    TokenKind::DoubleQuote => LexerMode::DoubleQuoteString(Interpolation::None),
715                    TokenKind::Backtick => LexerMode::ShellExecuteString(Interpolation::None),
716                    TokenKind::CloseTag => LexerMode::Inline,
717                    TokenKind::HaltCompiler => LexerMode::Halt(HaltStage::LookingForLeftParenthesis),
718                    TokenKind::DocumentStart(document_kind) => {
719                        let body_offset = self.input.current_offset() + len;
720                        let interpolated = matches!(document_kind, DocumentKind::Heredoc);
721                        let indent = read_document_indentation(&self.input, body_offset, document_label, interpolated);
722
723                        LexerMode::DocumentString(document_kind, document_label, indent, Interpolation::None)
724                    }
725                    _ => LexerMode::Script,
726                };
727
728                let buffer = self.input.consume(len);
729                let end = self.input.current_position();
730
731                Some(Ok(self.token(token_kind, buffer, start, end)))
732            }
733            LexerMode::DoubleQuoteString(interpolation) => match &interpolation {
734                Interpolation::None => {
735                    let start = self.input.current_position();
736
737                    let mut length = 0;
738                    let mut last_was_slash = false;
739                    let mut token_kind = TokenKind::StringPart;
740                    loop {
741                        match self.input.peek(length, 2) {
742                            [b'$', start_of_identifier!(), ..] if !last_was_slash => {
743                                let until_offset = read_until_end_of_variable_interpolation(&self.input, length + 2);
744
745                                self.mode =
746                                    LexerMode::DoubleQuoteString(Interpolation::Until(start.offset + until_offset));
747
748                                break;
749                            }
750                            [b'{', b'$', ..] | [b'$', b'{', ..] if !last_was_slash => {
751                                self.mode = LexerMode::DoubleQuoteString(Interpolation::Brace);
752
753                                break;
754                            }
755                            [b'\\', ..] => {
756                                length += 1;
757
758                                last_was_slash = !last_was_slash;
759                            }
760                            [b'"', ..] if !last_was_slash => {
761                                if length == 0 {
762                                    length += 1;
763                                    token_kind = TokenKind::DoubleQuote;
764
765                                    break;
766                                }
767
768                                break;
769                            }
770                            [_, ..] => {
771                                length += 1;
772                                last_was_slash = false;
773                            }
774                            [] => {
775                                break;
776                            }
777                        }
778                    }
779
780                    let buffer = self.input.consume(length);
781                    let end = self.input.current_position();
782
783                    if TokenKind::DoubleQuote == token_kind {
784                        self.mode = LexerMode::Script;
785                    }
786
787                    Some(Ok(self.token(token_kind, buffer, start, end)))
788                }
789                Interpolation::Until(offset) => {
790                    self.interpolation(Some(*offset), LexerMode::DoubleQuoteString(Interpolation::None))
791                }
792                Interpolation::Brace => self.interpolation(None, LexerMode::DoubleQuoteString(Interpolation::None)),
793            },
794            LexerMode::ShellExecuteString(interpolation) => match &interpolation {
795                Interpolation::None => {
796                    let start = self.input.current_position();
797
798                    let mut length = 0;
799                    let mut last_was_slash = false;
800                    let mut token_kind = TokenKind::StringPart;
801                    loop {
802                        match self.input.peek(length, 2) {
803                            [b'$', start_of_identifier!(), ..] if !last_was_slash => {
804                                let until_offset = read_until_end_of_variable_interpolation(&self.input, length + 2);
805
806                                self.mode =
807                                    LexerMode::ShellExecuteString(Interpolation::Until(start.offset + until_offset));
808
809                                break;
810                            }
811                            [b'{', b'$', ..] | [b'$', b'{', ..] if !last_was_slash => {
812                                self.mode = LexerMode::ShellExecuteString(Interpolation::Brace);
813
814                                break;
815                            }
816                            [b'\\', ..] => {
817                                length += 1;
818                                last_was_slash = !last_was_slash;
819                            }
820                            [b'`', ..] if !last_was_slash => {
821                                if length == 0 {
822                                    length += 1;
823                                    token_kind = TokenKind::Backtick;
824
825                                    break;
826                                }
827
828                                break;
829                            }
830                            [_, ..] => {
831                                length += 1;
832                                last_was_slash = false;
833                            }
834                            [] => {
835                                break;
836                            }
837                        }
838                    }
839
840                    let buffer = self.input.consume(length);
841                    let end = self.input.current_position();
842
843                    if TokenKind::Backtick == token_kind {
844                        self.mode = LexerMode::Script;
845                    }
846
847                    Some(Ok(self.token(token_kind, buffer, start, end)))
848                }
849                Interpolation::Until(offset) => {
850                    self.interpolation(Some(*offset), LexerMode::ShellExecuteString(Interpolation::None))
851                }
852                Interpolation::Brace => self.interpolation(None, LexerMode::ShellExecuteString(Interpolation::None)),
853            },
854            LexerMode::DocumentString(kind, label, indent, interpolation) => match &kind {
855                DocumentKind::Heredoc => match &interpolation {
856                    Interpolation::None => {
857                        let start = self.input.current_position();
858
859                        if indent > 0 && document_body_at_line_start(&self.input) {
860                            let width = document_leading_indent_width(&self.input, indent);
861                            if width > 0 && !document_line_is_closing_marker(&self.input, width, label) {
862                                let buffer = self.input.consume(width);
863                                let end = self.input.current_position();
864
865                                return Some(Ok(self.token(TokenKind::Whitespace, buffer, start, end)));
866                            }
867                        }
868
869                        let mut length = 0;
870                        let mut last_was_slash = false;
871                        let mut only_whitespaces = true;
872                        let mut token_kind = TokenKind::StringPart;
873                        loop {
874                            match self.input.peek(length, 2) {
875                                [b'\r', b'\n'] => {
876                                    if document_next_line_is_closing_marker(&self.input, length + 2, label) {
877                                        return self.document_segment_before_closing_marker(length, 2, start);
878                                    }
879
880                                    length += 2;
881
882                                    break;
883                                }
884                                [b'\n' | b'\r', ..] => {
885                                    if document_next_line_is_closing_marker(&self.input, length + 1, label) {
886                                        return self.document_segment_before_closing_marker(length, 1, start);
887                                    }
888
889                                    length += 1;
890
891                                    break;
892                                }
893                                [byte, ..] if byte.is_ascii_whitespace() => {
894                                    length += 1;
895                                }
896                                [b'$', start_of_identifier!(), ..] if !last_was_slash => {
897                                    let until_offset =
898                                        read_until_end_of_variable_interpolation(&self.input, length + 2);
899
900                                    self.mode = LexerMode::DocumentString(
901                                        kind,
902                                        label,
903                                        indent,
904                                        Interpolation::Until(start.offset + until_offset),
905                                    );
906
907                                    break;
908                                }
909                                [b'{', b'$', ..] | [b'$', b'{', ..] if !last_was_slash => {
910                                    self.mode = LexerMode::DocumentString(kind, label, indent, Interpolation::Brace);
911
912                                    break;
913                                }
914                                [b'\\', ..] => {
915                                    length += 1;
916                                    last_was_slash = !last_was_slash;
917                                    only_whitespaces = false;
918                                }
919                                [_, ..] => {
920                                    if only_whitespaces
921                                        && self.input.peek(length, label.len()) == label
922                                        && self
923                                            .input
924                                            .peek(length + label.len(), 1)
925                                            .first()
926                                            .is_none_or(|c| !is_part_of_identifier(c))
927                                    {
928                                        length += label.len();
929                                        token_kind = TokenKind::DocumentEnd;
930
931                                        break;
932                                    }
933
934                                    length += 1;
935                                    last_was_slash = false;
936                                    only_whitespaces = false;
937                                }
938                                [] => {
939                                    break;
940                                }
941                            }
942                        }
943
944                        let buffer = self.input.consume(length);
945                        let end = self.input.current_position();
946
947                        if TokenKind::DocumentEnd == token_kind {
948                            self.mode = LexerMode::Script;
949                        }
950
951                        Some(Ok(self.token(token_kind, buffer, start, end)))
952                    }
953                    Interpolation::Until(offset) => self.interpolation(
954                        Some(*offset),
955                        LexerMode::DocumentString(kind, label, indent, Interpolation::None),
956                    ),
957                    Interpolation::Brace => {
958                        self.interpolation(None, LexerMode::DocumentString(kind, label, indent, Interpolation::None))
959                    }
960                },
961                DocumentKind::Nowdoc => {
962                    let start = self.input.current_position();
963
964                    if indent > 0 && document_body_at_line_start(&self.input) {
965                        let width = document_leading_indent_width(&self.input, indent);
966                        if width > 0 && !document_line_is_closing_marker(&self.input, width, label) {
967                            let buffer = self.input.consume(width);
968                            let end = self.input.current_position();
969
970                            return Some(Ok(self.token(TokenKind::Whitespace, buffer, start, end)));
971                        }
972                    }
973
974                    let mut length = 0;
975                    let mut terminated = false;
976                    let mut only_whitespaces = true;
977
978                    loop {
979                        match self.input.peek(length, 2) {
980                            [b'\r', b'\n'] => {
981                                if document_next_line_is_closing_marker(&self.input, length + 2, label) {
982                                    return self.document_segment_before_closing_marker(length, 2, start);
983                                }
984
985                                length += 2;
986
987                                break;
988                            }
989                            [b'\n' | b'\r', ..] => {
990                                if document_next_line_is_closing_marker(&self.input, length + 1, label) {
991                                    return self.document_segment_before_closing_marker(length, 1, start);
992                                }
993
994                                length += 1;
995
996                                break;
997                            }
998                            [byte, ..] if byte.is_ascii_whitespace() => {
999                                length += 1;
1000                            }
1001                            [_, ..] => {
1002                                if only_whitespaces
1003                                    && self.input.peek(length, label.len()) == label
1004                                    && self
1005                                        .input
1006                                        .peek(length + label.len(), 1)
1007                                        .first()
1008                                        .is_none_or(|c| !is_part_of_identifier(c))
1009                                {
1010                                    length += label.len();
1011                                    terminated = true;
1012
1013                                    break;
1014                                }
1015
1016                                only_whitespaces = false;
1017                                length += 1;
1018                            }
1019                            [] => {
1020                                break;
1021                            }
1022                        }
1023                    }
1024
1025                    let buffer = self.input.consume(length);
1026                    let end = self.input.current_position();
1027
1028                    if terminated {
1029                        self.mode = LexerMode::Script;
1030
1031                        return Some(Ok(self.token(TokenKind::DocumentEnd, buffer, start, end)));
1032                    }
1033
1034                    Some(Ok(self.token(TokenKind::StringPart, buffer, start, end)))
1035                }
1036            },
1037            LexerMode::Halt(stage) => 'halt: {
1038                let start = self.input.current_position();
1039                if let HaltStage::End = stage {
1040                    let buffer = self.input.consume_remaining();
1041                    let end = self.input.current_position();
1042
1043                    break 'halt Some(Ok(self.token(TokenKind::InlineText, buffer, start, end)));
1044                }
1045
1046                let whitespaces = self.input.consume_whitespaces();
1047                if !whitespaces.is_empty() {
1048                    let end = self.input.current_position();
1049
1050                    break 'halt Some(Ok(self.token(TokenKind::Whitespace, whitespaces, start, end)));
1051                }
1052
1053                match &stage {
1054                    HaltStage::LookingForLeftParenthesis => {
1055                        if self.input.is_at(b"(", false) {
1056                            let buffer = self.input.consume(1);
1057                            let end = self.input.current_position();
1058
1059                            self.mode = LexerMode::Halt(HaltStage::LookingForRightParenthesis);
1060
1061                            Some(Ok(self.token(TokenKind::LeftParenthesis, buffer, start, end)))
1062                        } else {
1063                            let byte = self.input.read(1)[0];
1064                            let position = self.input.current_position();
1065                            // Consume the unexpected byte to avoid infinite loops
1066                            self.input.consume(1);
1067                            Some(Err(SyntaxError::UnexpectedToken(self.file_id(), byte, position)))
1068                        }
1069                    }
1070                    HaltStage::LookingForRightParenthesis => {
1071                        if self.input.is_at(b")", false) {
1072                            let buffer = self.input.consume(1);
1073                            let end = self.input.current_position();
1074
1075                            self.mode = LexerMode::Halt(HaltStage::LookingForTerminator);
1076
1077                            Some(Ok(self.token(TokenKind::RightParenthesis, buffer, start, end)))
1078                        } else {
1079                            let byte = self.input.read(1)[0];
1080                            let position = self.input.current_position();
1081                            self.input.consume(1);
1082                            Some(Err(SyntaxError::UnexpectedToken(self.file_id(), byte, position)))
1083                        }
1084                    }
1085                    HaltStage::LookingForTerminator => {
1086                        if self.input.is_at(b";", false) {
1087                            let buffer = self.input.consume(1);
1088                            let end = self.input.current_position();
1089
1090                            self.mode = LexerMode::Halt(HaltStage::End);
1091
1092                            Some(Ok(self.token(TokenKind::Semicolon, buffer, start, end)))
1093                        } else if self.input.is_at(b"?>", false) {
1094                            let buffer = self.input.consume(2);
1095                            let end = self.input.current_position();
1096
1097                            self.mode = LexerMode::Halt(HaltStage::End);
1098
1099                            Some(Ok(self.token(TokenKind::CloseTag, buffer, start, end)))
1100                        } else {
1101                            let byte = self.input.read(1)[0];
1102                            let position = self.input.current_position();
1103                            self.input.consume(1);
1104                            Some(Err(SyntaxError::UnexpectedToken(self.file_id(), byte, position)))
1105                        }
1106                    }
1107                    HaltStage::End => {
1108                        // The `HaltStage::End` arm is reached only after the early-return at the top of
1109                        // this branch consumed the terminating `?>` or EOF; surfacing `None` keeps the
1110                        // lexer total instead of relying on `unreachable!`.
1111                        None
1112                    }
1113                }
1114            }
1115        }
1116    }
1117
1118    /// Fast path for scanning identifiers and keywords.
1119    /// Called when we know the first byte is an identifier start character.
1120    /// Returns (TokenKind, length) to allow proper mode switching.
1121    #[inline]
1122    fn scan_identifier_or_keyword_info(&self) -> (TokenKind, usize) {
1123        let (length, ended_with_slash) = self.input.scan_identifier(0);
1124
1125        if !ended_with_slash && matches!(self.input.peek(length, 1), [b'(']) {
1126            match length {
1127                6 if self.input.is_at(b"public(set)", true) => {
1128                    return (TokenKind::PublicSet, 11);
1129                }
1130                7 if self.input.is_at(b"private(set)", true) => {
1131                    return (TokenKind::PrivateSet, 12);
1132                }
1133                9 if self.input.is_at(b"protected(set)", true) => {
1134                    return (TokenKind::ProtectedSet, 14);
1135                }
1136                _ => {}
1137            }
1138        }
1139
1140        if !ended_with_slash {
1141            if let Some(kind) = internal::keyword::lookup_keyword(self.input.read(length)) {
1142                return (kind, length);
1143            }
1144
1145            return (TokenKind::Identifier, length);
1146        }
1147
1148        self.scan_qualified_identifier_info(length)
1149    }
1150
1151    // Keep qualified-name scanning out of the common identifier/keyword path.
1152    #[inline(never)]
1153    fn scan_qualified_identifier_info(&self, mut length: usize) -> (TokenKind, usize) {
1154        let mut slashes = 0;
1155        let mut last_was_slash = false;
1156        loop {
1157            match self.input.peek(length, 1) {
1158                [b'a'..=b'z' | b'A'..=b'Z' | b'_' | 0x80..=0xFF] if last_was_slash => {
1159                    length += 1;
1160                    last_was_slash = false;
1161                }
1162                [b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | 0x80..=0xFF] if !last_was_slash => {
1163                    length += 1;
1164                }
1165                [b'\\'] if !self.interpolating || self.brace_interpolating => {
1166                    if last_was_slash {
1167                        length -= 1;
1168                        slashes -= 1;
1169                        last_was_slash = false;
1170                        break;
1171                    }
1172
1173                    length += 1;
1174                    slashes += 1;
1175                    last_was_slash = true;
1176                }
1177                _ => {
1178                    break;
1179                }
1180            }
1181        }
1182
1183        if last_was_slash {
1184            length -= 1;
1185            slashes -= 1;
1186        }
1187
1188        let kind = if slashes > 0 { TokenKind::QualifiedIdentifier } else { TokenKind::Identifier };
1189
1190        (kind, length)
1191    }
1192
1193    #[inline]
1194    fn token(&self, kind: TokenKind, value: &'input [u8], start: Position, _end: Position) -> Token<'input> {
1195        Token { kind, start, value }
1196    }
1197
1198    /// Emits the last body segment before a heredoc/nowdoc closing marker. The
1199    /// line terminator immediately preceding the marker is not part of the
1200    /// string value, so it is surfaced as `Whitespace` trivia: when there is
1201    /// preceding content the terminator is queued to follow the `StringPart`,
1202    /// otherwise the terminator is emitted on its own.
1203    fn document_segment_before_closing_marker(
1204        &mut self,
1205        content_length: usize,
1206        terminator_length: usize,
1207        start: Position,
1208    ) -> Option<Result<Token<'input>, SyntaxError>> {
1209        if content_length == 0 {
1210            let buffer = self.input.consume(terminator_length);
1211            let end = self.input.current_position();
1212
1213            return Some(Ok(self.token(TokenKind::Whitespace, buffer, start, end)));
1214        }
1215
1216        let content = self.input.consume(content_length);
1217        let content_end = self.input.current_position();
1218        let terminator = self.input.consume(terminator_length);
1219        let terminator_end = self.input.current_position();
1220
1221        if self.interpolating {
1222            self.buffer.push_back(self.token(TokenKind::StringPart, content, start, content_end));
1223
1224            return Some(Ok(self.token(TokenKind::Whitespace, terminator, content_end, terminator_end)));
1225        }
1226
1227        self.buffer.push_back(self.token(TokenKind::Whitespace, terminator, content_end, terminator_end));
1228
1229        Some(Ok(self.token(TokenKind::StringPart, content, start, content_end)))
1230    }
1231
1232    fn peek_string_varname_label(&self) -> bool {
1233        let Some(&first) = self.input.read(1).first() else {
1234            return false;
1235        };
1236
1237        if !IDENT_START_TABLE[first as usize] {
1238            return false;
1239        }
1240
1241        let (label_length, _) = self.input.scan_identifier(0);
1242
1243        matches!(self.input.read(label_length + 1).get(label_length), Some(b'[' | b'}'))
1244    }
1245
1246    #[inline]
1247    fn interpolation(
1248        &mut self,
1249        end_offset: Option<u32>,
1250        post_interpolation_mode: LexerMode<'input>,
1251    ) -> Option<Result<Token<'input>, SyntaxError>> {
1252        self.interpolation_depth += 1;
1253        if self.interpolation_depth > Self::MAX_INTERPOLATION_DEPTH {
1254            self.interpolation_depth -= 1;
1255
1256            return Some(Err(SyntaxError::RecursionLimitExceeded(self.file_id(), self.input.current_position())));
1257        }
1258
1259        let brace = end_offset.is_none();
1260        let mut brace_depth = 0u32;
1261        self.mode = LexerMode::Script;
1262
1263        let was_interpolating = self.interpolating;
1264        self.interpolating = true;
1265        let was_brace_interpolating = self.brace_interpolating;
1266        // For brace interpolation ({$...}), allow qualified identifiers with backslashes.
1267        self.brace_interpolating = brace;
1268        let was_var_offset_depth = self.var_offset_depth;
1269        self.var_offset_depth = 0;
1270        let was_expect_string_varname = self.expect_string_varname;
1271        self.expect_string_varname = false;
1272
1273        let pending_error = loop {
1274            match self.advance() {
1275                Some(Ok(token)) => {
1276                    let token_start = token.start.offset;
1277                    let token_end = token_start + token.value.len() as u32;
1278                    let is_final_token = match end_offset {
1279                        Some(end_offset) => token_start <= end_offset && end_offset <= token_end,
1280                        None => match token.kind {
1281                            TokenKind::LeftBrace | TokenKind::DollarLeftBrace => {
1282                                brace_depth += 1;
1283                                false
1284                            }
1285                            TokenKind::RightBrace => {
1286                                brace_depth = brace_depth.saturating_sub(1);
1287                                brace_depth == 0
1288                            }
1289                            _ => false,
1290                        },
1291                    };
1292
1293                    if brace {
1294                        if token.kind == TokenKind::DollarLeftBrace && self.peek_string_varname_label() {
1295                            self.expect_string_varname = true;
1296                        }
1297                    } else {
1298                        match token.kind {
1299                            TokenKind::LeftBracket => self.var_offset_depth += 1,
1300                            TokenKind::RightBracket => {
1301                                self.var_offset_depth = self.var_offset_depth.saturating_sub(1);
1302                            }
1303                            _ => {}
1304                        }
1305                    }
1306
1307                    self.buffer.push_back(token);
1308
1309                    if is_final_token {
1310                        break None;
1311                    }
1312                }
1313                Some(Err(error)) => break Some(error),
1314                None => break None,
1315            }
1316        };
1317
1318        self.mode = post_interpolation_mode;
1319        self.interpolating = was_interpolating;
1320        self.brace_interpolating = was_brace_interpolating;
1321        self.var_offset_depth = was_var_offset_depth;
1322        self.expect_string_varname = was_expect_string_varname;
1323        self.interpolation_depth -= 1;
1324
1325        if let Some(error) = pending_error {
1326            return Some(Err(error));
1327        }
1328
1329        self.advance()
1330    }
1331}
1332
1333impl HasFileId for Lexer<'_> {
1334    #[inline]
1335    fn file_id(&self) -> FileId {
1336        self.input.file_id()
1337    }
1338}
1339
1340#[inline]
1341fn matches_start_of_heredoc_document(input: &Input, prefix_len: usize) -> bool {
1342    let total = input.len();
1343    let base = input.current_offset();
1344
1345    // Start after the prefix (if any) and the fixed opener (3 bytes).
1346    let mut length = 3 + prefix_len;
1347    // Consume any following whitespace.
1348    while base + length < total && input.read_at(base + length).is_ascii_whitespace() {
1349        length += 1;
1350    }
1351
1352    // The next byte must be a valid start-of-identifier.
1353    if base + length >= total || !is_start_of_identifier(input.read_at(base + length)) {
1354        return false;
1355    }
1356    length += 1; // Include that identifier start.
1357
1358    // Now continue reading identifier characters until a newline is found.
1359    loop {
1360        let pos = base + length;
1361        if pos >= total {
1362            return false; // Unexpected EOF
1363        }
1364
1365        let byte = *input.read_at(pos);
1366        if byte == b'\n' {
1367            return true; // Newline found: valid heredoc opener.
1368        } else if byte == b'\r' {
1369            // Handle CRLF: treat '\r' followed by '\n' as a newline as well.
1370            return pos + 1 < total && *input.read_at(pos + 1) == b'\n';
1371        } else if is_part_of_identifier(input.read_at(pos)) {
1372            length += 1;
1373        } else {
1374            return false; // Unexpected character.
1375        }
1376    }
1377}
1378
1379#[inline]
1380fn matches_start_of_double_quote_heredoc_document(input: &Input, prefix_len: usize) -> bool {
1381    let total = input.len();
1382    let base = input.current_offset();
1383
1384    // Start after the prefix (if any) and the fixed opener (3 bytes), then skip any whitespace.
1385    let mut length = 3 + prefix_len;
1386    while base + length < total && input.read_at(base + length).is_ascii_whitespace() {
1387        length += 1;
1388    }
1389
1390    // Next, expect an opening double quote.
1391    if base + length >= total || *input.read_at(base + length) != b'"' {
1392        return false;
1393    }
1394    length += 1;
1395
1396    // The following byte must be a valid start-of-identifier.
1397    if base + length >= total || !is_start_of_identifier(input.read_at(base + length)) {
1398        return false;
1399    }
1400    length += 1;
1401
1402    // Now scan the label. For double‑quoted heredoc, a terminating double quote is required.
1403    let mut terminated = false;
1404    loop {
1405        let pos = base + length;
1406        if pos >= total {
1407            return false;
1408        }
1409        let byte = input.read_at(pos);
1410        if *byte == b'\n' {
1411            // End of line: valid only if a closing double quote was encountered.
1412            return terminated;
1413        } else if *byte == b'\r' {
1414            // Handle CRLF sequences.
1415            return terminated && pos + 1 < total && *input.read_at(pos + 1) == b'\n';
1416        } else if !terminated && is_part_of_identifier(byte) {
1417            length += 1;
1418        } else if !terminated && *byte == b'"' {
1419            terminated = true;
1420            length += 1;
1421        } else {
1422            return false;
1423        }
1424    }
1425}
1426
1427#[inline]
1428fn matches_start_of_nowdoc_document(input: &Input, prefix_len: usize) -> bool {
1429    let total = input.len();
1430    let base = input.current_offset();
1431
1432    // Start after the prefix (if any) and the fixed opener (3 bytes) and skip whitespace.
1433    let mut length = 3 + prefix_len;
1434    while base + length < total && input.read_at(base + length).is_ascii_whitespace() {
1435        length += 1;
1436    }
1437
1438    // Now, the next byte must be a single quote.
1439    if base + length >= total || *input.read_at(base + length) != b'\'' {
1440        return false;
1441    }
1442    length += 1;
1443
1444    // The following byte must be a valid start-of-identifier.
1445    if base + length >= total || !is_start_of_identifier(input.read_at(base + length)) {
1446        return false;
1447    }
1448    length += 1;
1449
1450    // Read the label until a newline. A terminating single quote is required.
1451    let mut terminated = false;
1452    loop {
1453        let pos = base + length;
1454        if pos >= total {
1455            return false;
1456        }
1457        let byte = *input.read_at(pos);
1458        if byte == b'\n' {
1459            return terminated;
1460        } else if byte == b'\r' {
1461            return terminated && pos + 1 < total && *input.read_at(pos + 1) == b'\n';
1462        } else if !terminated && is_part_of_identifier(&byte) {
1463            length += 1;
1464        } else if !terminated && byte == b'\'' {
1465            terminated = true;
1466            length += 1;
1467        } else {
1468            return false;
1469        }
1470    }
1471}
1472
1473#[inline]
1474fn read_literal_double_quote_string(input: &Input, prefix_len: usize) -> Option<(TokenKind, usize)> {
1475    let bytes = input.read_remaining();
1476    let mut start = prefix_len + 1;
1477    while let Some(offset) = memchr::memchr3(b'"', b'\\', b'$', &bytes[start..]) {
1478        let position = start + offset;
1479        match bytes[position] {
1480            b'"' => return Some((TokenKind::LiteralString, position + 1)),
1481            b'\\' => start = (position + 2).min(bytes.len()),
1482            _ => {
1483                // A brace before this scan's start belongs to the escape just skipped.
1484                if (position > start && bytes[position - 1] == b'{')
1485                    || bytes.get(position + 1).is_some_and(|next| is_start_of_identifier(next) || *next == b'{')
1486                {
1487                    return None;
1488                }
1489                start = position + 1;
1490            }
1491        }
1492    }
1493
1494    Some((TokenKind::PartialLiteralString, bytes.len()))
1495}
1496
1497/// Measures the indentation of a heredoc/nowdoc closing marker by scanning the
1498/// body line by line, starting at `body_offset`, until the first line whose
1499/// leading whitespace is followed by the closing `label`. The returned width is
1500/// the number of leading space/tab bytes on that line; PHP 7.3 flexible
1501/// heredoc/nowdoc strips up to that many columns from every body line.
1502fn read_document_indentation(input: &Input, body_offset: usize, label: &[u8], interpolated: bool) -> usize {
1503    let total = input.len();
1504    let base = input.current_offset();
1505    let mut position = body_offset;
1506    loop {
1507        let mut width = 0;
1508        while position < total && matches!(*input.read_at(position), b' ' | b'\t') {
1509            width += 1;
1510            position += 1;
1511        }
1512
1513        if label_matches_at(input, position, label, total) {
1514            return width;
1515        }
1516
1517        let mut last_was_slash = false;
1518        while position < total && !matches!(*input.read_at(position), b'\n' | b'\r') {
1519            let byte = *input.read_at(position);
1520            let next = (position + 1 < total).then(|| *input.read_at(position + 1));
1521
1522            if interpolated && !last_was_slash {
1523                if (byte == b'$' && next == Some(b'{')) || (byte == b'{' && next == Some(b'$')) {
1524                    let from = (position - base) + 2;
1525                    position = base + read_until_end_of_brace_interpolation(input, from) as usize;
1526
1527                    continue;
1528                }
1529
1530                if byte == b'$' && next.is_some_and(|c| is_start_of_identifier(&c)) {
1531                    let from = (position - base) + 2;
1532                    position = base + read_until_end_of_variable_interpolation(input, from) as usize;
1533
1534                    continue;
1535                }
1536            }
1537
1538            last_was_slash = byte == b'\\' && !last_was_slash;
1539            position += 1;
1540        }
1541
1542        if position >= total {
1543            return 0;
1544        }
1545
1546        if *input.read_at(position) == b'\r' && position + 1 < total && *input.read_at(position + 1) == b'\n' {
1547            position += 2;
1548        } else {
1549            position += 1;
1550        }
1551    }
1552}
1553
1554/// Whether the closing `label` appears at the absolute `position`, not followed
1555/// by an identifier byte (so `EOT` matches but `EOTish` does not).
1556fn label_matches_at(input: &Input, position: usize, label: &[u8], total: usize) -> bool {
1557    if position + label.len() > total {
1558        return false;
1559    }
1560
1561    let mut index = 0;
1562    while index < label.len() {
1563        if *input.read_at(position + index) != label[index] {
1564            return false;
1565        }
1566        index += 1;
1567    }
1568
1569    let after = position + label.len();
1570    after >= total || !is_part_of_identifier(input.read_at(after))
1571}
1572
1573/// Whether the lexer is positioned at the start of a heredoc/nowdoc body line,
1574/// i.e. the previous byte is a line terminator.
1575#[inline]
1576fn document_body_at_line_start(input: &Input) -> bool {
1577    let offset = input.current_offset();
1578    offset == 0 || matches!(*input.read_at(offset - 1), b'\n' | b'\r')
1579}
1580
1581/// Counts the leading space/tab bytes at the current position, capped at `indent`.
1582#[inline]
1583fn document_leading_indent_width(input: &Input, indent: usize) -> usize {
1584    let mut width = 0;
1585    while width < indent && matches!(input.peek(width, 1), [b' ' | b'\t']) {
1586        width += 1;
1587    }
1588
1589    width
1590}
1591
1592/// Whether the current line, after `width` leading whitespace bytes, is the
1593/// closing marker. The marker's own indentation is left attached to the
1594/// `DocumentEnd` token rather than stripped as trivia.
1595#[inline]
1596fn document_line_is_closing_marker(input: &Input, width: usize, label: &[u8]) -> bool {
1597    input.peek(width, label.len()) == label
1598        && input.peek(width + label.len(), 1).first().is_none_or(|byte| !is_part_of_identifier(byte))
1599}
1600
1601/// Whether the line beginning at relative `offset` (just past a line terminator)
1602/// is the closing marker. Used to recognise the terminator that immediately
1603/// precedes the marker, which a heredoc/nowdoc drops from the string value.
1604#[inline]
1605fn document_next_line_is_closing_marker(input: &Input, offset: usize, label: &[u8]) -> bool {
1606    let mut width = 0;
1607    while matches!(input.peek(offset + width, 1), [b' ' | b'\t']) {
1608        width += 1;
1609    }
1610
1611    input.peek(offset + width, label.len()) == label
1612        && input.peek(offset + width + label.len(), 1).first().is_none_or(|byte| !is_part_of_identifier(byte))
1613}
1614
1615#[inline]
1616fn read_start_of_heredoc_document(input: &Input, double_quoted: bool, prefix_len: usize) -> (usize, usize, usize) {
1617    let total = input.len();
1618    let base = input.current_offset();
1619
1620    // Start reading after the prefix (if any) and the fixed opener (3 bytes).
1621    let mut pos = base + 3 + prefix_len;
1622    let mut whitespaces = 0;
1623    while pos < total && input.read_at(pos).is_ascii_whitespace() {
1624        whitespaces += 1;
1625        pos += 1;
1626    }
1627
1628    // The label (or delimiter) starts after:
1629    //   prefix + 3 bytes + whitespace bytes + an extra offset:
1630    //      if double-quoted: 2 bytes (opening and closing quotes around the label)
1631    //      else: 1 byte.
1632    let mut length = 3 + prefix_len + whitespaces + if double_quoted { 2 } else { 1 };
1633
1634    let mut label_length = 1; // Start with at least one byte for the label.
1635    let mut terminated = false; // For double-quoted heredoc, to track the closing quote.
1636    loop {
1637        let pos = base + length;
1638        // Bail out gracefully if we run past the input or hit a byte that the caller's
1639        // earlier validation should have rejected: returning the accumulated `(length,
1640        // whitespaces, label_length)` lets the lexer produce a malformed-heredoc token
1641        // instead of panicking.
1642        if pos >= total {
1643            return (length, whitespaces, label_length);
1644        }
1645
1646        let byte = *input.read_at(pos);
1647        if byte == b'\n' {
1648            // Newline ends the label.
1649            length += 1;
1650            return (length, whitespaces, label_length);
1651        } else if byte == b'\r' {
1652            // Handle CRLF sequences
1653            if pos + 1 < total && *input.read_at(pos + 1) == b'\n' {
1654                length += 2;
1655            } else {
1656                length += 1;
1657            }
1658            return (length, whitespaces, label_length);
1659        } else if is_part_of_identifier(&byte) && (!double_quoted || !terminated) {
1660            // For both unquoted and double-quoted (before the closing quote) heredoc,
1661            // a valid identifier character is part of the label.
1662            length += 1;
1663            label_length += 1;
1664        } else if double_quoted && !terminated && byte == b'"' {
1665            // In a double-quoted heredoc, a double quote terminates the label.
1666            length += 1;
1667            terminated = true;
1668        } else {
1669            // Malformed heredoc label: stop scanning and let the caller surface a parse error.
1670            return (length, whitespaces, label_length);
1671        }
1672    }
1673}
1674
1675#[inline]
1676fn read_start_of_nowdoc_document(input: &Input, prefix_len: usize) -> (usize, usize, usize) {
1677    let total = input.len();
1678    let base = input.current_offset();
1679
1680    let mut pos = base + 3 + prefix_len;
1681    let mut whitespaces = 0;
1682    while pos < total && input.read_at(pos).is_ascii_whitespace() {
1683        whitespaces += 1;
1684        pos += 1;
1685    }
1686
1687    // For nowdoc, the fixed extra offset is always 2.
1688    let mut length = 3 + prefix_len + whitespaces + 2;
1689
1690    let mut label_length = 1;
1691    let mut terminated = false;
1692    loop {
1693        let pos = base + length;
1694        if pos >= total {
1695            // Bail out gracefully on truncated input; surfacing the accumulated state lets the
1696            // lexer report a parse error instead of panicking.
1697            return (length, whitespaces, label_length);
1698        }
1699        let byte = *input.read_at(pos);
1700
1701        if byte == b'\n' {
1702            // A newline indicates the end of the label.
1703            length += 1;
1704            return (length, whitespaces, label_length);
1705        } else if byte == b'\r' {
1706            // Handle CRLF sequences
1707            if pos + 1 < total && *input.read_at(pos + 1) == b'\n' {
1708                length += 2;
1709            } else {
1710                length += 1;
1711            }
1712            return (length, whitespaces, label_length);
1713        } else if is_part_of_identifier(&byte) && !terminated {
1714            // For nowdoc, identifier characters contribute to the label until terminated.
1715            length += 1;
1716            label_length += 1;
1717        } else if !terminated && byte == b'\'' {
1718            // A single quote terminates the nowdoc label.
1719            length += 1;
1720            terminated = true;
1721        } else {
1722            // Malformed nowdoc label: stop scanning and let the caller surface a parse error.
1723            return (length, whitespaces, label_length);
1724        }
1725    }
1726}
1727
1728#[inline]
1729fn read_literal_string(input: &Input, quote: u8, prefix_len: usize) -> (TokenKind, usize) {
1730    let total = input.len();
1731    let start = input.current_offset();
1732    let skip = prefix_len + 1; // prefix + opening quote
1733    let mut length = skip;
1734
1735    let bytes = input.peek(skip, total - start - skip);
1736    loop {
1737        let scan_start = length - skip;
1738        match memchr2(quote, b'\\', &bytes[scan_start..]) {
1739            Some(pos) => {
1740                let abs_pos = scan_start + pos;
1741                let byte = bytes[abs_pos];
1742
1743                if byte == b'\\' {
1744                    length = skip + abs_pos + 2;
1745                    if length > total - start {
1746                        return (TokenKind::PartialLiteralString, total - start);
1747                    }
1748                } else {
1749                    length = skip + abs_pos + 1; // +1 for the closing quote
1750                    return (TokenKind::LiteralString, length);
1751                }
1752            }
1753            None => {
1754                // No quote or backslash found - EOF
1755                return (TokenKind::PartialLiteralString, total - start);
1756            }
1757        }
1758    }
1759}
1760
1761#[inline]
1762fn read_until_end_of_variable_interpolation(input: &Input, from: usize) -> u32 {
1763    let total = input.len();
1764    let base = input.current_offset();
1765    // `offset` is relative to the current position.
1766    let mut offset = from;
1767
1768    loop {
1769        let abs = base + offset;
1770        if abs >= total {
1771            // End of input.
1772            break;
1773        }
1774
1775        // Pattern 1: If the current byte is part of an identifier, simply advance.
1776        if is_part_of_identifier(input.read_at(abs)) {
1777            offset += 1;
1778            continue;
1779        }
1780
1781        // Pattern 2: If the current byte is a '[' then we enter a bracketed interpolation.
1782        if *input.read_at(abs) == b'[' {
1783            offset += 1;
1784            let mut nesting = 0;
1785            loop {
1786                let abs_inner = base + offset;
1787                if abs_inner >= total {
1788                    break;
1789                }
1790                let b = input.read_at(abs_inner);
1791                if *b == b']' {
1792                    offset += 1;
1793                    if nesting == 0 {
1794                        break;
1795                    }
1796
1797                    nesting -= 1;
1798                } else if *b == b'[' {
1799                    offset += 1;
1800                    nesting += 1;
1801                } else if b.is_ascii_whitespace() {
1802                    // Do not include whitespace.
1803                    break;
1804                } else {
1805                    offset += 1;
1806                }
1807            }
1808            // When bracketed interpolation is processed, exit the loop.
1809            break;
1810        }
1811
1812        // Pattern 3: Check for "->" followed by a valid identifier start.
1813        if base + offset + 2 < total
1814            && *input.read_at(abs) == b'-'
1815            && *input.read_at(base + offset + 1) == b'>'
1816            && is_start_of_identifier(input.read_at(base + offset + 2))
1817        {
1818            offset += 3;
1819            // Consume any following identifier characters.
1820            while base + offset < total && is_part_of_identifier(input.read_at(base + offset)) {
1821                offset += 1;
1822            }
1823            break;
1824        }
1825
1826        // Pattern 4: Check for "?->" followed by a valid identifier start.
1827        if base + offset + 3 < total
1828            && *input.read_at(abs) == b'?'
1829            && *input.read_at(base + offset + 1) == b'-'
1830            && *input.read_at(base + offset + 2) == b'>'
1831            && is_start_of_identifier(input.read_at(base + offset + 3))
1832        {
1833            offset += 4;
1834            while base + offset < total && is_part_of_identifier(input.read_at(base + offset)) {
1835                offset += 1;
1836            }
1837            break;
1838        }
1839
1840        // None of the expected patterns matched: exit the loop.
1841        break;
1842    }
1843
1844    offset as u32
1845}
1846
1847/// Scan forward from a `{$`/`${` brace interpolation to the offset just past
1848/// its matching `}` (tracking `{`/`}` nesting), or to end-of-input if the
1849/// interpolation is never closed.
1850///
1851/// The expression inside `{$...}` is real PHP and may contain nested string
1852/// literals - e.g. `"{$a["key"]}"` - whose own `{`/`}` bytes must not be
1853/// counted as interpolation braces (consider `"{$a["}"]}"`). Nested `'`, `"`,
1854/// and `` ` `` strings are therefore skipped wholesale, honouring `\` escapes,
1855/// so a `}` inside a nested string neither closes the interpolation early nor
1856/// is miscounted.
1857#[inline]
1858fn read_until_end_of_brace_interpolation(input: &Input, from: usize) -> u32 {
1859    let total = input.len();
1860    let base = input.current_offset();
1861    let mut offset = from;
1862    let mut nesting = 0;
1863
1864    loop {
1865        let abs = base + offset;
1866        if abs >= total {
1867            break;
1868        }
1869        match *input.read_at(abs) {
1870            b'}' => {
1871                offset += 1;
1872                if nesting == 0 {
1873                    break;
1874                }
1875
1876                nesting -= 1;
1877            }
1878            b'{' => {
1879                offset += 1;
1880                nesting += 1;
1881            }
1882            quote @ (b'\'' | b'"' | b'`') => {
1883                offset += 1;
1884                loop {
1885                    let abs = base + offset;
1886                    if abs >= total {
1887                        break;
1888                    }
1889                    match *input.read_at(abs) {
1890                        b'\\' => offset += 2,
1891                        b if b == quote => {
1892                            offset += 1;
1893                            break;
1894                        }
1895                        _ => offset += 1,
1896                    }
1897                }
1898            }
1899            _ => {
1900                offset += 1;
1901            }
1902        }
1903    }
1904
1905    offset as u32
1906}
1907
1908/// Scan a multi-line comment using SIMD-accelerated search.
1909/// Returns Some(length) including the closing */, or None if unterminated.
1910#[inline]
1911fn scan_multi_line_comment(bytes: &[u8]) -> Option<usize> {
1912    // Use SIMD to find */ quickly
1913    memmem::find(bytes, b"*/").map(|pos| pos + 2)
1914}
1915
1916/// Scan a single-line comment using SIMD-accelerated search.
1917/// Returns the length of the comment body (not including the //).
1918/// Stops at newline or ?>.
1919#[inline]
1920fn scan_single_line_comment(bytes: &[u8]) -> usize {
1921    let mut pos = 0;
1922    while pos < bytes.len() {
1923        match memchr::memchr3(b'\n', b'\r', b'?', &bytes[pos..]) {
1924            Some(offset) => {
1925                let found_pos = pos + offset;
1926                match bytes[found_pos] {
1927                    b'\n' | b'\r' => return found_pos,
1928                    b'?' => {
1929                        // Check if it's ?>
1930                        if found_pos + 1 < bytes.len() && bytes[found_pos + 1] == b'>' {
1931                            // Also check for whitespace before ?>
1932                            if found_pos > 0 && bytes[found_pos - 1].is_ascii_whitespace() {
1933                                return found_pos - 1;
1934                            }
1935                            return found_pos;
1936                        }
1937                        // Not ?>, continue searching
1938                        pos = found_pos + 1;
1939                    }
1940                    // `memchr3` only matches the three bytes we asked for; any other value here would
1941                    // indicate a memchr bug. Treat it as end-of-comment so the lexer keeps making progress.
1942                    _ => return found_pos,
1943                }
1944            }
1945            None => return bytes.len(),
1946        }
1947    }
1948
1949    bytes.len()
1950}
1951
1952#[cfg(test)]
1953mod tests {
1954    use super::*;
1955
1956    fn read_double_quote_reference(input: &Input, prefix_len: usize) -> Option<(TokenKind, usize)> {
1957        let mut position = input.current_offset() + prefix_len + 1;
1958        while position < input.len() {
1959            let byte = *input.read_at(position);
1960            if byte == b'"' {
1961                break;
1962            }
1963            if byte == b'\\' {
1964                position += 2;
1965                continue;
1966            }
1967            if position + 1 < input.len() {
1968                let next = *input.read_at(position + 1);
1969                if (byte == b'$' && (is_start_of_identifier(&next) || next == b'{')) || (byte == b'{' && next == b'$') {
1970                    return None;
1971                }
1972            }
1973            position += 1;
1974        }
1975        Some(read_literal_string(input, b'"', prefix_len))
1976    }
1977
1978    fn check_double_quote_body(body: &[u8]) {
1979        for prefix in [b"".as_slice(), b"b", b"B"] {
1980            for leading in [b"".as_slice(), b"ignored "] {
1981                let mut bytes = leading.to_vec();
1982                bytes.extend_from_slice(prefix);
1983                bytes.push(b'"');
1984                bytes.extend_from_slice(body);
1985                let mut input = Input::new(FileId::zero(), &bytes);
1986                input.skip(leading.len());
1987                assert_eq!(
1988                    read_literal_double_quote_string(&input, prefix.len()),
1989                    read_double_quote_reference(&input, prefix.len()),
1990                    "source: {bytes:?}"
1991                );
1992            }
1993        }
1994    }
1995
1996    #[test]
1997    fn double_quote_scan_matches_reference() {
1998        const ALPHABET: [u8; 8] = [b'a', 0xff, b'"', b'\\', b'$', b'{', b'}', 0];
1999        for length in 0..=5 {
2000            for mut value in 0..ALPHABET.len().pow(length) {
2001                let mut body = Vec::new();
2002                for _ in 0..length {
2003                    body.push(ALPHABET[value % ALPHABET.len()]);
2004                    value /= ALPHABET.len();
2005                }
2006                check_double_quote_body(&body);
2007            }
2008        }
2009        for special in [b"\\{$\"".as_slice(), b"{$", b"$\xff", b"\\\\\"", b"\\", b"$1\""] {
2010            let mut body = vec![b'a'; 257];
2011            body.extend_from_slice(special);
2012            check_double_quote_body(&body);
2013        }
2014    }
2015}