Skip to main content

js_parse/
lexer.rs

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