Skip to main content

js_parse/
lexer.rs

1//! The lexer: ECMAScript 2025 source text to [`Token`]s.
2//!
3//! Two productions cannot be decided by a lexer alone and are therefore
4//! re-scanned on demand, exactly like upstream `js_parse_regexp` /
5//! `js_parse_template_part`:
6//!
7//! * a `/` is a division punctuator until the parser asks for a regular
8//!   expression literal with [`Lexer::re_scan_regex`];
9//! * `}` closes a block or resumes a template literal, decided by
10//!   [`Lexer::re_scan_template_continue`].
11//!
12//! Positions are byte offsets plus 1-based line/UTF-16 column numbers, which is
13//! what `SyntaxError` locations report.
14
15use crate::error::{LexError, Result};
16use crate::token::{
17    BigIntLiteral, Keyword, NumberLiteral, Position, Punct, Span, TemplateKind, TemplateToken,
18    Token, TokenKind,
19};
20use crate::unicode_id::{is_id_continue, is_id_start};
21
22/// A streaming lexer over one source text.
23///
24/// `Clone` is implemented deliberately: the parser snapshots the lexer to
25/// backtrack (arrow-function cover grammar), and cloning is a handful of words.
26#[derive(Clone)]
27pub struct Lexer<'a> {
28    src: &'a str,
29    bytes: &'a [u8],
30    pos: usize,
31    line: u32,
32    column: u32,
33    strict: bool,
34    legacy_octal: bool,
35    /// A high surrogate seen in an escape, waiting for its low half.
36    ///
37    /// `"\ud83d\ude00"` spells one code point as two escapes, and the pairing has to
38    /// survive between them, so the pending half lives here rather than being local to
39    /// one escape.
40    pending_high_surrogate: Option<u32>,
41}
42
43/// Every punctuator, longest first so that a prefix test picks the longest form.
44const PUNCTUATORS: &[(&str, Punct)] = &[
45    (">>>=", Punct::UShrEq),
46    ("...", Punct::Ellipsis),
47    ("===", Punct::EqEqEq),
48    ("!==", Punct::NotEqEq),
49    ("**=", Punct::StarStarEq),
50    ("<<=", Punct::ShlEq),
51    (">>=", Punct::ShrEq),
52    (">>>", Punct::UShr),
53    ("&&=", Punct::AmpAmpEq),
54    ("||=", Punct::PipePipeEq),
55    ("??=", Punct::QuestionQuestionEq),
56    ("=>", Punct::Arrow),
57    ("&=", Punct::AmpEq),
58    ("|=", Punct::PipeEq),
59    ("^=", Punct::CaretEq),
60    ("==", Punct::EqEq),
61    ("!=", Punct::NotEq),
62    ("<=", Punct::LtEq),
63    (">=", Punct::GtEq),
64    ("+=", Punct::PlusEq),
65    ("-=", Punct::MinusEq),
66    ("*=", Punct::StarEq),
67    ("/=", Punct::SlashEq),
68    ("%=", Punct::PercentEq),
69    ("**", Punct::StarStar),
70    ("++", Punct::PlusPlus),
71    ("--", Punct::MinusMinus),
72    ("<<", Punct::Shl),
73    (">>", Punct::Shr),
74    ("&&", Punct::AmpAmp),
75    ("||", Punct::PipePipe),
76    ("??", Punct::QuestionQuestion),
77    ("?.", Punct::QuestionDot),
78    ("{", Punct::LBrace),
79    ("}", Punct::RBrace),
80    ("(", Punct::LParen),
81    (")", Punct::RParen),
82    ("[", Punct::LBracket),
83    ("]", Punct::RBracket),
84    (";", Punct::Semicolon),
85    (",", Punct::Comma),
86    ("<", Punct::Lt),
87    (">", Punct::Gt),
88    ("+", Punct::Plus),
89    ("-", Punct::Minus),
90    ("*", Punct::Star),
91    ("/", Punct::Slash),
92    ("%", Punct::Percent),
93    ("&", Punct::Amp),
94    ("|", Punct::Pipe),
95    ("^", Punct::Caret),
96    ("!", Punct::Bang),
97    ("~", Punct::Tilde),
98    ("?", Punct::Question),
99    (":", Punct::Colon),
100    ("=", Punct::Eq),
101    (".", Punct::Dot),
102    ("#", Punct::Hash),
103];
104
105impl<'a> Lexer<'a> {
106    /// Create a lexer positioned at the beginning of `src`.
107    pub fn new(src: &'a str) -> Lexer<'a> {
108        Lexer {
109            src,
110            bytes: src.as_bytes(),
111            pos: 0,
112            line: 1,
113            column: 1,
114            strict: false,
115            legacy_octal: false,
116            pending_high_surrogate: None,
117        }
118    }
119
120    /// Enable strict-mode lexical rules (octal escapes become syntax errors).
121    pub fn set_strict(&mut self, strict: bool) {
122        self.strict = strict;
123    }
124
125    /// Whether strict-mode lexical rules are active.
126    pub fn is_strict(&self) -> bool {
127        self.strict
128    }
129
130    /// Current position of the cursor.
131    pub fn position(&self) -> Position {
132        Position {
133            offset: self.pos as u32,
134            line: self.line,
135            column: self.column,
136        }
137    }
138
139    /// The source text being lexed.
140    pub fn source(&self) -> &'a str {
141        self.src
142    }
143
144    /// Whether the token most recently returned by [`Lexer::next_token`]
145    /// contained an Annex B legacy octal escape (`"\101"`).
146    ///
147    /// The flag is reset by every `next_token` call, so it always describes the
148    /// token currently held by the caller. The parser uses it because strictness
149    /// is only known once the directive prologue has been read, which happens
150    /// after the offending literal was already scanned.
151    pub fn had_legacy_octal(&self) -> bool {
152        self.legacy_octal
153    }
154
155    /// Scan the next token.
156    pub fn next_token(&mut self) -> Result<Token> {
157        self.legacy_octal = false;
158        let newline_before = self.skip_trivia()?;
159        let start = self.position();
160        let Some(c) = self.peek_char() else {
161            return Ok(Token {
162                kind: TokenKind::Eof,
163                span: Span::new(start, start),
164                newline_before,
165            });
166        };
167        let kind = self.scan_token(c)?;
168        Ok(Token {
169            kind,
170            span: Span::new(start, self.position()),
171            newline_before,
172        })
173    }
174
175    /// Scan every remaining token (tests and tooling; the parser drives the
176    /// lexer one token at a time).
177    pub fn tokenize(mut self) -> Result<Vec<Token>> {
178        let mut out = Vec::new();
179        loop {
180            let token = self.next_token()?;
181            let done = token.is_eof();
182            out.push(token);
183            if done {
184                return Ok(out);
185            }
186        }
187    }
188
189    // -- cursor ------------------------------------------------------------
190
191    fn peek_char(&self) -> Option<char> {
192        self.src[self.pos..].chars().next()
193    }
194
195    fn peek_char_at(&self, offset: usize) -> Option<char> {
196        self.src.get(self.pos + offset..)?.chars().next()
197    }
198
199    fn peek_byte(&self) -> Option<u8> {
200        self.bytes.get(self.pos).copied()
201    }
202
203    fn bump(&mut self) -> Option<char> {
204        let c = self.peek_char()?;
205        self.pos += c.len_utf8();
206        match c {
207            '\n' | '\u{2028}' | '\u{2029}' => {
208                self.line += 1;
209                self.column = 1;
210            }
211            '\r' => {
212                // `\r\n` counts as a single line terminator: the `\n` half is
213                // absorbed here so callers never see a double increment.
214                if self.bytes.get(self.pos) == Some(&b'\n') {
215                    self.pos += 1;
216                }
217                self.line += 1;
218                self.column = 1;
219            }
220            _ => self.column += c.len_utf16() as u32,
221        }
222        Some(c)
223    }
224
225    fn reset_to(&mut self, position: Position) {
226        self.pos = position.offset as usize;
227        self.line = position.line;
228        self.column = position.column;
229    }
230
231    fn error(&self, message: impl Into<String>, start: Position) -> LexError {
232        LexError::new(message, Span::new(start, self.position()))
233    }
234
235    // -- trivia ------------------------------------------------------------
236
237    /// Skip whitespace, line terminators and comments; report whether a line
238    /// terminator was crossed.
239    fn skip_trivia(&mut self) -> Result<bool> {
240        let mut newline = false;
241        // A hashbang line is only allowed at offset 0 (Annex B / ES2023).
242        if self.pos == 0 && self.src.starts_with("#!") {
243            while let Some(c) = self.peek_char() {
244                if is_line_terminator(c) {
245                    break;
246                }
247                self.bump();
248            }
249        }
250        loop {
251            let Some(c) = self.peek_char() else {
252                return Ok(newline);
253            };
254            match c {
255                ' ' | '\t' | '\u{0b}' | '\u{0c}' => {
256                    self.bump();
257                }
258                c if is_line_terminator(c) => {
259                    newline = true;
260                    self.bump();
261                }
262                c if c.is_whitespace() || c == '\u{feff}' => {
263                    // Unicode space separators (`Zs`) and the BOM.
264                    self.bump();
265                }
266                '/' => match self.peek_char_at(1) {
267                    Some('/') => {
268                        self.bump();
269                        self.bump();
270                        while let Some(c) = self.peek_char() {
271                            if is_line_terminator(c) {
272                                break;
273                            }
274                            self.bump();
275                        }
276                    }
277                    Some('*') => {
278                        let start = self.position();
279                        self.bump();
280                        self.bump();
281                        loop {
282                            match self.peek_char() {
283                                None => return Err(self.error("unterminated comment", start)),
284                                Some('*') if self.peek_char_at(1) == Some('/') => {
285                                    self.bump();
286                                    self.bump();
287                                    break;
288                                }
289                                Some(c) => {
290                                    if is_line_terminator(c) {
291                                        newline = true;
292                                    }
293                                    self.bump();
294                                }
295                            }
296                        }
297                    }
298                    _ => return Ok(newline),
299                },
300                _ => return Ok(newline),
301            }
302        }
303    }
304
305    // -- tokens ------------------------------------------------------------
306
307    fn scan_token(&mut self, c: char) -> Result<TokenKind> {
308        if is_id_start(c) || c == '\\' {
309            return self.scan_identifier();
310        }
311        if c.is_ascii_digit() {
312            return self.scan_number();
313        }
314        match c {
315            '.' if self.peek_char_at(1).is_some_and(|d| d.is_ascii_digit()) => self.scan_number(),
316            '"' | '\'' => self.scan_string(c),
317            '`' => {
318                let start = self.position();
319                self.bump();
320                let chunk = self.scan_template_chunk(start, true)?;
321                Ok(TokenKind::Template(chunk))
322            }
323            _ => self.scan_punct(c),
324        }
325    }
326
327    fn scan_punct(&mut self, c: char) -> Result<TokenKind> {
328        let start = self.position();
329        for (text, punct) in PUNCTUATORS {
330            if !self.src[self.pos..].starts_with(text) {
331                continue;
332            }
333            // `?.` is only a punctuator when the next character is not a
334            // decimal digit (`a?.5:b` means `a ? .5 : b`).
335            if *punct == Punct::QuestionDot
336                && self.peek_char_at(2).is_some_and(|d| d.is_ascii_digit())
337            {
338                continue;
339            }
340            for _ in 0..text.len() {
341                self.bump();
342            }
343            return Ok(TokenKind::Punct(*punct));
344        }
345        Err(self.error(
346            format!("unexpected character '{}'", c.escape_debug()),
347            start,
348        ))
349    }
350
351    // -- identifiers -------------------------------------------------------
352
353    fn scan_identifier(&mut self) -> Result<TokenKind> {
354        let start = self.position();
355        let mut name = String::new();
356        let mut first = true;
357        while let Some(c) = self.peek_char() {
358            let ch = if c == '\\' {
359                if self.peek_char_at(1) != Some('u') {
360                    return Err(self.error("invalid escape sequence in identifier", start));
361                }
362                self.bump();
363                self.bump();
364                let escaped =
365                    char::from_u32(self.scan_unicode_escape_body(start)?).unwrap_or('\u{fffd}');
366                let ok = if first {
367                    is_id_start(escaped)
368                } else {
369                    is_id_continue(escaped)
370                };
371                if !ok {
372                    return Err(self.error("invalid Unicode escape sequence", start));
373                }
374                escaped
375            } else if (first && is_id_start(c)) || (!first && is_id_continue(c)) {
376                self.bump();
377                c
378            } else {
379                break;
380            };
381            name.push(ch);
382            first = false;
383        }
384        if name.is_empty() {
385            return Err(self.error("unexpected character", start));
386        }
387        if let Some(keyword) = Keyword::lookup(&name) {
388            return Ok(TokenKind::Keyword(keyword));
389        }
390        Ok(TokenKind::Ident(name))
391    }
392
393    // -- numbers -----------------------------------------------------------
394
395    fn scan_number(&mut self) -> Result<TokenKind> {
396        let start = self.position();
397        // Radix prefixes.
398        if self.peek_byte() == Some(b'0') {
399            match self.bytes.get(self.pos + 1).map(u8::to_ascii_lowercase) {
400                Some(b'x') | Some(b'o') | Some(b'b') => {
401                    let radix = match self.bytes[self.pos + 1].to_ascii_lowercase() {
402                        b'x' => 16,
403                        b'o' => 8,
404                        _ => 2,
405                    };
406                    self.bump();
407                    self.bump();
408                    let mut digits = String::new();
409                    let count = self.scan_digits(radix, &mut digits, start)?;
410                    if count == 0 {
411                        return Err(self.error("invalid number literal", start));
412                    }
413                    return self.finish_radix_literal(digits, radix, start);
414                }
415                Some(b'0'..=b'9') => return self.scan_legacy_number(start),
416                _ => {}
417            }
418        }
419
420        let mut digits = String::new();
421        let mut has_fraction = false;
422        let mut has_exponent = false;
423
424        // Integer part (may be empty for `.5`).
425        if self.peek_char() != Some('.') {
426            let count = self.scan_digits(10, &mut digits, start)?;
427            if count == 0 {
428                return Err(self.error("invalid number literal", start));
429            }
430        }
431        if self.peek_char() == Some('.') {
432            has_fraction = true;
433            digits.push('.');
434            self.bump();
435            let _ = self.scan_digits(10, &mut digits, start)?;
436        }
437        if matches!(self.peek_char(), Some('e') | Some('E')) {
438            has_exponent = true;
439            digits.push('e');
440            self.bump();
441            if matches!(self.peek_char(), Some('+') | Some('-')) {
442                let sign = self.peek_char().expect("checked above");
443                digits.push(sign);
444                self.bump();
445            }
446            let mut exponent = String::new();
447            let count = self.scan_digits(10, &mut exponent, start)?;
448            if count == 0 {
449                return Err(self.error("invalid number literal", start));
450            }
451            digits.push_str(&exponent);
452        }
453        if self.peek_char() == Some('n') {
454            if has_fraction || has_exponent {
455                return Err(self.error("invalid BigInt literal", start));
456            }
457            self.bump();
458            self.ensure_literal_boundary(start)?;
459            return Ok(TokenKind::BigInt(BigIntLiteral { digits, radix: 10 }));
460        }
461        self.ensure_literal_boundary(start)?;
462        Ok(TokenKind::Number(number_from_decimal(&digits)))
463    }
464
465    /// `0` followed by more digits: legacy octal (`017`) or a
466    /// NonOctalDecimalIntegerLiteral (`019`), both Annex B.
467    fn scan_legacy_number(&mut self, start: Position) -> Result<TokenKind> {
468        let mut text = String::new();
469        let mut all_octal = true;
470        while let Some(c) = self.peek_char() {
471            if !c.is_ascii_digit() {
472                break;
473            }
474            if c > '7' {
475                all_octal = false;
476            }
477            text.push(c);
478            self.bump();
479        }
480        if matches!(
481            self.peek_char(),
482            Some('.') | Some('e') | Some('E') | Some('_')
483        ) {
484            // `08.5`, `08e1`, `0_1` are ordinary decimal literals / errors; hand
485            // back to the general scanner by re-reading the leading `0`.
486            self.reset_to(start);
487            self.legacy_octal = true;
488            self.bump();
489            let mut digits = String::from("0");
490            let mut rest = String::new();
491            self.scan_digits(10, &mut rest, start)?;
492            digits.push_str(&rest);
493            let mut has_fraction = false;
494            let mut has_exponent = false;
495            if self.peek_char() == Some('.') {
496                has_fraction = true;
497                digits.push('.');
498                self.bump();
499                self.scan_digits(10, &mut digits, start)?;
500            }
501            if matches!(self.peek_char(), Some('e') | Some('E')) {
502                has_exponent = true;
503                digits.push('e');
504                self.bump();
505                if matches!(self.peek_char(), Some('+') | Some('-')) {
506                    let sign = self.peek_char().expect("checked above");
507                    digits.push(sign);
508                    self.bump();
509                }
510                let mut exponent = String::new();
511                let count = self.scan_digits(10, &mut exponent, start)?;
512                if count == 0 {
513                    return Err(self.error("invalid number literal", start));
514                }
515                digits.push_str(&exponent);
516            }
517            if self.peek_char() == Some('n') {
518                if has_fraction || has_exponent || text.len() > 1 {
519                    return Err(self.error("invalid BigInt literal", start));
520                }
521                self.bump();
522                return Ok(TokenKind::BigInt(BigIntLiteral { digits, radix: 10 }));
523            }
524            self.ensure_literal_boundary(start)?;
525            return Ok(TokenKind::Number(number_from_decimal(&digits)));
526        }
527        if self.peek_char() == Some('n') {
528            // `0n` is legal, `01n` / `08n` are not.
529            if text.len() > 1 {
530                return Err(self.error("invalid BigInt literal", start));
531            }
532            self.bump();
533            return Ok(TokenKind::BigInt(BigIntLiteral {
534                digits: "0".to_string(),
535                radix: 10,
536            }));
537        }
538        self.ensure_literal_boundary(start)?;
539        // `017` and `019` are both Annex B legacy literals, forbidden in strict
540        // mode.
541        self.legacy_octal = true;
542        let value = if all_octal {
543            radix_digits_to_f64(&text, 8)
544        } else {
545            radix_digits_to_f64(&text, 10)
546        };
547        Ok(TokenKind::Number(number_from_f64(value)))
548    }
549
550    fn finish_radix_literal(
551        &mut self,
552        digits: String,
553        radix: u32,
554        start: Position,
555    ) -> Result<TokenKind> {
556        if self.peek_char() == Some('n') {
557            self.bump();
558            self.ensure_literal_boundary(start)?;
559            return Ok(TokenKind::BigInt(BigIntLiteral { digits, radix }));
560        }
561        self.ensure_literal_boundary(start)?;
562        Ok(TokenKind::Number(number_from_f64(radix_digits_to_f64(
563            &digits, radix,
564        ))))
565    }
566
567    /// Scan digits of `radix`, accepting `_` separators. Returns the digit count.
568    fn scan_digits(&mut self, radix: u32, out: &mut String, start: Position) -> Result<usize> {
569        let mut count = 0;
570        let mut last_was_separator = false;
571        loop {
572            match self.peek_char() {
573                Some('_') => {
574                    if count == 0 || last_was_separator {
575                        return Err(self.error("invalid numeric separator", start));
576                    }
577                    last_was_separator = true;
578                    self.bump();
579                }
580                Some(c) if c.is_digit(radix) && c.is_ascii() => {
581                    out.push(c);
582                    count += 1;
583                    last_was_separator = false;
584                    self.bump();
585                }
586                _ => break,
587            }
588        }
589        if last_was_separator {
590            return Err(self.error("invalid numeric separator", start));
591        }
592        Ok(count)
593    }
594
595    /// A numeric literal may not be directly followed by an identifier start or
596    /// a digit (`1abc`, `3in`).
597    fn ensure_literal_boundary(&self, start: Position) -> Result<()> {
598        match self.peek_char() {
599            Some(c) if is_id_start(c) || c.is_ascii_digit() => {
600                Err(self.error("invalid number literal", start))
601            }
602            _ => Ok(()),
603        }
604    }
605
606    // -- strings -----------------------------------------------------------
607
608    fn scan_string(&mut self, quote: char) -> Result<TokenKind> {
609        let start = self.position();
610        self.bump(); // opening quote
611        let mut out = String::new();
612        self.pending_high_surrogate = None;
613        loop {
614            let Some(c) = self.peek_char() else {
615                return Err(self.error("unterminated string literal", start));
616            };
617            if c == quote {
618                self.bump();
619                self.flush_pending_surrogate(&mut out);
620                return Ok(TokenKind::String(out));
621            }
622            if is_line_terminator(c) {
623                return Err(self.error("unterminated string literal", start));
624            }
625            if c == '\\' {
626                self.bump();
627                self.scan_escape(&mut out, start, EscapeContext::String)?;
628            } else {
629                // A literal character after a pending high half means no low half
630                // followed, so the pair never completes.
631                self.flush_pending_surrogate(&mut out);
632                out.push(c);
633                self.bump();
634            }
635        }
636    }
637
638    /// The code point of a `\u…` escape, surrogates included.
639    ///
640    /// Returning the raw value rather than a `char` is what lets the caller pair a
641    /// high half with the low half that follows it.
642    fn scan_unicode_escape_body(&mut self, start: Position) -> Result<u32> {
643        if self.peek_char() == Some('{') {
644            self.bump();
645            let mut value: u32 = 0;
646            let mut digits = 0;
647            loop {
648                match self.peek_char() {
649                    Some('}') => {
650                        self.bump();
651                        break;
652                    }
653                    Some(c) if c.is_ascii_hexdigit() => {
654                        value = value
655                            .checked_mul(16)
656                            .and_then(|v| v.checked_add(c.to_digit(16).expect("hex digit")))
657                            .ok_or_else(|| self.error("malformed Unicode escape", start))?;
658                        if value > 0x10FFFF {
659                            return Err(self.error("malformed Unicode escape", start));
660                        }
661                        digits += 1;
662                        self.bump();
663                    }
664                    _ => return Err(self.error("malformed Unicode escape", start)),
665                }
666            }
667            if digits == 0 {
668                return Err(self.error("malformed Unicode escape", start));
669            }
670            if value > 0x10ffff {
671                return Err(self.error("code point out of range", start));
672            }
673            return Ok(value);
674        }
675        let mut value: u32 = 0;
676        for _ in 0..4 {
677            match self.peek_char() {
678                Some(c) if c.is_ascii_hexdigit() => {
679                    value = value * 16 + c.to_digit(16).expect("hex digit");
680                    self.bump();
681                }
682                _ => return Err(self.error("malformed Unicode escape", start)),
683            }
684        }
685        Ok(value)
686    }
687
688    /// Decode one escape sequence and append it to `out`.
689    ///
690    /// A surrogate written as a pair of escapes — `"\ud83d\ude00"` — denotes one code
691    /// point, so the high half is held in `pending_high` until the next escape says
692    /// whether a low half follows. `char` cannot hold a surrogate, so a true lone
693    /// surrogate becomes U+FFFD; a *pair* combines into the character it spells,
694    /// which is what makes `"\u{dbff}\u{dfff}"` and `"\u{10ffff}"` the same string.
695    fn scan_escape(
696        &mut self,
697        out: &mut String,
698        start: Position,
699        context: EscapeContext,
700    ) -> Result<()> {
701        self.scan_escape_inner(out, start, context)
702    }
703
704    /// Emit any half-finished surrogate as U+FFFD.
705    ///
706    /// Called when the string ends: a high half with no low half after it cannot be
707    /// represented, so it degrades to the replacement character, matching what an
708    /// engine sees when it converts the unpaired code unit to UTF-8.
709    fn flush_pending_surrogate(&mut self, out: &mut String) {
710        if self.pending_high_surrogate.take().is_some() {
711            out.push('\u{fffd}');
712        }
713    }
714
715    /// Append a decoded code unit, combining a surrogate pair written as two escapes.
716    fn push_code_unit(&mut self, out: &mut String, value: u32) {
717        const HIGH_START: u32 = 0xd800;
718        const HIGH_END: u32 = 0xdc00;
719        const LOW_END: u32 = 0xe000;
720        if let Some(high) = self.pending_high_surrogate.take() {
721            if (HIGH_START..HIGH_END).contains(&value) || !(HIGH_START..LOW_END).contains(&value) {
722                // A second high half, or a normal character: the first one stands
723                // alone. Nothing can rescue it, so it becomes the replacement.
724                out.push('\u{fffd}');
725            } else {
726                let combined = 0x10000 + ((high - HIGH_START) << 10) + (value - HIGH_START - 0x400);
727                out.push(char::from_u32(combined).unwrap_or('\u{fffd}'));
728                return;
729            }
730        }
731        if (HIGH_START..HIGH_END).contains(&value) {
732            self.pending_high_surrogate = Some(value);
733        } else if (HIGH_END..LOW_END).contains(&value) {
734            // A lone low half.
735            out.push('\u{fffd}');
736        } else {
737            out.push(char::from_u32(value).unwrap_or('\u{fffd}'));
738        }
739    }
740
741    fn scan_escape_inner(
742        &mut self,
743        out: &mut String,
744        start: Position,
745        context: EscapeContext,
746    ) -> Result<()> {
747        let Some(c) = self.bump() else {
748            return Err(self.error("unterminated string literal", start));
749        };
750        match c {
751            'n' => out.push('\n'),
752            'r' => out.push('\r'),
753            't' => out.push('\t'),
754            'b' => out.push('\u{8}'),
755            'f' => out.push('\u{c}'),
756            'v' => out.push('\u{b}'),
757            '0' if !self.peek_char().is_some_and(|c| c.is_ascii_digit()) => out.push('\0'),
758            '0' => {
759                // `\0` followed by a digit is a legacy octal escape.
760                self.legacy_octal = true;
761                if context == EscapeContext::Template {
762                    return Err(self.invalid_escape(context, start));
763                }
764                if self.strict {
765                    return Err(self.error(
766                        "octal escape sequences are not allowed in strict mode",
767                        start,
768                    ));
769                }
770                let mut value = 0u32;
771                for _ in 0..2 {
772                    match self.peek_char() {
773                        Some(d @ '0'..='7') => {
774                            value = value * 8 + d.to_digit(8).expect("octal digit");
775                            self.bump();
776                        }
777                        _ => break,
778                    }
779                }
780                out.push(char::from_u32(value).expect("value <= 63"));
781            }
782            'x' => {
783                let mut value = 0u32;
784                for _ in 0..2 {
785                    match self.peek_char() {
786                        Some(c) if c.is_ascii_hexdigit() => {
787                            value = value * 16 + c.to_digit(16).expect("hex digit");
788                            self.bump();
789                        }
790                        _ => {
791                            return Err(self.invalid_escape(context, start));
792                        }
793                    }
794                }
795                out.push(char::from_u32(value).expect("value <= 0xff"));
796            }
797            'u' => {
798                let unit = self.scan_unicode_escape_body(start)?;
799                self.push_code_unit(out, unit);
800            }
801            c if is_line_terminator(c) => {
802                // Escaped line terminator: contributes nothing (line
803                // continuation). `\r\n` was already folded by `bump`.
804            }
805            '1'..='7' => {
806                self.legacy_octal = true;
807                if context == EscapeContext::Template {
808                    // Templates never allow octal escapes: this is an invalid
809                    // escape sequence, so `cooked` becomes `undefined`.
810                    return Err(self.invalid_escape(context, start));
811                }
812                if self.strict {
813                    return Err(self.error(
814                        "octal escape sequences are not allowed in strict mode",
815                        start,
816                    ));
817                }
818                let mut value = c.to_digit(8).expect("octal digit");
819                for _ in 0..2 {
820                    match self.peek_char() {
821                        Some(d @ '0'..='7') => {
822                            let next = value * 8 + d.to_digit(8).expect("octal digit");
823                            if next > 255 {
824                                break;
825                            }
826                            value = next;
827                            self.bump();
828                        }
829                        _ => break,
830                    }
831                }
832                out.push(char::from_u32(value).expect("value <= 0xff"));
833            }
834            '8' | '9' => {
835                self.legacy_octal = true;
836                if context == EscapeContext::Template {
837                    return Err(self.invalid_escape(context, start));
838                }
839                if self.strict {
840                    return Err(self.error(
841                        "octal escape sequences are not allowed in strict mode",
842                        start,
843                    ));
844                }
845                out.push(c);
846            }
847            other => out.push(other),
848        }
849        Ok(())
850    }
851
852    fn invalid_escape(&self, context: EscapeContext, start: Position) -> LexError {
853        match context {
854            EscapeContext::String => self.error("invalid escape sequence in string literal", start),
855            EscapeContext::Template => {
856                self.error("invalid escape sequence in template literal", start)
857            }
858        }
859    }
860
861    // -- templates ---------------------------------------------------------
862
863    /// Resume a template literal after the `}` closing a substitution.
864    ///
865    /// `brace` is the position of that `}` (the parser keeps the token span).
866    pub fn re_scan_template_continue(&mut self, brace: Position) -> Result<Token> {
867        let start = brace;
868        self.reset_to(brace);
869        debug_assert_eq!(self.peek_char(), Some('}'));
870        self.bump(); // consume the `}` so the chunk starts after it
871        let chunk = self.scan_template_chunk(start, false)?;
872        Ok(Token {
873            kind: TokenKind::Template(chunk),
874            span: Span::new(start, self.position()),
875            newline_before: false,
876        })
877    }
878
879    /// Scan a template chunk; the opening backtick or `}` is already consumed and
880    /// `chunk_start` is its position (used for the `raw` slice and errors).
881    fn scan_template_chunk(
882        &mut self,
883        chunk_start: Position,
884        opening: bool,
885    ) -> Result<TemplateToken> {
886        let content_start = self.pos;
887        let mut cooked = String::new();
888        let mut valid_escape = true;
889        let kind;
890        loop {
891            let Some(c) = self.peek_char() else {
892                return Err(self.error("unterminated template literal", chunk_start));
893            };
894            match c {
895                '`' => {
896                    self.bump();
897                    kind = if opening {
898                        TemplateKind::NoSubstitution
899                    } else {
900                        TemplateKind::Tail
901                    };
902                    break;
903                }
904                '$' if self.peek_char_at(1) == Some('{') => {
905                    self.bump();
906                    self.bump();
907                    kind = if opening {
908                        TemplateKind::Head
909                    } else {
910                        TemplateKind::Middle
911                    };
912                    break;
913                }
914                '\\' => {
915                    let before = self.position();
916                    self.bump();
917                    let mut scratch = String::new();
918                    match self.scan_escape(&mut scratch, chunk_start, EscapeContext::Template) {
919                        Ok(()) => cooked.push_str(&scratch),
920                        Err(_) => {
921                            // Invalid escapes are legal in tagged templates,
922                            // where `cooked` becomes `undefined`. The raw text
923                            // still has to be recorded, so re-scan verbatim.
924                            valid_escape = false;
925                            // Replay the escape verbatim: `cooked` is undefined
926                            // but `raw` must keep the original bytes, and the
927                            // scan has to continue after it.
928                            self.reset_to(before);
929                            self.bump(); // the backslash
930                            if let Some(next) = self.peek_char() {
931                                if !is_line_terminator(next) {
932                                    self.bump();
933                                }
934                            }
935                        }
936                    }
937                }
938                c if is_line_terminator(c) => {
939                    // Line terminators are normalised to LF in templates.
940                    self.bump();
941                    cooked.push('\n');
942                }
943                other => {
944                    cooked.push(other);
945                    self.bump();
946                }
947            }
948        }
949        let content_end = match kind {
950            TemplateKind::NoSubstitution | TemplateKind::Tail => self.pos - 1,
951            TemplateKind::Head | TemplateKind::Middle => self.pos - 2,
952        }
953        .max(content_start);
954        let raw = self.src[content_start..content_end].to_string();
955        Ok(TemplateToken {
956            kind,
957            cooked: if valid_escape { Some(cooked) } else { None },
958            raw,
959        })
960    }
961
962    // -- regular expressions -----------------------------------------------
963
964    /// Re-scan the token starting at `start` (the `/`) as a regular expression
965    /// literal. Called by the parser when it expects an expression.
966    pub fn re_scan_regex(&mut self, start: Position) -> Result<Token> {
967        self.reset_to(start);
968        debug_assert_eq!(self.peek_char(), Some('/'));
969        self.bump(); // opening slash
970        let mut pattern = String::new();
971        let mut in_class = false;
972        loop {
973            let Some(c) = self.peek_char() else {
974                return Err(self.error("unterminated regexp literal", start));
975            };
976            if is_line_terminator(c) {
977                return Err(self.error("unterminated regexp literal", start));
978            }
979            match c {
980                '\\' => {
981                    pattern.push(c);
982                    self.bump();
983                    match self.peek_char() {
984                        Some(next) if !is_line_terminator(next) => {
985                            pattern.push(next);
986                            self.bump();
987                        }
988                        _ => return Err(self.error("unterminated regexp literal", start)),
989                    }
990                }
991                '[' => {
992                    in_class = true;
993                    pattern.push(c);
994                    self.bump();
995                }
996                ']' => {
997                    in_class = false;
998                    pattern.push(c);
999                    self.bump();
1000                }
1001                '/' if !in_class => {
1002                    self.bump();
1003                    break;
1004                }
1005                _ => {
1006                    pattern.push(c);
1007                    self.bump();
1008                }
1009            }
1010        }
1011        let mut flags = String::new();
1012        while let Some(c) = self.peek_char() {
1013            if is_id_continue(c) {
1014                flags.push(c);
1015                self.bump();
1016            } else {
1017                break;
1018            }
1019        }
1020        Ok(Token {
1021            kind: TokenKind::RegExp { pattern, flags },
1022            span: Span::new(start, self.position()),
1023            newline_before: false,
1024        })
1025    }
1026}
1027
1028/// Which literal an escape sequence belongs to; the two differ in their error
1029/// handling (invalid escapes are fatal in strings, `cooked = undefined` in
1030/// tagged templates).
1031#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1032enum EscapeContext {
1033    String,
1034    Template,
1035}
1036
1037fn is_line_terminator(c: char) -> bool {
1038    matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}')
1039}
1040
1041/// Build the value of a decimal literal text (digits with an optional fraction
1042/// and exponent, separators already removed).
1043fn number_from_decimal(text: &str) -> NumberLiteral {
1044    let is_integer = !text.contains(['.', 'e', 'E']);
1045    if is_integer {
1046        if let Ok(value) = text.parse::<i64>() {
1047            if let Ok(value) = i32::try_from(value) {
1048                return NumberLiteral::Int(value);
1049            }
1050        }
1051    }
1052    // Rust's `f64` parser is correctly rounded, which is exactly what
1053    // `StringNumericLiteral` requires for decimal literals.
1054    NumberLiteral::Float(text.parse::<f64>().unwrap_or(f64::NAN))
1055}
1056
1057fn number_from_f64(value: f64) -> NumberLiteral {
1058    if value.fract() == 0.0 && value >= i32::MIN as f64 && value <= i32::MAX as f64 {
1059        NumberLiteral::Int(value as i32)
1060    } else {
1061        NumberLiteral::Float(value)
1062    }
1063}
1064
1065/// Convert digits in `radix` to a double.
1066///
1067/// Exact for every literal that fits in 128 bits (which covers everything a
1068/// program realistically contains); longer literals accumulate in `f64`, which
1069/// can double-round in rare cases. The exact radix conversion lands with the
1070/// `js-dtoa` milestone (FR-6).
1071pub(crate) fn radix_digits_to_f64(digits: &str, radix: u32) -> f64 {
1072    let mut acc: u128 = 0;
1073    let mut overflow = false;
1074    for c in digits.chars() {
1075        let Some(digit) = c.to_digit(radix) else {
1076            continue;
1077        };
1078        match acc
1079            .checked_mul(radix as u128)
1080            .and_then(|v| v.checked_add(digit as u128))
1081        {
1082            Some(value) => acc = value,
1083            None => {
1084                overflow = true;
1085                break;
1086            }
1087        }
1088    }
1089    if !overflow {
1090        return acc as f64;
1091    }
1092    let mut value = 0.0f64;
1093    for c in digits.chars() {
1094        let Some(digit) = c.to_digit(radix) else {
1095            continue;
1096        };
1097        value = value * radix as f64 + digit as f64;
1098    }
1099    value
1100}