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