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'"', ..] if matches_literal_double_quote_string(&self.input, 1) => {
520                        read_literal_string(&self.input, b'"', 1)
521                    }
522                    [b'b' | b'B', b'"', ..] => (TokenKind::DoubleQuote, 2),
523                    [b'b' | b'B', b'<', b'<']
524                        if self.input.read(4).len() == 4
525                            && self.input.read(4)[3] == b'<'
526                            && matches_start_of_heredoc_document(&self.input, 1) =>
527                    {
528                        let (length, whitespaces, label_length) = read_start_of_heredoc_document(&self.input, false, 1);
529
530                        document_label = self.input.peek(4 + whitespaces, label_length);
531
532                        (TokenKind::DocumentStart(DocumentKind::Heredoc), length)
533                    }
534                    [b'b' | b'B', b'<', b'<']
535                        if self.input.read(4).len() == 4
536                            && self.input.read(4)[3] == b'<'
537                            && matches_start_of_double_quote_heredoc_document(&self.input, 1) =>
538                    {
539                        let (length, whitespaces, label_length) = read_start_of_heredoc_document(&self.input, true, 1);
540
541                        document_label = self.input.peek(5 + whitespaces, label_length);
542
543                        (TokenKind::DocumentStart(DocumentKind::Heredoc), length)
544                    }
545                    [b'b' | b'B', b'<', b'<']
546                        if self.input.read(4).len() == 4
547                            && self.input.read(4)[3] == b'<'
548                            && matches_start_of_nowdoc_document(&self.input, 1) =>
549                    {
550                        let (length, whitespaces, label_length) = read_start_of_nowdoc_document(&self.input, 1);
551
552                        document_label = self.input.peek(5 + whitespaces, label_length);
553
554                        (TokenKind::DocumentStart(DocumentKind::Nowdoc), length)
555                    }
556                    // Regular string literals
557                    [quote @ b'\'', ..] => read_literal_string(&self.input, *quote, 0),
558                    [quote @ b'"', ..] if matches_literal_double_quote_string(&self.input, 0) => {
559                        read_literal_string(&self.input, *quote, 0)
560                    }
561                    [b'"', ..] => (TokenKind::DoubleQuote, 1),
562                    [b'(', ..] => 'parenthesis: {
563                        let mut peek_offset = 1;
564                        while let Some(&b) = self.input.read(peek_offset + 1).get(peek_offset) {
565                            if b.is_ascii_whitespace() {
566                                peek_offset += 1;
567                            } else {
568                                // Check if this byte could start a cast type (case-insensitive)
569                                let lower = b | 0x20; // ASCII lowercase
570                                if !matches!(lower, b'i' | b'b' | b'f' | b'd' | b'r' | b's' | b'a' | b'o' | b'u' | b'v')
571                                {
572                                    break 'parenthesis (TokenKind::LeftParenthesis, 1);
573                                }
574                                break;
575                            }
576                        }
577
578                        for (value, kind) in internal::consts::CAST_TYPES {
579                            if let Some(length) = self.input.match_sequence_ignore_whitespace(value, true) {
580                                break 'parenthesis (kind, length);
581                            }
582                        }
583
584                        (TokenKind::LeftParenthesis, 1)
585                    }
586                    [b'#', ..] => {
587                        let remaining = self.input.peek(1, self.input.len() - self.input.current_offset());
588                        let comment_len = scan_single_line_comment(remaining);
589                        (TokenKind::HashComment, 1 + comment_len)
590                    }
591                    [b'\\', ..] => (TokenKind::NamespaceSeparator, 1),
592                    [start_of_number!(), ..] if self.var_offset_depth > 0 => {
593                        let mut length = 1;
594                        let base = match self.input.read(2) {
595                            [b'0', b'x' | b'X'] => {
596                                length = 2;
597                                16
598                            }
599                            [b'0', b'b' | b'B'] => {
600                                length = 2;
601                                2
602                            }
603                            [b'0', b'o' | b'O'] => {
604                                length = 2;
605                                8
606                            }
607                            _ => 10,
608                        };
609
610                        (TokenKind::OffsetNumber, read_digits_of_base(&self.input, length, base))
611                    }
612                    [b'.', start_of_number!(), ..] if self.var_offset_depth == 0 => {
613                        let mut length = read_digits_of_base(&self.input, 2, 10);
614                        if let float_exponent!() = self.input.peek(length, 1) {
615                            let mut exp_length = length + 1;
616                            if let number_sign!() = self.input.peek(exp_length, 1) {
617                                exp_length += 1;
618                            }
619
620                            let after_exp = read_digits_of_base(&self.input, exp_length, 10);
621                            if after_exp > exp_length {
622                                length = after_exp;
623                            }
624                        }
625
626                        (TokenKind::LiteralFloat, length)
627                    }
628                    [start_of_number!(), ..] => 'number: {
629                        let mut length = 1;
630
631                        let (base, kind): (u8, NumberKind) = match self.input.read(3) {
632                            start_of_binary_number!() => {
633                                length += 1;
634
635                                (2, NumberKind::Integer)
636                            }
637                            start_of_octal_number!() => {
638                                length += 1;
639
640                                (8, NumberKind::Integer)
641                            }
642                            start_of_hexadecimal_number!() => {
643                                length += 1;
644
645                                (16, NumberKind::Integer)
646                            }
647                            start_of_octal_or_float_number!() => (10, NumberKind::OctalOrFloat),
648                            start_of_float_number!() => (10, NumberKind::Float),
649                            _ => (10, NumberKind::IntegerOrFloat),
650                        };
651
652                        if kind != NumberKind::Float {
653                            length = read_digits_of_base(&self.input, length, base);
654
655                            if kind == NumberKind::Integer {
656                                break 'number (TokenKind::LiteralInteger, length);
657                            }
658                        }
659
660                        let is_float = matches!(self.input.peek(length, 3), float_separator!());
661
662                        if !is_float {
663                            if kind == NumberKind::OctalOrFloat
664                                && let Some(invalid_idx) =
665                                    (1..length).find(|&i| matches!(self.input.peek(i, 1), [b'8' | b'9']))
666                            {
667                                let invalid_byte = self.input.peek(invalid_idx, 1)[0];
668                                let start = self.input.current_position();
669                                let invalid_position = Position { offset: start.offset + invalid_idx as u32 };
670                                self.input.consume(length);
671                                return Some(Err(SyntaxError::UnexpectedToken(
672                                    self.file_id(),
673                                    invalid_byte,
674                                    invalid_position,
675                                )));
676                            }
677                            break 'number (TokenKind::LiteralInteger, length);
678                        }
679
680                        if let [b'.'] = self.input.peek(length, 1) {
681                            length += 1;
682                            length = read_digits_of_base(&self.input, length, 10);
683                        }
684
685                        if let float_exponent!() = self.input.peek(length, 1) {
686                            // Only include exponent if there are digits after it
687                            let mut exp_length = length + 1;
688                            if let number_sign!() = self.input.peek(exp_length, 1) {
689                                exp_length += 1;
690                            }
691                            let after_exp = read_digits_of_base(&self.input, exp_length, 10);
692                            if after_exp > exp_length {
693                                // There are digits after the exponent marker
694                                length = after_exp;
695                            }
696                        }
697
698                        (TokenKind::LiteralFloat, length)
699                    }
700                    [b'.', ..] => (TokenKind::Dot, 1),
701                    [unknown_byte, ..] => {
702                        let position = self.input.current_position();
703                        self.input.consume(1);
704
705                        return Some(Err(SyntaxError::UnrecognizedToken(self.file_id(), *unknown_byte, position)));
706                    }
707                    [] => {
708                        // We check for EOF before entering scripting section, so this should be
709                        // unreachable. If we ever land here it means an upstream invariant broke,
710                        // so signal EOF gracefully rather than panicking inside the lexer.
711                        return None;
712                    }
713                };
714
715                self.mode = match token_kind {
716                    TokenKind::DoubleQuote => LexerMode::DoubleQuoteString(Interpolation::None),
717                    TokenKind::Backtick => LexerMode::ShellExecuteString(Interpolation::None),
718                    TokenKind::CloseTag => LexerMode::Inline,
719                    TokenKind::HaltCompiler => LexerMode::Halt(HaltStage::LookingForLeftParenthesis),
720                    TokenKind::DocumentStart(document_kind) => {
721                        let body_offset = self.input.current_offset() + len;
722                        let interpolated = matches!(document_kind, DocumentKind::Heredoc);
723                        let indent = read_document_indentation(&self.input, body_offset, document_label, interpolated);
724
725                        LexerMode::DocumentString(document_kind, document_label, indent, Interpolation::None)
726                    }
727                    _ => LexerMode::Script,
728                };
729
730                let buffer = self.input.consume(len);
731                let end = self.input.current_position();
732
733                Some(Ok(self.token(token_kind, buffer, start, end)))
734            }
735            LexerMode::DoubleQuoteString(interpolation) => match &interpolation {
736                Interpolation::None => {
737                    let start = self.input.current_position();
738
739                    let mut length = 0;
740                    let mut last_was_slash = false;
741                    let mut token_kind = TokenKind::StringPart;
742                    loop {
743                        match self.input.peek(length, 2) {
744                            [b'$', start_of_identifier!(), ..] if !last_was_slash => {
745                                let until_offset = read_until_end_of_variable_interpolation(&self.input, length + 2);
746
747                                self.mode =
748                                    LexerMode::DoubleQuoteString(Interpolation::Until(start.offset + until_offset));
749
750                                break;
751                            }
752                            [b'{', b'$', ..] | [b'$', b'{', ..] if !last_was_slash => {
753                                self.mode = LexerMode::DoubleQuoteString(Interpolation::Brace);
754
755                                break;
756                            }
757                            [b'\\', ..] => {
758                                length += 1;
759
760                                last_was_slash = !last_was_slash;
761                            }
762                            [b'"', ..] if !last_was_slash => {
763                                if length == 0 {
764                                    length += 1;
765                                    token_kind = TokenKind::DoubleQuote;
766
767                                    break;
768                                }
769
770                                break;
771                            }
772                            [_, ..] => {
773                                length += 1;
774                                last_was_slash = false;
775                            }
776                            [] => {
777                                break;
778                            }
779                        }
780                    }
781
782                    let buffer = self.input.consume(length);
783                    let end = self.input.current_position();
784
785                    if TokenKind::DoubleQuote == token_kind {
786                        self.mode = LexerMode::Script;
787                    }
788
789                    Some(Ok(self.token(token_kind, buffer, start, end)))
790                }
791                Interpolation::Until(offset) => {
792                    self.interpolation(Some(*offset), LexerMode::DoubleQuoteString(Interpolation::None))
793                }
794                Interpolation::Brace => self.interpolation(None, LexerMode::DoubleQuoteString(Interpolation::None)),
795            },
796            LexerMode::ShellExecuteString(interpolation) => match &interpolation {
797                Interpolation::None => {
798                    let start = self.input.current_position();
799
800                    let mut length = 0;
801                    let mut last_was_slash = false;
802                    let mut token_kind = TokenKind::StringPart;
803                    loop {
804                        match self.input.peek(length, 2) {
805                            [b'$', start_of_identifier!(), ..] if !last_was_slash => {
806                                let until_offset = read_until_end_of_variable_interpolation(&self.input, length + 2);
807
808                                self.mode =
809                                    LexerMode::ShellExecuteString(Interpolation::Until(start.offset + until_offset));
810
811                                break;
812                            }
813                            [b'{', b'$', ..] | [b'$', b'{', ..] if !last_was_slash => {
814                                self.mode = LexerMode::ShellExecuteString(Interpolation::Brace);
815
816                                break;
817                            }
818                            [b'\\', ..] => {
819                                length += 1;
820                                last_was_slash = !last_was_slash;
821                            }
822                            [b'`', ..] if !last_was_slash => {
823                                if length == 0 {
824                                    length += 1;
825                                    token_kind = TokenKind::Backtick;
826
827                                    break;
828                                }
829
830                                break;
831                            }
832                            [_, ..] => {
833                                length += 1;
834                                last_was_slash = false;
835                            }
836                            [] => {
837                                break;
838                            }
839                        }
840                    }
841
842                    let buffer = self.input.consume(length);
843                    let end = self.input.current_position();
844
845                    if TokenKind::Backtick == token_kind {
846                        self.mode = LexerMode::Script;
847                    }
848
849                    Some(Ok(self.token(token_kind, buffer, start, end)))
850                }
851                Interpolation::Until(offset) => {
852                    self.interpolation(Some(*offset), LexerMode::ShellExecuteString(Interpolation::None))
853                }
854                Interpolation::Brace => self.interpolation(None, LexerMode::ShellExecuteString(Interpolation::None)),
855            },
856            LexerMode::DocumentString(kind, label, indent, interpolation) => match &kind {
857                DocumentKind::Heredoc => match &interpolation {
858                    Interpolation::None => {
859                        let start = self.input.current_position();
860
861                        if indent > 0 && document_body_at_line_start(&self.input) {
862                            let width = document_leading_indent_width(&self.input, indent);
863                            if width > 0 && !document_line_is_closing_marker(&self.input, width, label) {
864                                let buffer = self.input.consume(width);
865                                let end = self.input.current_position();
866
867                                return Some(Ok(self.token(TokenKind::Whitespace, buffer, start, end)));
868                            }
869                        }
870
871                        let mut length = 0;
872                        let mut last_was_slash = false;
873                        let mut only_whitespaces = true;
874                        let mut token_kind = TokenKind::StringPart;
875                        loop {
876                            match self.input.peek(length, 2) {
877                                [b'\r', b'\n'] => {
878                                    if document_next_line_is_closing_marker(&self.input, length + 2, label) {
879                                        return self.document_segment_before_closing_marker(length, 2, start);
880                                    }
881
882                                    length += 2;
883
884                                    break;
885                                }
886                                [b'\n' | b'\r', ..] => {
887                                    if document_next_line_is_closing_marker(&self.input, length + 1, label) {
888                                        return self.document_segment_before_closing_marker(length, 1, start);
889                                    }
890
891                                    length += 1;
892
893                                    break;
894                                }
895                                [byte, ..] if byte.is_ascii_whitespace() => {
896                                    length += 1;
897                                }
898                                [b'$', start_of_identifier!(), ..] if !last_was_slash => {
899                                    let until_offset =
900                                        read_until_end_of_variable_interpolation(&self.input, length + 2);
901
902                                    self.mode = LexerMode::DocumentString(
903                                        kind,
904                                        label,
905                                        indent,
906                                        Interpolation::Until(start.offset + until_offset),
907                                    );
908
909                                    break;
910                                }
911                                [b'{', b'$', ..] | [b'$', b'{', ..] if !last_was_slash => {
912                                    self.mode = LexerMode::DocumentString(kind, label, indent, Interpolation::Brace);
913
914                                    break;
915                                }
916                                [b'\\', ..] => {
917                                    length += 1;
918                                    last_was_slash = !last_was_slash;
919                                    only_whitespaces = false;
920                                }
921                                [_, ..] => {
922                                    if only_whitespaces
923                                        && self.input.peek(length, label.len()) == label
924                                        && self
925                                            .input
926                                            .peek(length + label.len(), 1)
927                                            .first()
928                                            .is_none_or(|c| !is_part_of_identifier(c))
929                                    {
930                                        length += label.len();
931                                        token_kind = TokenKind::DocumentEnd;
932
933                                        break;
934                                    }
935
936                                    length += 1;
937                                    last_was_slash = false;
938                                    only_whitespaces = false;
939                                }
940                                [] => {
941                                    break;
942                                }
943                            }
944                        }
945
946                        let buffer = self.input.consume(length);
947                        let end = self.input.current_position();
948
949                        if TokenKind::DocumentEnd == token_kind {
950                            self.mode = LexerMode::Script;
951                        }
952
953                        Some(Ok(self.token(token_kind, buffer, start, end)))
954                    }
955                    Interpolation::Until(offset) => self.interpolation(
956                        Some(*offset),
957                        LexerMode::DocumentString(kind, label, indent, Interpolation::None),
958                    ),
959                    Interpolation::Brace => {
960                        self.interpolation(None, LexerMode::DocumentString(kind, label, indent, Interpolation::None))
961                    }
962                },
963                DocumentKind::Nowdoc => {
964                    let start = self.input.current_position();
965
966                    if indent > 0 && document_body_at_line_start(&self.input) {
967                        let width = document_leading_indent_width(&self.input, indent);
968                        if width > 0 && !document_line_is_closing_marker(&self.input, width, label) {
969                            let buffer = self.input.consume(width);
970                            let end = self.input.current_position();
971
972                            return Some(Ok(self.token(TokenKind::Whitespace, buffer, start, end)));
973                        }
974                    }
975
976                    let mut length = 0;
977                    let mut terminated = false;
978                    let mut only_whitespaces = true;
979
980                    loop {
981                        match self.input.peek(length, 2) {
982                            [b'\r', b'\n'] => {
983                                if document_next_line_is_closing_marker(&self.input, length + 2, label) {
984                                    return self.document_segment_before_closing_marker(length, 2, start);
985                                }
986
987                                length += 2;
988
989                                break;
990                            }
991                            [b'\n' | b'\r', ..] => {
992                                if document_next_line_is_closing_marker(&self.input, length + 1, label) {
993                                    return self.document_segment_before_closing_marker(length, 1, start);
994                                }
995
996                                length += 1;
997
998                                break;
999                            }
1000                            [byte, ..] if byte.is_ascii_whitespace() => {
1001                                length += 1;
1002                            }
1003                            [_, ..] => {
1004                                if only_whitespaces
1005                                    && self.input.peek(length, label.len()) == label
1006                                    && self
1007                                        .input
1008                                        .peek(length + label.len(), 1)
1009                                        .first()
1010                                        .is_none_or(|c| !is_part_of_identifier(c))
1011                                {
1012                                    length += label.len();
1013                                    terminated = true;
1014
1015                                    break;
1016                                }
1017
1018                                only_whitespaces = false;
1019                                length += 1;
1020                            }
1021                            [] => {
1022                                break;
1023                            }
1024                        }
1025                    }
1026
1027                    let buffer = self.input.consume(length);
1028                    let end = self.input.current_position();
1029
1030                    if terminated {
1031                        self.mode = LexerMode::Script;
1032
1033                        return Some(Ok(self.token(TokenKind::DocumentEnd, buffer, start, end)));
1034                    }
1035
1036                    Some(Ok(self.token(TokenKind::StringPart, buffer, start, end)))
1037                }
1038            },
1039            LexerMode::Halt(stage) => 'halt: {
1040                let start = self.input.current_position();
1041                if let HaltStage::End = stage {
1042                    let buffer = self.input.consume_remaining();
1043                    let end = self.input.current_position();
1044
1045                    break 'halt Some(Ok(self.token(TokenKind::InlineText, buffer, start, end)));
1046                }
1047
1048                let whitespaces = self.input.consume_whitespaces();
1049                if !whitespaces.is_empty() {
1050                    let end = self.input.current_position();
1051
1052                    break 'halt Some(Ok(self.token(TokenKind::Whitespace, whitespaces, start, end)));
1053                }
1054
1055                match &stage {
1056                    HaltStage::LookingForLeftParenthesis => {
1057                        if self.input.is_at(b"(", false) {
1058                            let buffer = self.input.consume(1);
1059                            let end = self.input.current_position();
1060
1061                            self.mode = LexerMode::Halt(HaltStage::LookingForRightParenthesis);
1062
1063                            Some(Ok(self.token(TokenKind::LeftParenthesis, buffer, start, end)))
1064                        } else {
1065                            let byte = self.input.read(1)[0];
1066                            let position = self.input.current_position();
1067                            // Consume the unexpected byte to avoid infinite loops
1068                            self.input.consume(1);
1069                            Some(Err(SyntaxError::UnexpectedToken(self.file_id(), byte, position)))
1070                        }
1071                    }
1072                    HaltStage::LookingForRightParenthesis => {
1073                        if self.input.is_at(b")", false) {
1074                            let buffer = self.input.consume(1);
1075                            let end = self.input.current_position();
1076
1077                            self.mode = LexerMode::Halt(HaltStage::LookingForTerminator);
1078
1079                            Some(Ok(self.token(TokenKind::RightParenthesis, buffer, start, end)))
1080                        } else {
1081                            let byte = self.input.read(1)[0];
1082                            let position = self.input.current_position();
1083                            self.input.consume(1);
1084                            Some(Err(SyntaxError::UnexpectedToken(self.file_id(), byte, position)))
1085                        }
1086                    }
1087                    HaltStage::LookingForTerminator => {
1088                        if self.input.is_at(b";", false) {
1089                            let buffer = self.input.consume(1);
1090                            let end = self.input.current_position();
1091
1092                            self.mode = LexerMode::Halt(HaltStage::End);
1093
1094                            Some(Ok(self.token(TokenKind::Semicolon, buffer, start, end)))
1095                        } else if self.input.is_at(b"?>", false) {
1096                            let buffer = self.input.consume(2);
1097                            let end = self.input.current_position();
1098
1099                            self.mode = LexerMode::Halt(HaltStage::End);
1100
1101                            Some(Ok(self.token(TokenKind::CloseTag, buffer, start, end)))
1102                        } else {
1103                            let byte = self.input.read(1)[0];
1104                            let position = self.input.current_position();
1105                            self.input.consume(1);
1106                            Some(Err(SyntaxError::UnexpectedToken(self.file_id(), byte, position)))
1107                        }
1108                    }
1109                    HaltStage::End => {
1110                        // The `HaltStage::End` arm is reached only after the early-return at the top of
1111                        // this branch consumed the terminating `?>` or EOF; surfacing `None` keeps the
1112                        // lexer total instead of relying on `unreachable!`.
1113                        None
1114                    }
1115                }
1116            }
1117        }
1118    }
1119
1120    /// Fast path for scanning identifiers and keywords.
1121    /// Called when we know the first byte is an identifier start character.
1122    /// Returns (TokenKind, length) to allow proper mode switching.
1123    #[inline]
1124    fn scan_identifier_or_keyword_info(&self) -> (TokenKind, usize) {
1125        let (length, ended_with_slash) = self.input.scan_identifier(0);
1126
1127        if !ended_with_slash && matches!(self.input.peek(length, 1), [b'(']) {
1128            match length {
1129                6 if self.input.is_at(b"public(set)", true) => {
1130                    return (TokenKind::PublicSet, 11);
1131                }
1132                7 if self.input.is_at(b"private(set)", true) => {
1133                    return (TokenKind::PrivateSet, 12);
1134                }
1135                9 if self.input.is_at(b"protected(set)", true) => {
1136                    return (TokenKind::ProtectedSet, 14);
1137                }
1138                _ => {}
1139            }
1140        }
1141
1142        if !ended_with_slash {
1143            if let Some(kind) = internal::keyword::lookup_keyword(self.input.read(length)) {
1144                return (kind, length);
1145            }
1146
1147            return (TokenKind::Identifier, length);
1148        }
1149
1150        self.scan_qualified_identifier_info(length)
1151    }
1152
1153    // Keep qualified-name scanning out of the common identifier/keyword path.
1154    #[inline(never)]
1155    fn scan_qualified_identifier_info(&self, mut length: usize) -> (TokenKind, usize) {
1156        let mut slashes = 0;
1157        let mut last_was_slash = false;
1158        loop {
1159            match self.input.peek(length, 1) {
1160                [b'a'..=b'z' | b'A'..=b'Z' | b'_' | 0x80..=0xFF] if last_was_slash => {
1161                    length += 1;
1162                    last_was_slash = false;
1163                }
1164                [b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | 0x80..=0xFF] if !last_was_slash => {
1165                    length += 1;
1166                }
1167                [b'\\'] if !self.interpolating || self.brace_interpolating => {
1168                    if last_was_slash {
1169                        length -= 1;
1170                        slashes -= 1;
1171                        last_was_slash = false;
1172                        break;
1173                    }
1174
1175                    length += 1;
1176                    slashes += 1;
1177                    last_was_slash = true;
1178                }
1179                _ => {
1180                    break;
1181                }
1182            }
1183        }
1184
1185        if last_was_slash {
1186            length -= 1;
1187            slashes -= 1;
1188        }
1189
1190        let kind = if slashes > 0 { TokenKind::QualifiedIdentifier } else { TokenKind::Identifier };
1191
1192        (kind, length)
1193    }
1194
1195    #[inline]
1196    fn token(&self, kind: TokenKind, value: &'input [u8], start: Position, _end: Position) -> Token<'input> {
1197        Token { kind, start, value }
1198    }
1199
1200    /// Emits the last body segment before a heredoc/nowdoc closing marker. The
1201    /// line terminator immediately preceding the marker is not part of the
1202    /// string value, so it is surfaced as `Whitespace` trivia: when there is
1203    /// preceding content the terminator is queued to follow the `StringPart`,
1204    /// otherwise the terminator is emitted on its own.
1205    fn document_segment_before_closing_marker(
1206        &mut self,
1207        content_length: usize,
1208        terminator_length: usize,
1209        start: Position,
1210    ) -> Option<Result<Token<'input>, SyntaxError>> {
1211        if content_length == 0 {
1212            let buffer = self.input.consume(terminator_length);
1213            let end = self.input.current_position();
1214
1215            return Some(Ok(self.token(TokenKind::Whitespace, buffer, start, end)));
1216        }
1217
1218        let content = self.input.consume(content_length);
1219        let content_end = self.input.current_position();
1220        let terminator = self.input.consume(terminator_length);
1221        let terminator_end = self.input.current_position();
1222
1223        if self.interpolating {
1224            self.buffer.push_back(self.token(TokenKind::StringPart, content, start, content_end));
1225
1226            return Some(Ok(self.token(TokenKind::Whitespace, terminator, content_end, terminator_end)));
1227        }
1228
1229        self.buffer.push_back(self.token(TokenKind::Whitespace, terminator, content_end, terminator_end));
1230
1231        Some(Ok(self.token(TokenKind::StringPart, content, start, content_end)))
1232    }
1233
1234    fn peek_string_varname_label(&self) -> bool {
1235        let Some(&first) = self.input.read(1).first() else {
1236            return false;
1237        };
1238
1239        if !IDENT_START_TABLE[first as usize] {
1240            return false;
1241        }
1242
1243        let (label_length, _) = self.input.scan_identifier(0);
1244
1245        matches!(self.input.read(label_length + 1).get(label_length), Some(b'[' | b'}'))
1246    }
1247
1248    #[inline]
1249    fn interpolation(
1250        &mut self,
1251        end_offset: Option<u32>,
1252        post_interpolation_mode: LexerMode<'input>,
1253    ) -> Option<Result<Token<'input>, SyntaxError>> {
1254        self.interpolation_depth += 1;
1255        if self.interpolation_depth > Self::MAX_INTERPOLATION_DEPTH {
1256            self.interpolation_depth -= 1;
1257
1258            return Some(Err(SyntaxError::RecursionLimitExceeded(self.file_id(), self.input.current_position())));
1259        }
1260
1261        let brace = end_offset.is_none();
1262        let mut brace_depth = 0u32;
1263        self.mode = LexerMode::Script;
1264
1265        let was_interpolating = self.interpolating;
1266        self.interpolating = true;
1267        let was_brace_interpolating = self.brace_interpolating;
1268        // For brace interpolation ({$...}), allow qualified identifiers with backslashes.
1269        self.brace_interpolating = brace;
1270        let was_var_offset_depth = self.var_offset_depth;
1271        self.var_offset_depth = 0;
1272        let was_expect_string_varname = self.expect_string_varname;
1273        self.expect_string_varname = false;
1274
1275        let pending_error = loop {
1276            match self.advance() {
1277                Some(Ok(token)) => {
1278                    let token_start = token.start.offset;
1279                    let token_end = token_start + token.value.len() as u32;
1280                    let is_final_token = match end_offset {
1281                        Some(end_offset) => token_start <= end_offset && end_offset <= token_end,
1282                        None => match token.kind {
1283                            TokenKind::LeftBrace | TokenKind::DollarLeftBrace => {
1284                                brace_depth += 1;
1285                                false
1286                            }
1287                            TokenKind::RightBrace => {
1288                                brace_depth = brace_depth.saturating_sub(1);
1289                                brace_depth == 0
1290                            }
1291                            _ => false,
1292                        },
1293                    };
1294
1295                    if brace {
1296                        if token.kind == TokenKind::DollarLeftBrace && self.peek_string_varname_label() {
1297                            self.expect_string_varname = true;
1298                        }
1299                    } else {
1300                        match token.kind {
1301                            TokenKind::LeftBracket => self.var_offset_depth += 1,
1302                            TokenKind::RightBracket => {
1303                                self.var_offset_depth = self.var_offset_depth.saturating_sub(1);
1304                            }
1305                            _ => {}
1306                        }
1307                    }
1308
1309                    self.buffer.push_back(token);
1310
1311                    if is_final_token {
1312                        break None;
1313                    }
1314                }
1315                Some(Err(error)) => break Some(error),
1316                None => break None,
1317            }
1318        };
1319
1320        self.mode = post_interpolation_mode;
1321        self.interpolating = was_interpolating;
1322        self.brace_interpolating = was_brace_interpolating;
1323        self.var_offset_depth = was_var_offset_depth;
1324        self.expect_string_varname = was_expect_string_varname;
1325        self.interpolation_depth -= 1;
1326
1327        if let Some(error) = pending_error {
1328            return Some(Err(error));
1329        }
1330
1331        self.advance()
1332    }
1333}
1334
1335impl HasFileId for Lexer<'_> {
1336    #[inline]
1337    fn file_id(&self) -> FileId {
1338        self.input.file_id()
1339    }
1340}
1341
1342#[inline]
1343fn matches_start_of_heredoc_document(input: &Input, prefix_len: usize) -> bool {
1344    let total = input.len();
1345    let base = input.current_offset();
1346
1347    // Start after the prefix (if any) and the fixed opener (3 bytes).
1348    let mut length = 3 + prefix_len;
1349    // Consume any following whitespace.
1350    while base + length < total && input.read_at(base + length).is_ascii_whitespace() {
1351        length += 1;
1352    }
1353
1354    // The next byte must be a valid start-of-identifier.
1355    if base + length >= total || !is_start_of_identifier(input.read_at(base + length)) {
1356        return false;
1357    }
1358    length += 1; // Include that identifier start.
1359
1360    // Now continue reading identifier characters until a newline is found.
1361    loop {
1362        let pos = base + length;
1363        if pos >= total {
1364            return false; // Unexpected EOF
1365        }
1366
1367        let byte = *input.read_at(pos);
1368        if byte == b'\n' {
1369            return true; // Newline found: valid heredoc opener.
1370        } else if byte == b'\r' {
1371            // Handle CRLF: treat '\r' followed by '\n' as a newline as well.
1372            return pos + 1 < total && *input.read_at(pos + 1) == b'\n';
1373        } else if is_part_of_identifier(input.read_at(pos)) {
1374            length += 1;
1375        } else {
1376            return false; // Unexpected character.
1377        }
1378    }
1379}
1380
1381#[inline]
1382fn matches_start_of_double_quote_heredoc_document(input: &Input, prefix_len: usize) -> bool {
1383    let total = input.len();
1384    let base = input.current_offset();
1385
1386    // Start after the prefix (if any) and the fixed opener (3 bytes), then skip any whitespace.
1387    let mut length = 3 + prefix_len;
1388    while base + length < total && input.read_at(base + length).is_ascii_whitespace() {
1389        length += 1;
1390    }
1391
1392    // Next, expect an opening double quote.
1393    if base + length >= total || *input.read_at(base + length) != b'"' {
1394        return false;
1395    }
1396    length += 1;
1397
1398    // The following byte must be a valid start-of-identifier.
1399    if base + length >= total || !is_start_of_identifier(input.read_at(base + length)) {
1400        return false;
1401    }
1402    length += 1;
1403
1404    // Now scan the label. For double‑quoted heredoc, a terminating double quote is required.
1405    let mut terminated = false;
1406    loop {
1407        let pos = base + length;
1408        if pos >= total {
1409            return false;
1410        }
1411        let byte = input.read_at(pos);
1412        if *byte == b'\n' {
1413            // End of line: valid only if a closing double quote was encountered.
1414            return terminated;
1415        } else if *byte == b'\r' {
1416            // Handle CRLF sequences.
1417            return terminated && pos + 1 < total && *input.read_at(pos + 1) == b'\n';
1418        } else if !terminated && is_part_of_identifier(byte) {
1419            length += 1;
1420        } else if !terminated && *byte == b'"' {
1421            terminated = true;
1422            length += 1;
1423        } else {
1424            return false;
1425        }
1426    }
1427}
1428
1429#[inline]
1430fn matches_start_of_nowdoc_document(input: &Input, prefix_len: usize) -> bool {
1431    let total = input.len();
1432    let base = input.current_offset();
1433
1434    // Start after the prefix (if any) and the fixed opener (3 bytes) and skip whitespace.
1435    let mut length = 3 + prefix_len;
1436    while base + length < total && input.read_at(base + length).is_ascii_whitespace() {
1437        length += 1;
1438    }
1439
1440    // Now, the next byte must be a single quote.
1441    if base + length >= total || *input.read_at(base + length) != b'\'' {
1442        return false;
1443    }
1444    length += 1;
1445
1446    // The following byte must be a valid start-of-identifier.
1447    if base + length >= total || !is_start_of_identifier(input.read_at(base + length)) {
1448        return false;
1449    }
1450    length += 1;
1451
1452    // Read the label until a newline. A terminating single quote is required.
1453    let mut terminated = false;
1454    loop {
1455        let pos = base + length;
1456        if pos >= total {
1457            return false;
1458        }
1459        let byte = *input.read_at(pos);
1460        if byte == b'\n' {
1461            return terminated;
1462        } else if byte == b'\r' {
1463            return terminated && pos + 1 < total && *input.read_at(pos + 1) == b'\n';
1464        } else if !terminated && is_part_of_identifier(&byte) {
1465            length += 1;
1466        } else if !terminated && byte == b'\'' {
1467            terminated = true;
1468            length += 1;
1469        } else {
1470            return false;
1471        }
1472    }
1473}
1474
1475#[inline]
1476fn matches_literal_double_quote_string(input: &Input, prefix_len: usize) -> bool {
1477    let total = input.len();
1478    let base = input.current_offset();
1479
1480    // Start after the prefix (if any) and the initial double-quote.
1481    let mut pos = base + 1 + prefix_len;
1482    loop {
1483        if pos >= total {
1484            // Reached EOF: assume literal is complete.
1485            return true;
1486        }
1487        let byte = *input.read_at(pos);
1488        if byte == b'"' {
1489            // Encounter a closing double quote.
1490            return true;
1491        }
1492        if byte == b'\\' {
1493            // Skip an escape sequence: assume that the backslash and the escaped character form a pair.
1494            pos += 2;
1495            continue;
1496        }
1497
1498        // Check for variable interpolation or complex expression start:
1499        // If two-byte sequences match either "$" followed by a start-of-identifier or "{" and "$", then return false.
1500        if pos + 1 < total {
1501            let next = *input.read_at(pos + 1);
1502            if (byte == b'$' && (is_start_of_identifier(&next) || next == b'{')) || (byte == b'{' && next == b'$') {
1503                return false;
1504            }
1505        }
1506        pos += 1;
1507    }
1508}
1509
1510/// Measures the indentation of a heredoc/nowdoc closing marker by scanning the
1511/// body line by line, starting at `body_offset`, until the first line whose
1512/// leading whitespace is followed by the closing `label`. The returned width is
1513/// the number of leading space/tab bytes on that line; PHP 7.3 flexible
1514/// heredoc/nowdoc strips up to that many columns from every body line.
1515fn read_document_indentation(input: &Input, body_offset: usize, label: &[u8], interpolated: bool) -> usize {
1516    let total = input.len();
1517    let base = input.current_offset();
1518    let mut position = body_offset;
1519    loop {
1520        let mut width = 0;
1521        while position < total && matches!(*input.read_at(position), b' ' | b'\t') {
1522            width += 1;
1523            position += 1;
1524        }
1525
1526        if label_matches_at(input, position, label, total) {
1527            return width;
1528        }
1529
1530        let mut last_was_slash = false;
1531        while position < total && !matches!(*input.read_at(position), b'\n' | b'\r') {
1532            let byte = *input.read_at(position);
1533            let next = (position + 1 < total).then(|| *input.read_at(position + 1));
1534
1535            if interpolated && !last_was_slash {
1536                if (byte == b'$' && next == Some(b'{')) || (byte == b'{' && next == Some(b'$')) {
1537                    let from = (position - base) + 2;
1538                    position = base + read_until_end_of_brace_interpolation(input, from) as usize;
1539
1540                    continue;
1541                }
1542
1543                if byte == b'$' && next.is_some_and(|c| is_start_of_identifier(&c)) {
1544                    let from = (position - base) + 2;
1545                    position = base + read_until_end_of_variable_interpolation(input, from) as usize;
1546
1547                    continue;
1548                }
1549            }
1550
1551            last_was_slash = byte == b'\\' && !last_was_slash;
1552            position += 1;
1553        }
1554
1555        if position >= total {
1556            return 0;
1557        }
1558
1559        if *input.read_at(position) == b'\r' && position + 1 < total && *input.read_at(position + 1) == b'\n' {
1560            position += 2;
1561        } else {
1562            position += 1;
1563        }
1564    }
1565}
1566
1567/// Whether the closing `label` appears at the absolute `position`, not followed
1568/// by an identifier byte (so `EOT` matches but `EOTish` does not).
1569fn label_matches_at(input: &Input, position: usize, label: &[u8], total: usize) -> bool {
1570    if position + label.len() > total {
1571        return false;
1572    }
1573
1574    let mut index = 0;
1575    while index < label.len() {
1576        if *input.read_at(position + index) != label[index] {
1577            return false;
1578        }
1579        index += 1;
1580    }
1581
1582    let after = position + label.len();
1583    after >= total || !is_part_of_identifier(input.read_at(after))
1584}
1585
1586/// Whether the lexer is positioned at the start of a heredoc/nowdoc body line,
1587/// i.e. the previous byte is a line terminator.
1588#[inline]
1589fn document_body_at_line_start(input: &Input) -> bool {
1590    let offset = input.current_offset();
1591    offset == 0 || matches!(*input.read_at(offset - 1), b'\n' | b'\r')
1592}
1593
1594/// Counts the leading space/tab bytes at the current position, capped at `indent`.
1595#[inline]
1596fn document_leading_indent_width(input: &Input, indent: usize) -> usize {
1597    let mut width = 0;
1598    while width < indent && matches!(input.peek(width, 1), [b' ' | b'\t']) {
1599        width += 1;
1600    }
1601
1602    width
1603}
1604
1605/// Whether the current line, after `width` leading whitespace bytes, is the
1606/// closing marker. The marker's own indentation is left attached to the
1607/// `DocumentEnd` token rather than stripped as trivia.
1608#[inline]
1609fn document_line_is_closing_marker(input: &Input, width: usize, label: &[u8]) -> bool {
1610    input.peek(width, label.len()) == label
1611        && input.peek(width + label.len(), 1).first().is_none_or(|byte| !is_part_of_identifier(byte))
1612}
1613
1614/// Whether the line beginning at relative `offset` (just past a line terminator)
1615/// is the closing marker. Used to recognise the terminator that immediately
1616/// precedes the marker, which a heredoc/nowdoc drops from the string value.
1617#[inline]
1618fn document_next_line_is_closing_marker(input: &Input, offset: usize, label: &[u8]) -> bool {
1619    let mut width = 0;
1620    while matches!(input.peek(offset + width, 1), [b' ' | b'\t']) {
1621        width += 1;
1622    }
1623
1624    input.peek(offset + width, label.len()) == label
1625        && input.peek(offset + width + label.len(), 1).first().is_none_or(|byte| !is_part_of_identifier(byte))
1626}
1627
1628#[inline]
1629fn read_start_of_heredoc_document(input: &Input, double_quoted: bool, prefix_len: usize) -> (usize, usize, usize) {
1630    let total = input.len();
1631    let base = input.current_offset();
1632
1633    // Start reading after the prefix (if any) and the fixed opener (3 bytes).
1634    let mut pos = base + 3 + prefix_len;
1635    let mut whitespaces = 0;
1636    while pos < total && input.read_at(pos).is_ascii_whitespace() {
1637        whitespaces += 1;
1638        pos += 1;
1639    }
1640
1641    // The label (or delimiter) starts after:
1642    //   prefix + 3 bytes + whitespace bytes + an extra offset:
1643    //      if double-quoted: 2 bytes (opening and closing quotes around the label)
1644    //      else: 1 byte.
1645    let mut length = 3 + prefix_len + whitespaces + if double_quoted { 2 } else { 1 };
1646
1647    let mut label_length = 1; // Start with at least one byte for the label.
1648    let mut terminated = false; // For double-quoted heredoc, to track the closing quote.
1649    loop {
1650        let pos = base + length;
1651        // Bail out gracefully if we run past the input or hit a byte that the caller's
1652        // earlier validation should have rejected: returning the accumulated `(length,
1653        // whitespaces, label_length)` lets the lexer produce a malformed-heredoc token
1654        // instead of panicking.
1655        if pos >= total {
1656            return (length, whitespaces, label_length);
1657        }
1658
1659        let byte = *input.read_at(pos);
1660        if byte == b'\n' {
1661            // Newline ends the label.
1662            length += 1;
1663            return (length, whitespaces, label_length);
1664        } else if byte == b'\r' {
1665            // Handle CRLF sequences
1666            if pos + 1 < total && *input.read_at(pos + 1) == b'\n' {
1667                length += 2;
1668            } else {
1669                length += 1;
1670            }
1671            return (length, whitespaces, label_length);
1672        } else if is_part_of_identifier(&byte) && (!double_quoted || !terminated) {
1673            // For both unquoted and double-quoted (before the closing quote) heredoc,
1674            // a valid identifier character is part of the label.
1675            length += 1;
1676            label_length += 1;
1677        } else if double_quoted && !terminated && byte == b'"' {
1678            // In a double-quoted heredoc, a double quote terminates the label.
1679            length += 1;
1680            terminated = true;
1681        } else {
1682            // Malformed heredoc label: stop scanning and let the caller surface a parse error.
1683            return (length, whitespaces, label_length);
1684        }
1685    }
1686}
1687
1688#[inline]
1689fn read_start_of_nowdoc_document(input: &Input, prefix_len: usize) -> (usize, usize, usize) {
1690    let total = input.len();
1691    let base = input.current_offset();
1692
1693    let mut pos = base + 3 + prefix_len;
1694    let mut whitespaces = 0;
1695    while pos < total && input.read_at(pos).is_ascii_whitespace() {
1696        whitespaces += 1;
1697        pos += 1;
1698    }
1699
1700    // For nowdoc, the fixed extra offset is always 2.
1701    let mut length = 3 + prefix_len + whitespaces + 2;
1702
1703    let mut label_length = 1;
1704    let mut terminated = false;
1705    loop {
1706        let pos = base + length;
1707        if pos >= total {
1708            // Bail out gracefully on truncated input; surfacing the accumulated state lets the
1709            // lexer report a parse error instead of panicking.
1710            return (length, whitespaces, label_length);
1711        }
1712        let byte = *input.read_at(pos);
1713
1714        if byte == b'\n' {
1715            // A newline indicates the end of the label.
1716            length += 1;
1717            return (length, whitespaces, label_length);
1718        } else if byte == b'\r' {
1719            // Handle CRLF sequences
1720            if pos + 1 < total && *input.read_at(pos + 1) == b'\n' {
1721                length += 2;
1722            } else {
1723                length += 1;
1724            }
1725            return (length, whitespaces, label_length);
1726        } else if is_part_of_identifier(&byte) && !terminated {
1727            // For nowdoc, identifier characters contribute to the label until terminated.
1728            length += 1;
1729            label_length += 1;
1730        } else if !terminated && byte == b'\'' {
1731            // A single quote terminates the nowdoc label.
1732            length += 1;
1733            terminated = true;
1734        } else {
1735            // Malformed nowdoc label: stop scanning and let the caller surface a parse error.
1736            return (length, whitespaces, label_length);
1737        }
1738    }
1739}
1740
1741#[inline]
1742fn read_literal_string(input: &Input, quote: u8, prefix_len: usize) -> (TokenKind, usize) {
1743    let total = input.len();
1744    let start = input.current_offset();
1745    let skip = prefix_len + 1; // prefix + opening quote
1746    let mut length = skip;
1747
1748    let bytes = input.peek(skip, total - start - skip);
1749    loop {
1750        let scan_start = length - skip;
1751        match memchr2(quote, b'\\', &bytes[scan_start..]) {
1752            Some(pos) => {
1753                let abs_pos = scan_start + pos;
1754                let byte = bytes[abs_pos];
1755
1756                if byte == b'\\' {
1757                    length = skip + abs_pos + 2;
1758                    if length > total - start {
1759                        return (TokenKind::PartialLiteralString, total - start);
1760                    }
1761                } else {
1762                    length = skip + abs_pos + 1; // +1 for the closing quote
1763                    return (TokenKind::LiteralString, length);
1764                }
1765            }
1766            None => {
1767                // No quote or backslash found - EOF
1768                return (TokenKind::PartialLiteralString, total - start);
1769            }
1770        }
1771    }
1772}
1773
1774#[inline]
1775fn read_until_end_of_variable_interpolation(input: &Input, from: usize) -> u32 {
1776    let total = input.len();
1777    let base = input.current_offset();
1778    // `offset` is relative to the current position.
1779    let mut offset = from;
1780
1781    loop {
1782        let abs = base + offset;
1783        if abs >= total {
1784            // End of input.
1785            break;
1786        }
1787
1788        // Pattern 1: If the current byte is part of an identifier, simply advance.
1789        if is_part_of_identifier(input.read_at(abs)) {
1790            offset += 1;
1791            continue;
1792        }
1793
1794        // Pattern 2: If the current byte is a '[' then we enter a bracketed interpolation.
1795        if *input.read_at(abs) == b'[' {
1796            offset += 1;
1797            let mut nesting = 0;
1798            loop {
1799                let abs_inner = base + offset;
1800                if abs_inner >= total {
1801                    break;
1802                }
1803                let b = input.read_at(abs_inner);
1804                if *b == b']' {
1805                    offset += 1;
1806                    if nesting == 0 {
1807                        break;
1808                    }
1809
1810                    nesting -= 1;
1811                } else if *b == b'[' {
1812                    offset += 1;
1813                    nesting += 1;
1814                } else if b.is_ascii_whitespace() {
1815                    // Do not include whitespace.
1816                    break;
1817                } else {
1818                    offset += 1;
1819                }
1820            }
1821            // When bracketed interpolation is processed, exit the loop.
1822            break;
1823        }
1824
1825        // Pattern 3: Check for "->" followed by a valid identifier start.
1826        if base + offset + 2 < total
1827            && *input.read_at(abs) == b'-'
1828            && *input.read_at(base + offset + 1) == b'>'
1829            && is_start_of_identifier(input.read_at(base + offset + 2))
1830        {
1831            offset += 3;
1832            // Consume any following identifier characters.
1833            while base + offset < total && is_part_of_identifier(input.read_at(base + offset)) {
1834                offset += 1;
1835            }
1836            break;
1837        }
1838
1839        // Pattern 4: Check for "?->" followed by a valid identifier start.
1840        if base + offset + 3 < total
1841            && *input.read_at(abs) == b'?'
1842            && *input.read_at(base + offset + 1) == b'-'
1843            && *input.read_at(base + offset + 2) == b'>'
1844            && is_start_of_identifier(input.read_at(base + offset + 3))
1845        {
1846            offset += 4;
1847            while base + offset < total && is_part_of_identifier(input.read_at(base + offset)) {
1848                offset += 1;
1849            }
1850            break;
1851        }
1852
1853        // None of the expected patterns matched: exit the loop.
1854        break;
1855    }
1856
1857    offset as u32
1858}
1859
1860/// Scan forward from a `{$`/`${` brace interpolation to the offset just past
1861/// its matching `}` (tracking `{`/`}` nesting), or to end-of-input if the
1862/// interpolation is never closed.
1863///
1864/// The expression inside `{$...}` is real PHP and may contain nested string
1865/// literals - e.g. `"{$a["key"]}"` - whose own `{`/`}` bytes must not be
1866/// counted as interpolation braces (consider `"{$a["}"]}"`). Nested `'`, `"`,
1867/// and `` ` `` strings are therefore skipped wholesale, honouring `\` escapes,
1868/// so a `}` inside a nested string neither closes the interpolation early nor
1869/// is miscounted.
1870#[inline]
1871fn read_until_end_of_brace_interpolation(input: &Input, from: usize) -> u32 {
1872    let total = input.len();
1873    let base = input.current_offset();
1874    let mut offset = from;
1875    let mut nesting = 0;
1876
1877    loop {
1878        let abs = base + offset;
1879        if abs >= total {
1880            break;
1881        }
1882        match *input.read_at(abs) {
1883            b'}' => {
1884                offset += 1;
1885                if nesting == 0 {
1886                    break;
1887                }
1888
1889                nesting -= 1;
1890            }
1891            b'{' => {
1892                offset += 1;
1893                nesting += 1;
1894            }
1895            quote @ (b'\'' | b'"' | b'`') => {
1896                offset += 1;
1897                loop {
1898                    let abs = base + offset;
1899                    if abs >= total {
1900                        break;
1901                    }
1902                    match *input.read_at(abs) {
1903                        b'\\' => offset += 2,
1904                        b if b == quote => {
1905                            offset += 1;
1906                            break;
1907                        }
1908                        _ => offset += 1,
1909                    }
1910                }
1911            }
1912            _ => {
1913                offset += 1;
1914            }
1915        }
1916    }
1917
1918    offset as u32
1919}
1920
1921/// Scan a multi-line comment using SIMD-accelerated search.
1922/// Returns Some(length) including the closing */, or None if unterminated.
1923#[inline]
1924fn scan_multi_line_comment(bytes: &[u8]) -> Option<usize> {
1925    // Use SIMD to find */ quickly
1926    memmem::find(bytes, b"*/").map(|pos| pos + 2)
1927}
1928
1929/// Scan a single-line comment using SIMD-accelerated search.
1930/// Returns the length of the comment body (not including the //).
1931/// Stops at newline or ?>.
1932#[inline]
1933fn scan_single_line_comment(bytes: &[u8]) -> usize {
1934    let mut pos = 0;
1935    while pos < bytes.len() {
1936        match memchr::memchr3(b'\n', b'\r', b'?', &bytes[pos..]) {
1937            Some(offset) => {
1938                let found_pos = pos + offset;
1939                match bytes[found_pos] {
1940                    b'\n' | b'\r' => return found_pos,
1941                    b'?' => {
1942                        // Check if it's ?>
1943                        if found_pos + 1 < bytes.len() && bytes[found_pos + 1] == b'>' {
1944                            // Also check for whitespace before ?>
1945                            if found_pos > 0 && bytes[found_pos - 1].is_ascii_whitespace() {
1946                                return found_pos - 1;
1947                            }
1948                            return found_pos;
1949                        }
1950                        // Not ?>, continue searching
1951                        pos = found_pos + 1;
1952                    }
1953                    // `memchr3` only matches the three bytes we asked for; any other value here would
1954                    // indicate a memchr bug. Treat it as end-of-comment so the lexer keeps making progress.
1955                    _ => return found_pos,
1956                }
1957            }
1958            None => return bytes.len(),
1959        }
1960    }
1961
1962    bytes.len()
1963}