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            // `0_1`: a separator may not follow the leading zero of a decimal
427            // literal — the `0` form admits no digits after it.
428            if self.peek_char() == Some('0') && self.bytes.get(self.pos + 1) == Some(&b'_') {
429                return Err(self.error("invalid number literal", start));
430            }
431            let count = self.scan_digits(10, &mut digits, start)?;
432            if count == 0 {
433                return Err(self.error("invalid number literal", start));
434            }
435        }
436        if self.peek_char() == Some('.') {
437            has_fraction = true;
438            digits.push('.');
439            self.bump();
440            let _ = self.scan_digits(10, &mut digits, start)?;
441        }
442        if matches!(self.peek_char(), Some('e') | Some('E')) {
443            has_exponent = true;
444            digits.push('e');
445            self.bump();
446            if matches!(self.peek_char(), Some('+') | Some('-')) {
447                let sign = self.peek_char().expect("checked above");
448                digits.push(sign);
449                self.bump();
450            }
451            let mut exponent = String::new();
452            let count = self.scan_digits(10, &mut exponent, start)?;
453            if count == 0 {
454                return Err(self.error("invalid number literal", start));
455            }
456            digits.push_str(&exponent);
457        }
458        if self.peek_char() == Some('n') {
459            if has_fraction || has_exponent {
460                return Err(self.error("invalid BigInt literal", start));
461            }
462            self.bump();
463            self.ensure_literal_boundary(start)?;
464            return Ok(TokenKind::BigInt(BigIntLiteral { digits, radix: 10 }));
465        }
466        self.ensure_literal_boundary(start)?;
467        Ok(TokenKind::Number(number_from_decimal(&digits)))
468    }
469
470    /// `0` followed by more digits: legacy octal (`017`) or a
471    /// NonOctalDecimalIntegerLiteral (`019`), both Annex B.
472    fn scan_legacy_number(&mut self, start: Position) -> Result<TokenKind> {
473        let mut text = String::new();
474        let mut all_octal = true;
475        while let Some(c) = self.peek_char() {
476            if !c.is_ascii_digit() {
477                break;
478            }
479            if c > '7' {
480                all_octal = false;
481            }
482            text.push(c);
483            self.bump();
484        }
485        if matches!(self.peek_char(), Some('.') | Some('e') | Some('E')) && !all_octal {
486            // `08.5`, `018e1`, `019.5` are ordinary decimal literals: a digit
487            // outside 0-7 makes the whole literal a NonOctalDecimalIntegerLiteral.
488            // A genuine legacy octal (`077`) ends at the last digit — the `.` in
489            // `077.a` is a property access, and `077.5` is two tokens (`077`, `.5`).
490            // Hand back to the general scanner by re-reading the leading `0`.
491            self.reset_to(start);
492            self.legacy_octal = true;
493            self.bump();
494            let mut digits = String::from("0");
495            let mut rest = String::new();
496            self.scan_digits(10, &mut rest, start)?;
497            digits.push_str(&rest);
498            let mut has_fraction = false;
499            let mut has_exponent = false;
500            if self.peek_char() == Some('.') {
501                has_fraction = true;
502                digits.push('.');
503                self.bump();
504                self.scan_digits(10, &mut digits, start)?;
505            }
506            if matches!(self.peek_char(), Some('e') | Some('E')) {
507                has_exponent = true;
508                digits.push('e');
509                self.bump();
510                if matches!(self.peek_char(), Some('+') | Some('-')) {
511                    let sign = self.peek_char().expect("checked above");
512                    digits.push(sign);
513                    self.bump();
514                }
515                let mut exponent = String::new();
516                let count = self.scan_digits(10, &mut exponent, start)?;
517                if count == 0 {
518                    return Err(self.error("invalid number literal", start));
519                }
520                digits.push_str(&exponent);
521            }
522            if self.peek_char() == Some('n') {
523                if has_fraction || has_exponent || text.len() > 1 {
524                    return Err(self.error("invalid BigInt literal", start));
525                }
526                self.bump();
527                return Ok(TokenKind::BigInt(BigIntLiteral { digits, radix: 10 }));
528            }
529            self.ensure_literal_boundary(start)?;
530            return Ok(TokenKind::Number(number_from_decimal(&digits)));
531        }
532        if self.peek_char() == Some('n') {
533            // `0n` is legal, `01n` / `08n` are not.
534            if text.len() > 1 {
535                return Err(self.error("invalid BigInt literal", start));
536            }
537            self.bump();
538            return Ok(TokenKind::BigInt(BigIntLiteral {
539                digits: "0".to_string(),
540                radix: 10,
541            }));
542        }
543        self.ensure_literal_boundary(start)?;
544        // `017` and `019` are both Annex B legacy literals, forbidden in strict
545        // mode.
546        self.legacy_octal = true;
547        let value = if all_octal {
548            radix_digits_to_f64(&text, 8)
549        } else {
550            radix_digits_to_f64(&text, 10)
551        };
552        Ok(TokenKind::Number(number_from_f64(value)))
553    }
554
555    fn finish_radix_literal(
556        &mut self,
557        digits: String,
558        radix: u32,
559        start: Position,
560    ) -> Result<TokenKind> {
561        if self.peek_char() == Some('n') {
562            self.bump();
563            self.ensure_literal_boundary(start)?;
564            return Ok(TokenKind::BigInt(BigIntLiteral { digits, radix }));
565        }
566        self.ensure_literal_boundary(start)?;
567        Ok(TokenKind::Number(number_from_f64(radix_digits_to_f64(
568            &digits, radix,
569        ))))
570    }
571
572    /// Scan digits of `radix`, accepting `_` separators. Returns the digit count.
573    fn scan_digits(&mut self, radix: u32, out: &mut String, start: Position) -> Result<usize> {
574        let mut count = 0;
575        let mut last_was_separator = false;
576        loop {
577            match self.peek_char() {
578                Some('_') => {
579                    if count == 0 || last_was_separator {
580                        return Err(self.error("invalid numeric separator", start));
581                    }
582                    last_was_separator = true;
583                    self.bump();
584                }
585                Some(c) if c.is_digit(radix) && c.is_ascii() => {
586                    out.push(c);
587                    count += 1;
588                    last_was_separator = false;
589                    self.bump();
590                }
591                _ => break,
592            }
593        }
594        if last_was_separator {
595            return Err(self.error("invalid numeric separator", start));
596        }
597        Ok(count)
598    }
599
600    /// A numeric literal may not be directly followed by an identifier start or
601    /// a digit (`1abc`, `3in`).
602    fn ensure_literal_boundary(&self, start: Position) -> Result<()> {
603        match self.peek_char() {
604            Some(c) if is_id_start(c) || c.is_ascii_digit() => {
605                Err(self.error("invalid number literal", start))
606            }
607            _ => Ok(()),
608        }
609    }
610
611    // -- strings -----------------------------------------------------------
612
613    fn scan_string(&mut self, quote: char) -> Result<TokenKind> {
614        let start = self.position();
615        self.bump(); // opening quote
616        let mut out = String::new();
617        self.pending_high_surrogate = None;
618        loop {
619            let Some(c) = self.peek_char() else {
620                return Err(self.error("unterminated string literal", start));
621            };
622            if c == quote {
623                self.bump();
624                self.flush_pending_surrogate(&mut out);
625                return Ok(TokenKind::String(out));
626            }
627            if is_line_terminator(c) {
628                return Err(self.error("unterminated string literal", start));
629            }
630            if c == '\\' {
631                self.bump();
632                self.scan_escape(&mut out, start, EscapeContext::String)?;
633            } else {
634                // A literal character after a pending high half means no low half
635                // followed, so the pair never completes.
636                self.flush_pending_surrogate(&mut out);
637                out.push(c);
638                self.bump();
639            }
640        }
641    }
642
643    /// The code point of a `\u…` escape, surrogates included.
644    ///
645    /// Returning the raw value rather than a `char` is what lets the caller pair a
646    /// high half with the low half that follows it.
647    fn scan_unicode_escape_body(&mut self, start: Position) -> Result<u32> {
648        if self.peek_char() == Some('{') {
649            self.bump();
650            let mut value: u32 = 0;
651            let mut digits = 0;
652            loop {
653                match self.peek_char() {
654                    Some('}') => {
655                        self.bump();
656                        break;
657                    }
658                    Some(c) if c.is_ascii_hexdigit() => {
659                        value = value
660                            .checked_mul(16)
661                            .and_then(|v| v.checked_add(c.to_digit(16).expect("hex digit")))
662                            .ok_or_else(|| self.error("malformed Unicode escape", start))?;
663                        if value > 0x10FFFF {
664                            return Err(self.error("malformed Unicode escape", start));
665                        }
666                        digits += 1;
667                        self.bump();
668                    }
669                    _ => return Err(self.error("malformed Unicode escape", start)),
670                }
671            }
672            if digits == 0 {
673                return Err(self.error("malformed Unicode escape", start));
674            }
675            if value > 0x10ffff {
676                return Err(self.error("code point out of range", start));
677            }
678            return Ok(value);
679        }
680        let mut value: u32 = 0;
681        for _ in 0..4 {
682            match self.peek_char() {
683                Some(c) if c.is_ascii_hexdigit() => {
684                    value = value * 16 + c.to_digit(16).expect("hex digit");
685                    self.bump();
686                }
687                _ => return Err(self.error("malformed Unicode escape", start)),
688            }
689        }
690        Ok(value)
691    }
692
693    /// Decode one escape sequence and append it to `out`.
694    ///
695    /// A surrogate written as a pair of escapes — `"\ud83d\ude00"` — denotes one code
696    /// point, so the high half is held in `pending_high` until the next escape says
697    /// whether a low half follows. `char` cannot hold a surrogate, so a true lone
698    /// surrogate becomes U+FFFD; a *pair* combines into the character it spells,
699    /// which is what makes `"\u{dbff}\u{dfff}"` and `"\u{10ffff}"` the same string.
700    fn scan_escape(
701        &mut self,
702        out: &mut String,
703        start: Position,
704        context: EscapeContext,
705    ) -> Result<()> {
706        self.scan_escape_inner(out, start, context)
707    }
708
709    /// Emit any half-finished surrogate as U+FFFD.
710    ///
711    /// Called when the string ends: a high half with no low half after it cannot be
712    /// represented, so it degrades to the replacement character, matching what an
713    /// engine sees when it converts the unpaired code unit to UTF-8.
714    fn flush_pending_surrogate(&mut self, out: &mut String) {
715        if self.pending_high_surrogate.take().is_some() {
716            out.push('\u{fffd}');
717        }
718    }
719
720    /// Append a decoded code unit, combining a surrogate pair written as two escapes.
721    fn push_code_unit(&mut self, out: &mut String, value: u32) {
722        const HIGH_START: u32 = 0xd800;
723        const HIGH_END: u32 = 0xdc00;
724        const LOW_END: u32 = 0xe000;
725        if let Some(high) = self.pending_high_surrogate.take() {
726            if (HIGH_START..HIGH_END).contains(&value) || !(HIGH_START..LOW_END).contains(&value) {
727                // A second high half, or a normal character: the first one stands
728                // alone. Nothing can rescue it, so it becomes the replacement.
729                out.push('\u{fffd}');
730            } else {
731                let combined = 0x10000 + ((high - HIGH_START) << 10) + (value - HIGH_START - 0x400);
732                out.push(char::from_u32(combined).unwrap_or('\u{fffd}'));
733                return;
734            }
735        }
736        if (HIGH_START..HIGH_END).contains(&value) {
737            self.pending_high_surrogate = Some(value);
738        } else if (HIGH_END..LOW_END).contains(&value) {
739            // A lone low half.
740            out.push('\u{fffd}');
741        } else {
742            out.push(char::from_u32(value).unwrap_or('\u{fffd}'));
743        }
744    }
745
746    fn scan_escape_inner(
747        &mut self,
748        out: &mut String,
749        start: Position,
750        context: EscapeContext,
751    ) -> Result<()> {
752        let Some(c) = self.bump() else {
753            return Err(self.error("unterminated string literal", start));
754        };
755        match c {
756            'n' => out.push('\n'),
757            'r' => out.push('\r'),
758            't' => out.push('\t'),
759            'b' => out.push('\u{8}'),
760            'f' => out.push('\u{c}'),
761            'v' => out.push('\u{b}'),
762            '0' if !self.peek_char().is_some_and(|c| c.is_ascii_digit()) => out.push('\0'),
763            '0' => {
764                // `\0` followed by a digit is a legacy octal escape.
765                self.legacy_octal = true;
766                if context == EscapeContext::Template {
767                    return Err(self.invalid_escape(context, start));
768                }
769                if self.strict {
770                    return Err(self.error(
771                        "octal escape sequences are not allowed in strict mode",
772                        start,
773                    ));
774                }
775                let mut value = 0u32;
776                for _ in 0..2 {
777                    match self.peek_char() {
778                        Some(d @ '0'..='7') => {
779                            value = value * 8 + d.to_digit(8).expect("octal digit");
780                            self.bump();
781                        }
782                        _ => break,
783                    }
784                }
785                out.push(char::from_u32(value).expect("value <= 63"));
786            }
787            'x' => {
788                let mut value = 0u32;
789                for _ in 0..2 {
790                    match self.peek_char() {
791                        Some(c) if c.is_ascii_hexdigit() => {
792                            value = value * 16 + c.to_digit(16).expect("hex digit");
793                            self.bump();
794                        }
795                        _ => {
796                            return Err(self.invalid_escape(context, start));
797                        }
798                    }
799                }
800                out.push(char::from_u32(value).expect("value <= 0xff"));
801            }
802            'u' => {
803                let unit = self.scan_unicode_escape_body(start)?;
804                self.push_code_unit(out, unit);
805            }
806            c if is_line_terminator(c) => {
807                // Escaped line terminator: contributes nothing (line
808                // continuation). `\r\n` was already folded by `bump`.
809            }
810            '1'..='7' => {
811                self.legacy_octal = true;
812                if context == EscapeContext::Template {
813                    // Templates never allow octal escapes: this is an invalid
814                    // escape sequence, so `cooked` becomes `undefined`.
815                    return Err(self.invalid_escape(context, start));
816                }
817                if self.strict {
818                    return Err(self.error(
819                        "octal escape sequences are not allowed in strict mode",
820                        start,
821                    ));
822                }
823                let mut value = c.to_digit(8).expect("octal digit");
824                for _ in 0..2 {
825                    match self.peek_char() {
826                        Some(d @ '0'..='7') => {
827                            let next = value * 8 + d.to_digit(8).expect("octal digit");
828                            if next > 255 {
829                                break;
830                            }
831                            value = next;
832                            self.bump();
833                        }
834                        _ => break,
835                    }
836                }
837                out.push(char::from_u32(value).expect("value <= 0xff"));
838            }
839            '8' | '9' => {
840                self.legacy_octal = true;
841                if context == EscapeContext::Template {
842                    return Err(self.invalid_escape(context, start));
843                }
844                if self.strict {
845                    return Err(self.error(
846                        "octal escape sequences are not allowed in strict mode",
847                        start,
848                    ));
849                }
850                out.push(c);
851            }
852            other => out.push(other),
853        }
854        Ok(())
855    }
856
857    fn invalid_escape(&self, context: EscapeContext, start: Position) -> LexError {
858        match context {
859            EscapeContext::String => self.error("invalid escape sequence in string literal", start),
860            EscapeContext::Template => {
861                self.error("invalid escape sequence in template literal", start)
862            }
863        }
864    }
865
866    // -- templates ---------------------------------------------------------
867
868    /// Resume a template literal after the `}` closing a substitution.
869    ///
870    /// `brace` is the position of that `}` (the parser keeps the token span).
871    pub fn re_scan_template_continue(&mut self, brace: Position) -> Result<Token> {
872        let start = brace;
873        self.reset_to(brace);
874        debug_assert_eq!(self.peek_char(), Some('}'));
875        self.bump(); // consume the `}` so the chunk starts after it
876        let chunk = self.scan_template_chunk(start, false)?;
877        Ok(Token {
878            kind: TokenKind::Template(chunk),
879            span: Span::new(start, self.position()),
880            newline_before: false,
881        })
882    }
883
884    /// Scan a template chunk; the opening backtick or `}` is already consumed and
885    /// `chunk_start` is its position (used for the `raw` slice and errors).
886    fn scan_template_chunk(
887        &mut self,
888        chunk_start: Position,
889        opening: bool,
890    ) -> Result<TemplateToken> {
891        let content_start = self.pos;
892        let mut cooked = String::new();
893        let mut valid_escape = true;
894        let kind;
895        loop {
896            let Some(c) = self.peek_char() else {
897                return Err(self.error("unterminated template literal", chunk_start));
898            };
899            match c {
900                '`' => {
901                    self.bump();
902                    kind = if opening {
903                        TemplateKind::NoSubstitution
904                    } else {
905                        TemplateKind::Tail
906                    };
907                    break;
908                }
909                '$' if self.peek_char_at(1) == Some('{') => {
910                    self.bump();
911                    self.bump();
912                    kind = if opening {
913                        TemplateKind::Head
914                    } else {
915                        TemplateKind::Middle
916                    };
917                    break;
918                }
919                '\\' => {
920                    let before = self.position();
921                    self.bump();
922                    let mut scratch = String::new();
923                    match self.scan_escape(&mut scratch, chunk_start, EscapeContext::Template) {
924                        Ok(()) => cooked.push_str(&scratch),
925                        Err(_) => {
926                            // Invalid escapes are legal in tagged templates,
927                            // where `cooked` becomes `undefined`. The raw text
928                            // still has to be recorded, so re-scan verbatim.
929                            valid_escape = false;
930                            // Replay the escape verbatim: `cooked` is undefined
931                            // but `raw` must keep the original bytes, and the
932                            // scan has to continue after it.
933                            self.reset_to(before);
934                            self.bump(); // the backslash
935                            if let Some(next) = self.peek_char() {
936                                if !is_line_terminator(next) {
937                                    self.bump();
938                                }
939                            }
940                        }
941                    }
942                }
943                c if is_line_terminator(c) => {
944                    // Line terminators are normalised to LF in templates.
945                    self.bump();
946                    cooked.push('\n');
947                }
948                other => {
949                    cooked.push(other);
950                    self.bump();
951                }
952            }
953        }
954        let content_end = match kind {
955            TemplateKind::NoSubstitution | TemplateKind::Tail => self.pos - 1,
956            TemplateKind::Head | TemplateKind::Middle => self.pos - 2,
957        }
958        .max(content_start);
959        let raw = self.src[content_start..content_end].to_string();
960        Ok(TemplateToken {
961            kind,
962            cooked: if valid_escape { Some(cooked) } else { None },
963            raw,
964        })
965    }
966
967    // -- regular expressions -----------------------------------------------
968
969    /// Re-scan the token starting at `start` (the `/`) as a regular expression
970    /// literal. Called by the parser when it expects an expression.
971    pub fn re_scan_regex(&mut self, start: Position) -> Result<Token> {
972        self.reset_to(start);
973        debug_assert_eq!(self.peek_char(), Some('/'));
974        self.bump(); // opening slash
975        let mut pattern = String::new();
976        let mut in_class = false;
977        loop {
978            let Some(c) = self.peek_char() else {
979                return Err(self.error("unterminated regexp literal", start));
980            };
981            if is_line_terminator(c) {
982                return Err(self.error("unterminated regexp literal", start));
983            }
984            match c {
985                '\\' => {
986                    pattern.push(c);
987                    self.bump();
988                    match self.peek_char() {
989                        Some(next) if !is_line_terminator(next) => {
990                            pattern.push(next);
991                            self.bump();
992                        }
993                        _ => return Err(self.error("unterminated regexp literal", start)),
994                    }
995                }
996                '[' => {
997                    in_class = true;
998                    pattern.push(c);
999                    self.bump();
1000                }
1001                ']' => {
1002                    in_class = false;
1003                    pattern.push(c);
1004                    self.bump();
1005                }
1006                '/' if !in_class => {
1007                    self.bump();
1008                    break;
1009                }
1010                _ => {
1011                    pattern.push(c);
1012                    self.bump();
1013                }
1014            }
1015        }
1016        let mut flags = String::new();
1017        while let Some(c) = self.peek_char() {
1018            if is_id_continue(c) {
1019                flags.push(c);
1020                self.bump();
1021            } else {
1022                break;
1023            }
1024        }
1025        Ok(Token {
1026            kind: TokenKind::RegExp { pattern, flags },
1027            span: Span::new(start, self.position()),
1028            newline_before: false,
1029        })
1030    }
1031}
1032
1033/// Which literal an escape sequence belongs to; the two differ in their error
1034/// handling (invalid escapes are fatal in strings, `cooked = undefined` in
1035/// tagged templates).
1036#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1037enum EscapeContext {
1038    String,
1039    Template,
1040}
1041
1042fn is_line_terminator(c: char) -> bool {
1043    matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}')
1044}
1045
1046/// Build the value of a decimal literal text (digits with an optional fraction
1047/// and exponent, separators already removed).
1048fn number_from_decimal(text: &str) -> NumberLiteral {
1049    let is_integer = !text.contains(['.', 'e', 'E']);
1050    if is_integer {
1051        if let Ok(value) = text.parse::<i64>() {
1052            if let Ok(value) = i32::try_from(value) {
1053                return NumberLiteral::Int(value);
1054            }
1055        }
1056    }
1057    // Rust's `f64` parser is correctly rounded, which is exactly what
1058    // `StringNumericLiteral` requires for decimal literals.
1059    NumberLiteral::Float(text.parse::<f64>().unwrap_or(f64::NAN))
1060}
1061
1062fn number_from_f64(value: f64) -> NumberLiteral {
1063    if value.fract() == 0.0 && value >= i32::MIN as f64 && value <= i32::MAX as f64 {
1064        NumberLiteral::Int(value as i32)
1065    } else {
1066        NumberLiteral::Float(value)
1067    }
1068}
1069
1070/// Convert digits in `radix` to a double.
1071///
1072/// Exact for every literal that fits in 128 bits (which covers everything a
1073/// program realistically contains); longer literals accumulate in `f64`, which
1074/// can double-round in rare cases. The exact radix conversion lands with the
1075/// `js-dtoa` milestone (FR-6).
1076pub(crate) fn radix_digits_to_f64(digits: &str, radix: u32) -> f64 {
1077    let mut acc: u128 = 0;
1078    let mut overflow = false;
1079    for c in digits.chars() {
1080        let Some(digit) = c.to_digit(radix) else {
1081            continue;
1082        };
1083        match acc
1084            .checked_mul(radix as u128)
1085            .and_then(|v| v.checked_add(digit as u128))
1086        {
1087            Some(value) => acc = value,
1088            None => {
1089                overflow = true;
1090                break;
1091            }
1092        }
1093    }
1094    if !overflow {
1095        return acc as f64;
1096    }
1097    let mut value = 0.0f64;
1098    for c in digits.chars() {
1099        let Some(digit) = c.to_digit(radix) else {
1100            continue;
1101        };
1102        value = value * radix as f64 + digit as f64;
1103    }
1104    value
1105}