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 matches!(byte, b'\n' | b'\r') {
1367            return true; // Newline found: valid heredoc opener.
1368        } else if is_part_of_identifier(input.read_at(pos)) {
1369            length += 1;
1370        } else {
1371            return false; // Unexpected character.
1372        }
1373    }
1374}
1375
1376#[inline]
1377fn matches_start_of_double_quote_heredoc_document(input: &Input, prefix_len: usize) -> bool {
1378    let total = input.len();
1379    let base = input.current_offset();
1380
1381    // Start after the prefix (if any) and the fixed opener (3 bytes), then skip any whitespace.
1382    let mut length = 3 + prefix_len;
1383    while base + length < total && input.read_at(base + length).is_ascii_whitespace() {
1384        length += 1;
1385    }
1386
1387    // Next, expect an opening double quote.
1388    if base + length >= total || *input.read_at(base + length) != b'"' {
1389        return false;
1390    }
1391    length += 1;
1392
1393    // The following byte must be a valid start-of-identifier.
1394    if base + length >= total || !is_start_of_identifier(input.read_at(base + length)) {
1395        return false;
1396    }
1397    length += 1;
1398
1399    // Now scan the label. For double‑quoted heredoc, a terminating double quote is required.
1400    let mut terminated = false;
1401    loop {
1402        let pos = base + length;
1403        if pos >= total {
1404            return false;
1405        }
1406        let byte = input.read_at(pos);
1407        if matches!(*byte, b'\n' | b'\r') {
1408            // End of line: valid only if a closing double quote was encountered.
1409            return terminated;
1410        } else if !terminated && is_part_of_identifier(byte) {
1411            length += 1;
1412        } else if !terminated && *byte == b'"' {
1413            terminated = true;
1414            length += 1;
1415        } else {
1416            return false;
1417        }
1418    }
1419}
1420
1421#[inline]
1422fn matches_start_of_nowdoc_document(input: &Input, prefix_len: usize) -> bool {
1423    let total = input.len();
1424    let base = input.current_offset();
1425
1426    // Start after the prefix (if any) and the fixed opener (3 bytes) and skip whitespace.
1427    let mut length = 3 + prefix_len;
1428    while base + length < total && input.read_at(base + length).is_ascii_whitespace() {
1429        length += 1;
1430    }
1431
1432    // Now, the next byte must be a single quote.
1433    if base + length >= total || *input.read_at(base + length) != b'\'' {
1434        return false;
1435    }
1436    length += 1;
1437
1438    // The following byte must be a valid start-of-identifier.
1439    if base + length >= total || !is_start_of_identifier(input.read_at(base + length)) {
1440        return false;
1441    }
1442    length += 1;
1443
1444    // Read the label until a newline. A terminating single quote is required.
1445    let mut terminated = false;
1446    loop {
1447        let pos = base + length;
1448        if pos >= total {
1449            return false;
1450        }
1451        let byte = *input.read_at(pos);
1452        if matches!(byte, b'\n' | b'\r') {
1453            return terminated;
1454        } else if !terminated && is_part_of_identifier(&byte) {
1455            length += 1;
1456        } else if !terminated && byte == b'\'' {
1457            terminated = true;
1458            length += 1;
1459        } else {
1460            return false;
1461        }
1462    }
1463}
1464
1465#[inline]
1466fn read_literal_double_quote_string(input: &Input, prefix_len: usize) -> Option<(TokenKind, usize)> {
1467    let bytes = input.read_remaining();
1468    let mut start = prefix_len + 1;
1469    while let Some(offset) = memchr::memchr3(b'"', b'\\', b'$', &bytes[start..]) {
1470        let position = start + offset;
1471        match bytes[position] {
1472            b'"' => return Some((TokenKind::LiteralString, position + 1)),
1473            b'\\' => start = (position + 2).min(bytes.len()),
1474            _ => {
1475                // A brace before this scan's start belongs to the escape just skipped.
1476                if (position > start && bytes[position - 1] == b'{')
1477                    || bytes.get(position + 1).is_some_and(|next| is_start_of_identifier(next) || *next == b'{')
1478                {
1479                    return None;
1480                }
1481                start = position + 1;
1482            }
1483        }
1484    }
1485
1486    Some((TokenKind::PartialLiteralString, bytes.len()))
1487}
1488
1489/// Measures the indentation of a heredoc/nowdoc closing marker by scanning the
1490/// body line by line, starting at `body_offset`, until the first line whose
1491/// leading whitespace is followed by the closing `label`. The returned width is
1492/// the number of leading space/tab bytes on that line; PHP 7.3 flexible
1493/// heredoc/nowdoc strips up to that many columns from every body line.
1494fn read_document_indentation(input: &Input, body_offset: usize, label: &[u8], interpolated: bool) -> usize {
1495    let total = input.len();
1496    let base = input.current_offset();
1497    let mut position = body_offset;
1498    loop {
1499        let mut width = 0;
1500        while position < total && matches!(*input.read_at(position), b' ' | b'\t') {
1501            width += 1;
1502            position += 1;
1503        }
1504
1505        if label_matches_at(input, position, label, total) {
1506            return width;
1507        }
1508
1509        let mut last_was_slash = false;
1510        while position < total && !matches!(*input.read_at(position), b'\n' | b'\r') {
1511            let byte = *input.read_at(position);
1512            let next = (position + 1 < total).then(|| *input.read_at(position + 1));
1513
1514            if interpolated && !last_was_slash {
1515                if (byte == b'$' && next == Some(b'{')) || (byte == b'{' && next == Some(b'$')) {
1516                    let from = (position - base) + 2;
1517                    position = base + read_until_end_of_brace_interpolation(input, from) as usize;
1518
1519                    continue;
1520                }
1521
1522                if byte == b'$' && next.is_some_and(|c| is_start_of_identifier(&c)) {
1523                    let from = (position - base) + 2;
1524                    position = base + read_until_end_of_variable_interpolation(input, from) as usize;
1525
1526                    continue;
1527                }
1528            }
1529
1530            last_was_slash = byte == b'\\' && !last_was_slash;
1531            position += 1;
1532        }
1533
1534        if position >= total {
1535            return 0;
1536        }
1537
1538        if *input.read_at(position) == b'\r' && position + 1 < total && *input.read_at(position + 1) == b'\n' {
1539            position += 2;
1540        } else {
1541            position += 1;
1542        }
1543    }
1544}
1545
1546/// Whether the closing `label` appears at the absolute `position`, not followed
1547/// by an identifier byte (so `EOT` matches but `EOTish` does not).
1548fn label_matches_at(input: &Input, position: usize, label: &[u8], total: usize) -> bool {
1549    if position + label.len() > total {
1550        return false;
1551    }
1552
1553    let mut index = 0;
1554    while index < label.len() {
1555        if *input.read_at(position + index) != label[index] {
1556            return false;
1557        }
1558        index += 1;
1559    }
1560
1561    let after = position + label.len();
1562    after >= total || !is_part_of_identifier(input.read_at(after))
1563}
1564
1565/// Whether the lexer is positioned at the start of a heredoc/nowdoc body line,
1566/// i.e. the previous byte is a line terminator.
1567#[inline]
1568fn document_body_at_line_start(input: &Input) -> bool {
1569    let offset = input.current_offset();
1570    offset == 0 || matches!(*input.read_at(offset - 1), b'\n' | b'\r')
1571}
1572
1573/// Counts the leading space/tab bytes at the current position, capped at `indent`.
1574#[inline]
1575fn document_leading_indent_width(input: &Input, indent: usize) -> usize {
1576    let mut width = 0;
1577    while width < indent && matches!(input.peek(width, 1), [b' ' | b'\t']) {
1578        width += 1;
1579    }
1580
1581    width
1582}
1583
1584/// Whether the current line, after `width` leading whitespace bytes, is the
1585/// closing marker. The marker's own indentation is left attached to the
1586/// `DocumentEnd` token rather than stripped as trivia.
1587#[inline]
1588fn document_line_is_closing_marker(input: &Input, width: usize, label: &[u8]) -> bool {
1589    input.peek(width, label.len()) == label
1590        && input.peek(width + label.len(), 1).first().is_none_or(|byte| !is_part_of_identifier(byte))
1591}
1592
1593/// Whether the line beginning at relative `offset` (just past a line terminator)
1594/// is the closing marker. Used to recognise the terminator that immediately
1595/// precedes the marker, which a heredoc/nowdoc drops from the string value.
1596#[inline]
1597fn document_next_line_is_closing_marker(input: &Input, offset: usize, label: &[u8]) -> bool {
1598    let mut width = 0;
1599    while matches!(input.peek(offset + width, 1), [b' ' | b'\t']) {
1600        width += 1;
1601    }
1602
1603    input.peek(offset + width, label.len()) == label
1604        && input.peek(offset + width + label.len(), 1).first().is_none_or(|byte| !is_part_of_identifier(byte))
1605}
1606
1607#[inline]
1608fn read_start_of_heredoc_document(input: &Input, double_quoted: bool, prefix_len: usize) -> (usize, usize, usize) {
1609    let total = input.len();
1610    let base = input.current_offset();
1611
1612    // Start reading after the prefix (if any) and the fixed opener (3 bytes).
1613    let mut pos = base + 3 + prefix_len;
1614    let mut whitespaces = 0;
1615    while pos < total && input.read_at(pos).is_ascii_whitespace() {
1616        whitespaces += 1;
1617        pos += 1;
1618    }
1619
1620    // The label (or delimiter) starts after:
1621    //   prefix + 3 bytes + whitespace bytes + an extra offset:
1622    //      if double-quoted: 2 bytes (opening and closing quotes around the label)
1623    //      else: 1 byte.
1624    let mut length = 3 + prefix_len + whitespaces + if double_quoted { 2 } else { 1 };
1625
1626    let mut label_length = 1; // Start with at least one byte for the label.
1627    let mut terminated = false; // For double-quoted heredoc, to track the closing quote.
1628    loop {
1629        let pos = base + length;
1630        // Bail out gracefully if we run past the input or hit a byte that the caller's
1631        // earlier validation should have rejected: returning the accumulated `(length,
1632        // whitespaces, label_length)` lets the lexer produce a malformed-heredoc token
1633        // instead of panicking.
1634        if pos >= total {
1635            return (length, whitespaces, label_length);
1636        }
1637
1638        let byte = *input.read_at(pos);
1639        if byte == b'\n' {
1640            // Newline ends the label.
1641            length += 1;
1642            return (length, whitespaces, label_length);
1643        } else if byte == b'\r' {
1644            // Handle CRLF sequences
1645            if pos + 1 < total && *input.read_at(pos + 1) == b'\n' {
1646                length += 2;
1647            } else {
1648                length += 1;
1649            }
1650            return (length, whitespaces, label_length);
1651        } else if is_part_of_identifier(&byte) && (!double_quoted || !terminated) {
1652            // For both unquoted and double-quoted (before the closing quote) heredoc,
1653            // a valid identifier character is part of the label.
1654            length += 1;
1655            label_length += 1;
1656        } else if double_quoted && !terminated && byte == b'"' {
1657            // In a double-quoted heredoc, a double quote terminates the label.
1658            length += 1;
1659            terminated = true;
1660        } else {
1661            // Malformed heredoc label: stop scanning and let the caller surface a parse error.
1662            return (length, whitespaces, label_length);
1663        }
1664    }
1665}
1666
1667#[inline]
1668fn read_start_of_nowdoc_document(input: &Input, prefix_len: usize) -> (usize, usize, usize) {
1669    let total = input.len();
1670    let base = input.current_offset();
1671
1672    let mut pos = base + 3 + prefix_len;
1673    let mut whitespaces = 0;
1674    while pos < total && input.read_at(pos).is_ascii_whitespace() {
1675        whitespaces += 1;
1676        pos += 1;
1677    }
1678
1679    // For nowdoc, the fixed extra offset is always 2.
1680    let mut length = 3 + prefix_len + whitespaces + 2;
1681
1682    let mut label_length = 1;
1683    let mut terminated = false;
1684    loop {
1685        let pos = base + length;
1686        if pos >= total {
1687            // Bail out gracefully on truncated input; surfacing the accumulated state lets the
1688            // lexer report a parse error instead of panicking.
1689            return (length, whitespaces, label_length);
1690        }
1691        let byte = *input.read_at(pos);
1692
1693        if byte == b'\n' {
1694            // A newline indicates the end of the label.
1695            length += 1;
1696            return (length, whitespaces, label_length);
1697        } else if byte == b'\r' {
1698            // Handle CRLF sequences
1699            if pos + 1 < total && *input.read_at(pos + 1) == b'\n' {
1700                length += 2;
1701            } else {
1702                length += 1;
1703            }
1704            return (length, whitespaces, label_length);
1705        } else if is_part_of_identifier(&byte) && !terminated {
1706            // For nowdoc, identifier characters contribute to the label until terminated.
1707            length += 1;
1708            label_length += 1;
1709        } else if !terminated && byte == b'\'' {
1710            // A single quote terminates the nowdoc label.
1711            length += 1;
1712            terminated = true;
1713        } else {
1714            // Malformed nowdoc label: stop scanning and let the caller surface a parse error.
1715            return (length, whitespaces, label_length);
1716        }
1717    }
1718}
1719
1720#[inline]
1721fn read_literal_string(input: &Input, quote: u8, prefix_len: usize) -> (TokenKind, usize) {
1722    let total = input.len();
1723    let start = input.current_offset();
1724    let skip = prefix_len + 1; // prefix + opening quote
1725    let mut length = skip;
1726
1727    let bytes = input.peek(skip, total - start - skip);
1728    loop {
1729        let scan_start = length - skip;
1730        match memchr2(quote, b'\\', &bytes[scan_start..]) {
1731            Some(pos) => {
1732                let abs_pos = scan_start + pos;
1733                let byte = bytes[abs_pos];
1734
1735                if byte == b'\\' {
1736                    length = skip + abs_pos + 2;
1737                    if length > total - start {
1738                        return (TokenKind::PartialLiteralString, total - start);
1739                    }
1740                } else {
1741                    length = skip + abs_pos + 1; // +1 for the closing quote
1742                    return (TokenKind::LiteralString, length);
1743                }
1744            }
1745            None => {
1746                // No quote or backslash found - EOF
1747                return (TokenKind::PartialLiteralString, total - start);
1748            }
1749        }
1750    }
1751}
1752
1753#[inline]
1754fn read_until_end_of_variable_interpolation(input: &Input, from: usize) -> u32 {
1755    let total = input.len();
1756    let base = input.current_offset();
1757    // `offset` is relative to the current position.
1758    let mut offset = from;
1759
1760    loop {
1761        let abs = base + offset;
1762        if abs >= total {
1763            // End of input.
1764            break;
1765        }
1766
1767        // Pattern 1: If the current byte is part of an identifier, simply advance.
1768        if is_part_of_identifier(input.read_at(abs)) {
1769            offset += 1;
1770            continue;
1771        }
1772
1773        // Pattern 2: If the current byte is a '[' then we enter a bracketed interpolation.
1774        if *input.read_at(abs) == b'[' {
1775            offset += 1;
1776            let mut nesting = 0;
1777            loop {
1778                let abs_inner = base + offset;
1779                if abs_inner >= total {
1780                    break;
1781                }
1782                let b = input.read_at(abs_inner);
1783                if *b == b']' {
1784                    offset += 1;
1785                    if nesting == 0 {
1786                        break;
1787                    }
1788
1789                    nesting -= 1;
1790                } else if *b == b'[' {
1791                    offset += 1;
1792                    nesting += 1;
1793                } else if b.is_ascii_whitespace() {
1794                    // Do not include whitespace.
1795                    break;
1796                } else {
1797                    offset += 1;
1798                }
1799            }
1800            // When bracketed interpolation is processed, exit the loop.
1801            break;
1802        }
1803
1804        // Pattern 3: Check for "->" followed by a valid identifier start.
1805        if base + offset + 2 < total
1806            && *input.read_at(abs) == b'-'
1807            && *input.read_at(base + offset + 1) == b'>'
1808            && is_start_of_identifier(input.read_at(base + offset + 2))
1809        {
1810            offset += 3;
1811            // Consume any following identifier characters.
1812            while base + offset < total && is_part_of_identifier(input.read_at(base + offset)) {
1813                offset += 1;
1814            }
1815            break;
1816        }
1817
1818        // Pattern 4: Check for "?->" followed by a valid identifier start.
1819        if base + offset + 3 < total
1820            && *input.read_at(abs) == b'?'
1821            && *input.read_at(base + offset + 1) == b'-'
1822            && *input.read_at(base + offset + 2) == b'>'
1823            && is_start_of_identifier(input.read_at(base + offset + 3))
1824        {
1825            offset += 4;
1826            while base + offset < total && is_part_of_identifier(input.read_at(base + offset)) {
1827                offset += 1;
1828            }
1829            break;
1830        }
1831
1832        // None of the expected patterns matched: exit the loop.
1833        break;
1834    }
1835
1836    offset as u32
1837}
1838
1839/// Scan forward from a `{$`/`${` brace interpolation to the offset just past
1840/// its matching `}` (tracking `{`/`}` nesting), or to end-of-input if the
1841/// interpolation is never closed.
1842///
1843/// The expression inside `{$...}` is real PHP and may contain nested string
1844/// literals - e.g. `"{$a["key"]}"` - whose own `{`/`}` bytes must not be
1845/// counted as interpolation braces (consider `"{$a["}"]}"`). Nested `'`, `"`,
1846/// and `` ` `` strings are therefore skipped wholesale, honouring `\` escapes,
1847/// so a `}` inside a nested string neither closes the interpolation early nor
1848/// is miscounted.
1849#[inline]
1850fn read_until_end_of_brace_interpolation(input: &Input, from: usize) -> u32 {
1851    let total = input.len();
1852    let base = input.current_offset();
1853    let mut offset = from;
1854    let mut nesting = 0;
1855
1856    loop {
1857        let abs = base + offset;
1858        if abs >= total {
1859            break;
1860        }
1861        match *input.read_at(abs) {
1862            b'}' => {
1863                offset += 1;
1864                if nesting == 0 {
1865                    break;
1866                }
1867
1868                nesting -= 1;
1869            }
1870            b'{' => {
1871                offset += 1;
1872                nesting += 1;
1873            }
1874            quote @ (b'\'' | b'"' | b'`') => {
1875                offset += 1;
1876                loop {
1877                    let abs = base + offset;
1878                    if abs >= total {
1879                        break;
1880                    }
1881                    match *input.read_at(abs) {
1882                        b'\\' => offset += 2,
1883                        b if b == quote => {
1884                            offset += 1;
1885                            break;
1886                        }
1887                        _ => offset += 1,
1888                    }
1889                }
1890            }
1891            _ => {
1892                offset += 1;
1893            }
1894        }
1895    }
1896
1897    offset as u32
1898}
1899
1900/// Scan a multi-line comment using SIMD-accelerated search.
1901/// Returns Some(length) including the closing */, or None if unterminated.
1902#[inline]
1903fn scan_multi_line_comment(bytes: &[u8]) -> Option<usize> {
1904    // Use SIMD to find */ quickly
1905    memmem::find(bytes, b"*/").map(|pos| pos + 2)
1906}
1907
1908/// Scan a single-line comment using SIMD-accelerated search.
1909/// Returns the length of the comment body (not including the //).
1910/// Stops at newline or ?>.
1911#[inline]
1912fn scan_single_line_comment(bytes: &[u8]) -> usize {
1913    let mut pos = 0;
1914    while pos < bytes.len() {
1915        match memchr::memchr3(b'\n', b'\r', b'?', &bytes[pos..]) {
1916            Some(offset) => {
1917                let found_pos = pos + offset;
1918                match bytes[found_pos] {
1919                    b'\n' | b'\r' => return found_pos,
1920                    b'?' => {
1921                        // Check if it's ?>
1922                        if found_pos + 1 < bytes.len() && bytes[found_pos + 1] == b'>' {
1923                            // Also check for whitespace before ?>
1924                            if found_pos > 0 && bytes[found_pos - 1].is_ascii_whitespace() {
1925                                return found_pos - 1;
1926                            }
1927                            return found_pos;
1928                        }
1929                        // Not ?>, continue searching
1930                        pos = found_pos + 1;
1931                    }
1932                    // `memchr3` only matches the three bytes we asked for; any other value here would
1933                    // indicate a memchr bug. Treat it as end-of-comment so the lexer keeps making progress.
1934                    _ => return found_pos,
1935                }
1936            }
1937            None => return bytes.len(),
1938        }
1939    }
1940
1941    bytes.len()
1942}
1943
1944#[cfg(test)]
1945mod tests {
1946    use super::*;
1947
1948    fn read_double_quote_reference(input: &Input, prefix_len: usize) -> Option<(TokenKind, usize)> {
1949        let mut position = input.current_offset() + prefix_len + 1;
1950        while position < input.len() {
1951            let byte = *input.read_at(position);
1952            if byte == b'"' {
1953                break;
1954            }
1955            if byte == b'\\' {
1956                position += 2;
1957                continue;
1958            }
1959            if position + 1 < input.len() {
1960                let next = *input.read_at(position + 1);
1961                if (byte == b'$' && (is_start_of_identifier(&next) || next == b'{')) || (byte == b'{' && next == b'$') {
1962                    return None;
1963                }
1964            }
1965            position += 1;
1966        }
1967        Some(read_literal_string(input, b'"', prefix_len))
1968    }
1969
1970    fn check_double_quote_body(body: &[u8]) {
1971        for prefix in [b"".as_slice(), b"b", b"B"] {
1972            for leading in [b"".as_slice(), b"ignored "] {
1973                let mut bytes = leading.to_vec();
1974                bytes.extend_from_slice(prefix);
1975                bytes.push(b'"');
1976                bytes.extend_from_slice(body);
1977                let mut input = Input::new(FileId::zero(), &bytes);
1978                input.skip(leading.len());
1979                assert_eq!(
1980                    read_literal_double_quote_string(&input, prefix.len()),
1981                    read_double_quote_reference(&input, prefix.len()),
1982                    "source: {bytes:?}"
1983                );
1984            }
1985        }
1986    }
1987
1988    #[test]
1989    fn double_quote_scan_matches_reference() {
1990        const ALPHABET: [u8; 8] = [b'a', 0xff, b'"', b'\\', b'$', b'{', b'}', 0];
1991        for length in 0..=5 {
1992            for mut value in 0..ALPHABET.len().pow(length) {
1993                let mut body = Vec::new();
1994                for _ in 0..length {
1995                    body.push(ALPHABET[value % ALPHABET.len()]);
1996                    value /= ALPHABET.len();
1997                }
1998                check_double_quote_body(&body);
1999            }
2000        }
2001        for special in [b"\\{$\"".as_slice(), b"{$", b"$\xff", b"\\\\\"", b"\\", b"$1\""] {
2002            let mut body = vec![b'a'; 257];
2003            body.extend_from_slice(special);
2004            check_double_quote_body(&body);
2005        }
2006    }
2007}