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