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