Skip to main content

parsec_js/
lexer.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! The lexer: ECMA-262's lexical grammar (clause 12) and Annex B's
5//! additions to it (B.1), one token per call.
6
7use parsec_base::{Diagnostic, Limits, Severity, Span};
8
9use crate::token::{Flags, Keyword, Kind, Punct, Token};
10use crate::unicode;
11
12/// Which of the lexical grammar's goal symbols to read the next token
13/// with. The grammar is ambiguous without one: `/` divides after an
14/// expression and starts a regular expression anywhere else, and `}`
15/// closes a block unless it ends a template substitution. The parser
16/// knows which; the lexer is told and never guesses.
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18pub enum Goal {
19    /// InputElementDiv: `/` and `/=` are punctuators, `}` is a punctuator.
20    Div,
21    /// InputElementRegExp: `/` starts a regular expression.
22    RegExp,
23    /// InputElementTemplateTail: `}` starts a TemplateMiddle or TemplateTail.
24    TemplateTail,
25    /// InputElementRegExpOrTemplateTail: both.
26    RegExpOrTemplateTail,
27}
28
29impl Goal {
30    const fn regexp(self) -> bool {
31        matches!(self, Goal::RegExp | Goal::RegExpOrTemplateTail)
32    }
33
34    const fn template_tail(self) -> bool {
35        matches!(self, Goal::TemplateTail | Goal::RegExpOrTemplateTail)
36    }
37}
38
39/// Whether the source is a Script or a Module. Modules are strict, and
40/// Annex B's HTML-like comments are a syntax error in them.
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
42pub enum SourceType {
43    #[default]
44    Script,
45    Module,
46}
47
48/// Reads tokens from a source, one per [`Lexer::next_token`].
49///
50/// It never fails: a token it can't read whole comes back as far as it
51/// goes (a string with no closing quote ends at the end of the line), or
52/// as [`Kind::Invalid`], and a [`Diagnostic`] says what was wrong. Time is
53/// linear in the input, and nothing is allocated per token; only a
54/// diagnostic is.
55///
56/// ```
57/// use parsec_js::{Goal, Kind, Lexer, Punct, SourceType};
58///
59/// let src = "a / b; /b/g";
60/// let mut lexer = Lexer::new(src, SourceType::Script);
61/// let kinds: Vec<Kind> = [Goal::RegExp, Goal::Div, Goal::RegExp, Goal::Div, Goal::RegExp]
62///     .into_iter()
63///     .map(|goal| lexer.next_token(goal).kind)
64///     .collect();
65/// assert_eq!(kinds[1], Kind::Punct(Punct::Slash));
66/// assert_eq!(kinds[4], Kind::RegExp);
67/// assert!(lexer.diagnostics().is_empty());
68/// ```
69#[derive(Clone, Debug)]
70pub struct Lexer<'a> {
71    src: &'a str,
72    pos: usize,
73    source: SourceType,
74    /// A line terminator since the last token that wasn't trivia.
75    newline: bool,
76    /// Only whitespace and comments without line terminators since the
77    /// last line terminator: where Annex B lets `-->` start a comment.
78    line_start: bool,
79    /// An identifier with an escape has been read, so a name's text may
80    /// not be its name.
81    escaped_ident: bool,
82    diagnostics: Vec<Diagnostic>,
83}
84
85impl<'a> Lexer<'a> {
86    pub fn new(src: &'a str, source: SourceType) -> Lexer<'a> {
87        Lexer::with_limits(src, source, &Limits::default())
88    }
89
90    /// A lexer that refuses input longer than `limits.max_input`, or than
91    /// spans can hold: it reports `input-too-large` and gives only
92    /// [`Kind::Eof`].
93    pub fn with_limits(src: &'a str, source: SourceType, limits: &Limits) -> Lexer<'a> {
94        let mut diagnostics = Vec::new();
95        let src = match limits.check_input(src.len()) {
96            Ok(()) => src,
97            Err(d) => {
98                diagnostics.push(d);
99                ""
100            }
101        };
102        Lexer {
103            src,
104            pos: 0,
105            source,
106            newline: false,
107            // InputElementHashbangOrRegExp, the goal at the start, has
108            // HTMLCloseComment: `-->` can start the first line too.
109            line_start: true,
110            escaped_ident: false,
111            diagnostics,
112        }
113    }
114
115    pub fn source(&self) -> &'a str {
116        self.src
117    }
118
119    /// The byte offset the next token is read from.
120    pub fn position(&self) -> u32 {
121        self.pos as u32
122    }
123
124    /// What's been reported so far, in the order it was found.
125    pub fn diagnostics(&self) -> &[Diagnostic] {
126        &self.diagnostics
127    }
128
129    /// Whether any identifier read so far had an escape in it. Until one
130    /// has, every identifier's text is its name.
131    pub(crate) fn escaped_ident(&self) -> bool {
132        self.escaped_ident
133    }
134
135    pub fn take_diagnostics(&mut self) -> Vec<Diagnostic> {
136        std::mem::take(&mut self.diagnostics)
137    }
138
139    /// Reads `token`, the last token read, again with `goal`: the parser
140    /// read a `/` or `}` with [`Goal::Div`] and then found it starts a
141    /// regular expression or carries a template on. Reading either with
142    /// `Div` reports nothing, so there's nothing to take back.
143    pub(crate) fn rescan(&mut self, token: Token, goal: Goal) -> Token {
144        debug_assert_eq!(self.pos, token.span.end as usize);
145        self.pos = token.span.start as usize;
146        self.newline = token.newline_before();
147        self.line_start = false;
148        self.next_token(goal)
149    }
150
151    /// A lexer reading on from here, with none of the diagnostics so far,
152    /// for looking a token ahead.
153    pub(crate) fn fork(&self) -> Lexer<'a> {
154        Lexer {
155            src: self.src,
156            pos: self.pos,
157            source: self.source,
158            newline: self.newline,
159            line_start: self.line_start,
160            escaped_ident: self.escaped_ident,
161            diagnostics: Vec::new(),
162        }
163    }
164
165    /// A lexer reading from byte `pos`, as from the start of a line when
166    /// `newline` says one is before it.
167    pub(crate) fn starting_at(&self, pos: u32, newline: bool) -> Lexer<'a> {
168        Lexer {
169            src: self.src,
170            pos: pos as usize,
171            source: self.source,
172            newline,
173            line_start: newline,
174            escaped_ident: self.escaped_ident,
175            diagnostics: Vec::new(),
176        }
177    }
178
179    /// The next token, read with `goal`. Comments and a hashbang come
180    /// back as tokens too ([`Kind::is_trivia`]); whitespace and line
181    /// terminators don't, but [`Token::newline_before`] says where a line
182    /// terminator was.
183    pub fn next_token(&mut self, goal: Goal) -> Token {
184        if self.pos == 0 && self.src.starts_with("#!") {
185            return self.rest_of_line(Kind::Hashbang, 0, 2);
186        }
187        if !self.skip_whitespace() {
188            return self.after_unicode(goal);
189        }
190        let start = self.pos;
191        let b = self.src.as_bytes();
192        let Some(&c) = b.get(start) else {
193            return self.token(Kind::Eof, start, Flags::empty());
194        };
195        let script = self.source == SourceType::Script;
196        let kind = match c {
197            b'/' => match b.get(start + 1) {
198                Some(b'/') => return self.rest_of_line(Kind::LineComment, start, 2),
199                Some(b'*') => return self.block_comment(start),
200                _ if goal.regexp() => return self.regexp(start),
201                Some(b'=') => self.punct(2, Punct::SlashEq),
202                _ => self.punct(1, Punct::Slash),
203            },
204            // Annex B's HTML-like comments, in scripts only: in a module
205            // `<!--` is `<` `!` `--` and `-->` is `--` `>`.
206            b'<' if script && b[start..].starts_with(b"<!--") => {
207                return self.rest_of_line(Kind::HtmlOpenComment, start, 4);
208            }
209            b'-' if script && self.line_start && b[start..].starts_with(b"-->") => {
210                return self.rest_of_line(Kind::HtmlCloseComment, start, 3);
211            }
212            b'a'..=b'z' | b'A'..=b'Z' | b'$' | b'_' | b'\\' => return self.ident(start),
213            b'0'..=b'9' => return self.number(start),
214            b'.' if b.get(start + 1).is_some_and(u8::is_ascii_digit) => return self.number(start),
215            b'"' | b'\'' => return self.string(start, c),
216            b'`' => return self.template(start, false),
217            b'}' if goal.template_tail() => return self.template(start, true),
218            b'#' => return self.private_name(start),
219            // The punctuators that are one character whatever follows,
220            // most of them, without the lookahead the others need.
221            b'{' => self.punct(1, Punct::LBrace),
222            b'}' => self.punct(1, Punct::RBrace),
223            b'(' => self.punct(1, Punct::LParen),
224            b')' => self.punct(1, Punct::RParen),
225            b'[' => self.punct(1, Punct::LBracket),
226            b']' => self.punct(1, Punct::RBracket),
227            b';' => self.punct(1, Punct::Semicolon),
228            b',' => self.punct(1, Punct::Comma),
229            b':' => self.punct(1, Punct::Colon),
230            b'~' => self.punct(1, Punct::Tilde),
231            0x80.. => return self.non_ascii(start),
232            _ => match self.punctuator(start) {
233                Some(p) => Kind::Punct(p),
234                None => return self.unexpected_character(start, 1),
235            },
236        };
237        self.token(kind, start, Flags::empty())
238    }
239
240    // What `next_token` leaves out of line, so the registers these need
241    // aren't saved and restored for every token.
242
243    /// A comment or hashbang `skip` bytes long to start, to the end of
244    /// its line.
245    #[inline(never)]
246    fn rest_of_line(&mut self, kind: Kind, start: usize, skip: usize) -> Token {
247        self.pos = self.line_end(start + skip);
248        self.trivia(kind, start, false)
249    }
250
251    /// A token starting with a character above ASCII.
252    #[inline(never)]
253    fn non_ascii(&mut self, start: usize) -> Token {
254        let ch = self.char_at(start);
255        if is_id_start(ch) {
256            return self.ident(start);
257        }
258        self.unexpected_character(start, ch.len_utf8())
259    }
260
261    #[cold]
262    #[inline(never)]
263    fn unexpected_character(&mut self, start: usize, len: usize) -> Token {
264        self.pos += len;
265        self.error(
266            "unexpected-character",
267            start,
268            "this character can't start a token",
269        );
270        self.token(Kind::Invalid, start, Flags::empty())
271    }
272
273    // Helpers that end a token.
274
275    fn token(&mut self, kind: Kind, start: usize, mut flags: Flags) -> Token {
276        if self.newline {
277            flags.insert(Flags::NEWLINE_BEFORE);
278        }
279        self.newline = false;
280        self.line_start = false;
281        Token {
282            kind,
283            flags,
284            span: Span::new(start as u32, self.pos as u32),
285        }
286    }
287
288    /// A comment, which leaves the newline flag for the token after it,
289    /// and sets it if the comment held a line terminator.
290    fn trivia(&mut self, kind: Kind, start: usize, holds_newline: bool) -> Token {
291        let flags = if self.newline {
292            Flags::NEWLINE_BEFORE
293        } else {
294            Flags::empty()
295        };
296        if holds_newline {
297            self.newline = true;
298            self.line_start = true;
299        } else if kind != Kind::BlockComment {
300            // A line comment runs to a line terminator, which sets
301            // line_start again when it's skipped.
302            self.line_start = false;
303        }
304        Token {
305            kind,
306            flags,
307            span: Span::new(start as u32, self.pos as u32),
308        }
309    }
310
311    fn punct(&mut self, len: usize, p: Punct) -> Kind {
312        self.pos += len;
313        Kind::Punct(p)
314    }
315
316    fn report(
317        &mut self,
318        code: &'static str,
319        severity: Severity,
320        start: usize,
321        message: &'static str,
322    ) {
323        let span = Span::new(start as u32, self.pos.max(start) as u32);
324        self.diagnostics
325            .push(Diagnostic::new(code, severity, span, message));
326    }
327
328    fn error(&mut self, code: &'static str, start: usize, message: &'static str) {
329        self.report(code, Severity::Error, start, message);
330    }
331
332    /// A legacy form: an error in a module, a warning in a script, whose
333    /// strictness only the parser knows.
334    fn legacy(&mut self, code: &'static str, start: usize, message: &'static str) {
335        let severity = match self.source {
336            SourceType::Module => Severity::Error,
337            SourceType::Script => Severity::Warning,
338        };
339        self.report(code, severity, start, message);
340    }
341
342    // Characters.
343
344    fn char_at(&self, at: usize) -> char {
345        self.src[at..].chars().next().unwrap_or('\0')
346    }
347
348    /// The offset of the first line terminator at or after `from`, or the
349    /// end.
350    fn line_end(&self, from: usize) -> usize {
351        let b = self.src.as_bytes();
352        let mut i = from;
353        while i < b.len() {
354            match b[i] {
355                b'\n' | b'\r' => return i,
356                0xE2 if is_separator(&b[i..]) => return i,
357                _ => i += 1,
358            }
359        }
360        i
361    }
362
363    /// Whitespace and line terminators (12.2, 12.3) in ASCII. False if it
364    /// stopped at a character above ASCII, which may be either.
365    #[inline(always)]
366    fn skip_whitespace(&mut self) -> bool {
367        let b = self.src.as_bytes();
368        while let Some(&c) = b.get(self.pos) {
369            match c {
370                b' ' | b'\t' | 0x0B | 0x0C => self.pos += 1,
371                b'\n' | b'\r' => {
372                    self.pos += 1;
373                    self.newline = true;
374                    self.line_start = true;
375                    // The spaces of the indent after it, a word at a time:
376                    // the count is the run of zero bytes at the bottom of
377                    // the word with the spaces taken out.
378                    const SPACES: u64 = u64::from_ne_bytes([b' '; 8]);
379                    while let Some(&w) = b.get(self.pos..).and_then(|r| r.first_chunk::<8>()) {
380                        let n = (u64::from_le_bytes(w) ^ SPACES).trailing_zeros() as usize / 8;
381                        self.pos += n;
382                        if n < 8 {
383                            break;
384                        }
385                    }
386                }
387                0x80.. => return false,
388                _ => return true,
389            }
390        }
391        true
392    }
393
394    /// The next token from a character above ASCII, after any whitespace
395    /// and line terminators from there. Out of line, so `next_token`
396    /// calls nothing before it reads a token and saves no registers.
397    #[inline(never)]
398    fn after_unicode(&mut self, goal: Goal) -> Token {
399        while self.unicode_space() {
400            if self.skip_whitespace() {
401                // At ASCII that isn't whitespace, or the end: one call
402                // deep, as there's nothing to skip there.
403                return self.next_token(goal);
404            }
405        }
406        self.non_ascii(self.pos)
407    }
408
409    /// Skips the whitespace or line terminator above ASCII at `pos`, if
410    /// that's what's there.
411    fn unicode_space(&mut self) -> bool {
412        let ch = self.char_at(self.pos);
413        if matches!(ch, '\u{2028}' | '\u{2029}') {
414            self.newline = true;
415            self.line_start = true;
416        } else if !is_whitespace(ch) {
417            return false;
418        }
419        self.pos += ch.len_utf8();
420        true
421    }
422
423    // Comments (12.4, B.1.1).
424
425    fn block_comment(&mut self, start: usize) -> Token {
426        let b = self.src.as_bytes();
427        let mut i = start + 2;
428        let mut newline = false;
429        loop {
430            match b.get(i) {
431                None => {
432                    self.pos = i;
433                    self.error(
434                        "unterminated-comment",
435                        start,
436                        "a /* comment has no closing */",
437                    );
438                    break;
439                }
440                Some(b'*') if b.get(i + 1) == Some(&b'/') => {
441                    self.pos = i + 2;
442                    break;
443                }
444                Some(b'\n' | b'\r') => newline = true,
445                Some(0xE2) if is_separator(&b[i..]) => newline = true,
446                _ => {}
447            }
448            i += 1;
449        }
450        self.trivia(Kind::BlockComment, start, newline)
451    }
452
453    // Identifiers (12.7) and private names.
454
455    fn private_name(&mut self, start: usize) -> Token {
456        let next = self.pos + 1;
457        let starts_ident = match self.src.as_bytes().get(next) {
458            Some(b'a'..=b'z' | b'A'..=b'Z' | b'$' | b'_' | b'\\') => true,
459            Some(0x80..) => is_id_start(self.char_at(next)),
460            _ => false,
461        };
462        if !starts_ident {
463            self.pos = next;
464            self.error(
465                "unexpected-character",
466                start,
467                "# starts a private name, like #x",
468            );
469            return self.token(Kind::Invalid, start, Flags::empty());
470        }
471        let ident = self.ident(next);
472        // An escape that isn't one is reported already; the name is still
473        // a name.
474        Token {
475            kind: Kind::PrivateName,
476            span: Span::new(start as u32, ident.span.end),
477            ..ident
478        }
479    }
480
481    fn ident(&mut self, start: usize) -> Token {
482        let b = self.src.as_bytes();
483        // Most identifiers are plain ASCII: read those in a tight loop,
484        // and leave escapes and other characters to the loop below.
485        // No indexing that could panic either: that's a call to save
486        // registers for.
487        let rest = b.get(start..).unwrap_or_default();
488        if let Some((b'a'..=b'z' | b'A'..=b'Z' | b'$' | b'_', tail)) = rest.split_first() {
489            let len = 1 + ident_run(tail);
490            if !matches!(rest.get(len), Some(b'\\' | 0x80..)) {
491                self.pos = start + len;
492                let kind = Keyword::from_prefix(rest, len).map_or(Kind::Ident, Kind::Keyword);
493                return self.token(kind, start, Flags::empty());
494            }
495        }
496        self.ident_slow(start)
497    }
498
499    /// An identifier with an escape or a character above ASCII in it.
500    /// Out of line, so plain ones save no registers for it.
501    #[inline(never)]
502    fn ident_slow(&mut self, start: usize) -> Token {
503        let b = self.src.as_bytes();
504        let mut flags = Flags::empty();
505        self.pos = start;
506        let mut first = true;
507        loop {
508            match b.get(self.pos) {
509                Some(&c) if c < 0x80 && ID_CONTINUE_ASCII[c as usize] => {
510                    if first && c.is_ascii_digit() {
511                        break;
512                    }
513                    self.pos += 1;
514                }
515                Some(b'\\') => {
516                    let at = self.pos;
517                    flags.insert(Flags::ESCAPED);
518                    self.pos += 1;
519                    let ok = if b.get(self.pos) == Some(&b'u') {
520                        self.pos += 1;
521                        self.unicode_escape()
522                            .and_then(char::from_u32)
523                            .is_some_and(|ch| {
524                                if first {
525                                    is_id_start(ch) || ch == '$' || ch == '_'
526                                } else {
527                                    is_id_continue(ch)
528                                }
529                            })
530                    } else {
531                        false
532                    };
533                    if !ok {
534                        if first && self.pos == at + 1 {
535                            // A lone `\`: no identifier at all.
536                            self.error("invalid-escape", at, "\\ here has to start a \\u escape");
537                            return self.token(Kind::Invalid, start, Flags::empty());
538                        }
539                        self.error(
540                            "invalid-identifier-escape",
541                            at,
542                            "this escape isn't a character an identifier can have here",
543                        );
544                    }
545                }
546                Some(0x80..) => {
547                    let ch = self.char_at(self.pos);
548                    if !(if first {
549                        is_id_start(ch)
550                    } else {
551                        is_id_continue(ch)
552                    }) {
553                        break;
554                    }
555                    self.pos += ch.len_utf8();
556                }
557                _ => break,
558            }
559            first = false;
560        }
561        self.escaped_ident |= flags.contains(Flags::ESCAPED);
562        let kind = match flags.contains(Flags::ESCAPED) {
563            false => Keyword::from_bytes(&b[start..self.pos]).map_or(Kind::Ident, Kind::Keyword),
564            true => Kind::Ident,
565        };
566        self.token(kind, start, flags)
567    }
568
569    /// After `\u`: four hex digits, or hex digits in braces up to
570    /// 10FFFF. It consumes only hex digits and the braces, so a bad escape
571    /// never swallows the quote or backtick after it.
572    fn unicode_escape(&mut self) -> Option<u32> {
573        let b = self.src.as_bytes();
574        if b.get(self.pos) == Some(&b'{') {
575            self.pos += 1;
576            let mut value: u32 = 0;
577            let mut digits = 0;
578            while let Some(d) = b.get(self.pos).and_then(|&c| (c as char).to_digit(16)) {
579                value = value.saturating_mul(16).saturating_add(d).min(0x11_0000);
580                digits += 1;
581                self.pos += 1;
582            }
583            if digits == 0 || b.get(self.pos) != Some(&b'}') {
584                return None;
585            }
586            self.pos += 1;
587            (value <= 0x10_FFFF).then_some(value)
588        } else {
589            self.hex_digits(4)
590        }
591    }
592
593    /// Exactly `n` hex digits, consuming the ones there are up to `n`.
594    fn hex_digits(&mut self, n: usize) -> Option<u32> {
595        let b = self.src.as_bytes();
596        let mut value = 0;
597        for _ in 0..n {
598            let d = b.get(self.pos).and_then(|&c| (c as char).to_digit(16))?;
599            value = value * 16 + d;
600            self.pos += 1;
601        }
602        Some(value)
603    }
604
605    // Numeric literals (12.9.3, B.1.1).
606
607    fn number(&mut self, start: usize) -> Token {
608        // Most numbers are decimal digits with nothing after them that
609        // could go on with the number: those need none of the registers
610        // the rest does.
611        let b = self.src.as_bytes();
612        if b[start] != b'.' {
613            let mut end = start + 1;
614            if b[start] != b'0' {
615                while b.get(end).is_some_and(u8::is_ascii_digit) {
616                    end += 1;
617                }
618            }
619            let plain = b.get(end).is_none_or(|&c| {
620                c < 0x80 && !c.is_ascii_alphanumeric() && !matches!(c, b'.' | b'$' | b'_' | b'\\')
621            });
622            if plain {
623                self.pos = end;
624                return self.token(Kind::Number, start, Flags::empty());
625            }
626        }
627        self.number_rest(start)
628    }
629
630    /// A number from `start` that isn't only decimal digits.
631    #[inline(never)]
632    fn number_rest(&mut self, start: usize) -> Token {
633        let b = self.src.as_bytes();
634        let mut flags = Flags::empty();
635        let mut kind = Kind::Number;
636        self.pos = start;
637        let radix = match (b[start], b.get(start + 1).map(u8::to_ascii_lowercase)) {
638            (b'0', Some(b'x')) => 16,
639            (b'0', Some(b'o')) => 8,
640            (b'0', Some(b'b')) => 2,
641            _ => 10,
642        };
643        if radix != 10 {
644            self.pos += 2;
645            if self.digits(radix) == 0 {
646                self.error(
647                    "missing-digits",
648                    start,
649                    "a number needs digits after its prefix",
650                );
651            }
652            if b.get(self.pos) == Some(&b'n') {
653                self.pos += 1;
654                kind = Kind::BigInt;
655            }
656        } else if b[start] == b'0' && b.get(start + 1).is_some_and(u8::is_ascii_digit) {
657            // A legacy octal literal (017), or a decimal one with a leading
658            // zero (08, 09.5), which has a fraction and exponent like any.
659            self.pos += 1;
660            let mut octal = true;
661            while let Some(&c) = b.get(self.pos).filter(|c| c.is_ascii_digit()) {
662                octal &= c < b'8';
663                self.pos += 1;
664            }
665            flags.insert(Flags::LEGACY_OCTAL);
666            if octal {
667                self.legacy(
668                    "legacy-octal-literal",
669                    start,
670                    "legacy octal literals like 017 aren't allowed in strict code; write 0o17",
671                );
672            } else {
673                self.legacy(
674                    "leading-zero-literal",
675                    start,
676                    "decimal literals with a leading zero aren't allowed in strict code",
677                );
678                self.fraction_and_exponent();
679            }
680        } else {
681            let mut integer = true;
682            if b[start] == b'0' {
683                self.pos += 1;
684            } else if b[start] != b'.' {
685                self.digits(10);
686            }
687            if b.get(self.pos) == Some(&b'.') {
688                integer = false;
689            }
690            integer &= !self.fraction_and_exponent();
691            if integer && b.get(self.pos) == Some(&b'n') {
692                self.pos += 1;
693                kind = Kind::BigInt;
694            }
695        }
696        // The SourceCharacter after a NumericLiteral can't be an
697        // IdentifierStart or a digit: `3in`, `1_`, `0b12` and `1.5n` are all
698        // errors. The rest of the word goes in the token.
699        let bad = match b.get(self.pos) {
700            Some(c) if c.is_ascii_digit() => true,
701            Some(b'a'..=b'z' | b'A'..=b'Z' | b'$' | b'_' | b'\\') => true,
702            Some(0x80..) => is_id_start(self.char_at(self.pos)),
703            _ => false,
704        };
705        if bad {
706            let at = self.pos;
707            while let Some(&c) = b.get(self.pos) {
708                if c < 0x80 && ID_CONTINUE_ASCII[c as usize] {
709                    self.pos += 1;
710                } else if c >= 0x80 && is_id_continue(self.char_at(self.pos)) {
711                    self.pos += self.char_at(self.pos).len_utf8();
712                } else {
713                    break;
714                }
715            }
716            self.pos = self.pos.max(at + 1);
717            self.error(
718                "identifier-after-number",
719                at,
720                "a number can't be followed straight away by a letter or digit",
721            );
722        }
723        self.token(kind, start, flags)
724    }
725
726    /// `.digits` and `e±digits`, if they're there. Whether either was.
727    fn fraction_and_exponent(&mut self) -> bool {
728        let b = self.src.as_bytes();
729        let mut any = false;
730        if b.get(self.pos) == Some(&b'.') {
731            self.pos += 1;
732            self.digits(10);
733            any = true;
734        }
735        if matches!(b.get(self.pos), Some(b'e' | b'E')) {
736            let at = self.pos;
737            self.pos += 1;
738            if matches!(b.get(self.pos), Some(b'+' | b'-')) {
739                self.pos += 1;
740            }
741            if self.digits(10) == 0 {
742                self.error("missing-exponent", at, "an exponent needs digits");
743            }
744            any = true;
745        }
746        any
747    }
748
749    /// Digits in `radix`, with `_` separators between two of them. How
750    /// many digits there were.
751    fn digits(&mut self, radix: u32) -> usize {
752        let b = self.src.as_bytes();
753        let mut count = 0;
754        loop {
755            match b.get(self.pos) {
756                Some(&c) if (c as char).is_digit(radix) => {
757                    count += 1;
758                    self.pos += 1;
759                }
760                Some(b'_') => {
761                    let next_digit = b
762                        .get(self.pos + 1)
763                        .is_some_and(|&c| (c as char).is_digit(radix));
764                    let prev_digit = count > 0 && b[self.pos - 1] != b'_';
765                    if !(prev_digit && next_digit) {
766                        let at = self.pos;
767                        self.pos += 1;
768                        self.error(
769                            "invalid-numeric-separator",
770                            at,
771                            "a _ in a number has to be between two digits",
772                        );
773                        if !next_digit {
774                            return count;
775                        }
776                    } else {
777                        self.pos += 1;
778                    }
779                }
780                _ => return count,
781            }
782        }
783    }
784
785    // String literals (12.9.4, B.1.2).
786
787    #[inline(never)]
788    fn string(&mut self, start: usize, quote: u8) -> Token {
789        // Most strings end at the first byte that might end one, with no
790        // escape: those need none of the registers the rest does.
791        let b = self.src.as_bytes();
792        let end = start + 1 + string_run(&b[start + 1..], quote);
793        if b.get(end) == Some(&quote) {
794            self.pos = end + 1;
795            return self.token(Kind::String, start, Flags::empty());
796        }
797        self.pos = end;
798        self.string_rest(start, quote)
799    }
800
801    /// The rest of a string from `start`, from a byte at `pos` that
802    /// might end it or start an escape.
803    #[inline(never)]
804    fn string_rest(&mut self, start: usize, quote: u8) -> Token {
805        let b = self.src.as_bytes();
806        let mut flags = Flags::empty();
807        loop {
808            // Skip what can't end the string or start an escape at once:
809            // long strings in inline scripts are mostly that.
810            self.pos += string_run(&b[self.pos..], quote);
811            match b.get(self.pos) {
812                None | Some(b'\n' | b'\r') => {
813                    self.error(
814                        "unterminated-string",
815                        start,
816                        "a string has no closing quote on its line",
817                    );
818                    break;
819                }
820                Some(&c) if c == quote => {
821                    self.pos += 1;
822                    break;
823                }
824                Some(b'\\') => {
825                    flags.insert(Flags::ESCAPED);
826                    self.pos += 1;
827                    self.string_escape(&mut flags);
828                }
829                Some(_) => self.pos += 1,
830            }
831        }
832        self.token(Kind::String, start, flags)
833    }
834
835    /// After a `\` in a string.
836    fn string_escape(&mut self, flags: &mut Flags) {
837        let b = self.src.as_bytes();
838        let at = self.pos - 1;
839        match b.get(self.pos) {
840            None => {}
841            Some(b'\r') => {
842                self.pos += 1;
843                if b.get(self.pos) == Some(&b'\n') {
844                    self.pos += 1;
845                }
846            }
847            Some(b'x') => {
848                self.pos += 1;
849                if self.hex_digits(2).is_none() {
850                    self.error("invalid-escape", at, "\\x needs two hex digits");
851                }
852            }
853            Some(b'u') => {
854                self.pos += 1;
855                if self.unicode_escape().is_none() {
856                    self.error(
857                        "invalid-escape",
858                        at,
859                        "\\u needs four hex digits, or hex digits in braces up to 10FFFF",
860                    );
861                }
862            }
863            Some(b'0') if !b.get(self.pos + 1).is_some_and(u8::is_ascii_digit) => self.pos += 1,
864            Some(&c @ b'0'..=b'7') => {
865                // ZeroToThree OctalDigit OctalDigit at most, or FourToSeven
866                // OctalDigit.
867                let max = if c <= b'3' { 3 } else { 2 };
868                let mut n = 0;
869                while n < max && b.get(self.pos).is_some_and(|c| (b'0'..=b'7').contains(c)) {
870                    self.pos += 1;
871                    n += 1;
872                }
873                flags.insert(Flags::LEGACY_OCTAL);
874                self.legacy(
875                    "legacy-octal-escape",
876                    at,
877                    "octal escapes like \\01 aren't allowed in strict code",
878                );
879            }
880            Some(b'8' | b'9') => {
881                self.pos += 1;
882                flags.insert(Flags::LEGACY_OCTAL);
883                self.legacy(
884                    "legacy-octal-escape",
885                    at,
886                    "\\8 and \\9 aren't allowed in strict code",
887                );
888            }
889            Some(_) => self.pos += self.char_at(self.pos).len_utf8(),
890        }
891    }
892
893    // Templates (12.9.6).
894
895    /// From `` ` `` or, for a middle or tail, from `}`.
896    fn template(&mut self, start: usize, continued: bool) -> Token {
897        // Most templates in minified code are strings in backquotes, with
898        // no escape or substitution: those need none of the registers
899        // the rest does.
900        let b = self.src.as_bytes();
901        let mut end = start + 1;
902        while b
903            .get(end)
904            .is_some_and(|c| !matches!(c, b'`' | b'\\' | b'$'))
905        {
906            end += 1;
907        }
908        self.pos = end;
909        if b.get(end) == Some(&b'`') {
910            self.pos += 1;
911            let kind = if continued {
912                Kind::TemplateTail
913            } else {
914                Kind::Template
915            };
916            return self.token(kind, start, Flags::empty());
917        }
918        self.template_rest(start, continued)
919    }
920
921    /// The rest of a template part from `start`, from a `\`, a `$` or the
922    /// end of the input at `pos`.
923    #[inline(never)]
924    fn template_rest(&mut self, start: usize, continued: bool) -> Token {
925        let b = self.src.as_bytes();
926        let mut flags = Flags::empty();
927        let kind = loop {
928            match b.get(self.pos) {
929                None => {
930                    self.error(
931                        "unterminated-template",
932                        start,
933                        "a template has no closing `",
934                    );
935                    break if continued {
936                        Kind::TemplateTail
937                    } else {
938                        Kind::Template
939                    };
940                }
941                Some(b'`') => {
942                    self.pos += 1;
943                    break if continued {
944                        Kind::TemplateTail
945                    } else {
946                        Kind::Template
947                    };
948                }
949                Some(b'$') if b.get(self.pos + 1) == Some(&b'{') => {
950                    self.pos += 2;
951                    break if continued {
952                        Kind::TemplateMiddle
953                    } else {
954                        Kind::TemplateHead
955                    };
956                }
957                Some(b'\\') => {
958                    flags.insert(Flags::ESCAPED);
959                    self.pos += 1;
960                    if !self.template_escape() {
961                        flags.insert(Flags::INVALID_ESCAPE);
962                    }
963                }
964                Some(_) => self.pos += 1,
965            }
966        };
967        self.token(kind, start, flags)
968    }
969
970    /// After a `\` in a template: whether it's an escape sequence and not
971    /// a NotEscapeSequence.
972    fn template_escape(&mut self) -> bool {
973        let b = self.src.as_bytes();
974        match b.get(self.pos) {
975            None => true,
976            Some(b'x') => {
977                self.pos += 1;
978                self.hex_digits(2).is_some()
979            }
980            Some(b'u') => {
981                self.pos += 1;
982                self.unicode_escape().is_some()
983            }
984            Some(b'0') if !b.get(self.pos + 1).is_some_and(u8::is_ascii_digit) => {
985                self.pos += 1;
986                true
987            }
988            // `\0` before a digit, and `\1` to `\9`: the digit is the
989            // escape, and what follows is template text again.
990            Some(b'0'..=b'9') => {
991                self.pos += 1;
992                false
993            }
994            // A line continuation, CRLF included, or any other character.
995            Some(_) => {
996                self.pos += self.char_at(self.pos).len_utf8();
997                if b[self.pos - 1] == b'\r' && b.get(self.pos) == Some(&b'\n') {
998                    self.pos += 1;
999                }
1000                true
1001            }
1002        }
1003    }
1004
1005    // Regular expression literals (12.9.5).
1006
1007    fn regexp(&mut self, start: usize) -> Token {
1008        let b = self.src.as_bytes();
1009        self.pos = start + 1;
1010        let mut class = false;
1011        loop {
1012            match b.get(self.pos) {
1013                None | Some(b'\n' | b'\r') => {
1014                    self.error(
1015                        "unterminated-regexp",
1016                        start,
1017                        "a regular expression has no closing / on its line",
1018                    );
1019                    return self.token(Kind::RegExp, start, Flags::empty());
1020                }
1021                Some(0xE2) if is_separator(&b[self.pos..]) => {
1022                    self.error(
1023                        "unterminated-regexp",
1024                        start,
1025                        "a regular expression has no closing / on its line",
1026                    );
1027                    return self.token(Kind::RegExp, start, Flags::empty());
1028                }
1029                Some(b'\\') => {
1030                    self.pos += 1;
1031                    match b.get(self.pos) {
1032                        None | Some(b'\n' | b'\r') => {}
1033                        Some(0xE2) if is_separator(&b[self.pos..]) => {}
1034                        Some(_) => self.pos += self.char_at(self.pos).len_utf8(),
1035                    }
1036                }
1037                Some(b'[') => {
1038                    class = true;
1039                    self.pos += 1;
1040                }
1041                Some(b']') => {
1042                    class = false;
1043                    self.pos += 1;
1044                }
1045                Some(b'/') if !class => {
1046                    self.pos += 1;
1047                    break;
1048                }
1049                Some(_) => self.pos += 1,
1050            }
1051        }
1052        // The flags: IdentifierPartChars, of which only dgimsuyv mean
1053        // anything, each once, and not u with v.
1054        let flags_at = self.pos;
1055        let mut seen = 0u8;
1056        let mut bad = false;
1057        while let Some(&c) = b.get(self.pos) {
1058            if c == b'\\' {
1059                let at = self.pos;
1060                self.pos += 1;
1061                if b.get(self.pos) == Some(&b'u') {
1062                    self.pos += 1;
1063                    self.unicode_escape();
1064                }
1065                self.error(
1066                    "invalid-regexp-flags",
1067                    at,
1068                    "regular expression flags can't be escaped",
1069                );
1070                continue;
1071            }
1072            let ch = self.char_at(self.pos);
1073            if !(c < 0x80 && ID_CONTINUE_ASCII[c as usize] || c >= 0x80 && is_id_continue(ch)) {
1074                break;
1075            }
1076            let bit = "dgimsuyv".find(ch).map(|i| 1u8 << i);
1077            match bit {
1078                Some(bit) if seen & bit == 0 => seen |= bit,
1079                _ => bad = true,
1080            }
1081            self.pos += ch.len_utf8();
1082        }
1083        if bad || seen & 0b1010_0000 == 0b1010_0000 {
1084            self.error(
1085                "invalid-regexp-flags",
1086                flags_at,
1087                "regular expression flags are d, g, i, m, s, u, v and y, each at most once, and not both u and v",
1088            );
1089        }
1090        self.token(Kind::RegExp, start, Flags::empty())
1091    }
1092
1093    // Punctuators (12.8).
1094
1095    /// The longest punctuator at `start` of those that can be longer
1096    /// than one character; the caller has handled the rest, and `/`,
1097    /// `/=` and `}` with a template goal.
1098    fn punctuator(&mut self, start: usize) -> Option<Punct> {
1099        let b = &self.src.as_bytes()[start..];
1100        let at = |i: usize| b.get(i).copied().unwrap_or(0);
1101        use Punct::*;
1102        let (len, p) = match (b[0], at(1), at(2), at(3)) {
1103            (b'.', b'.', b'.', _) => (3, Ellipsis),
1104            (b'.', ..) => (1, Dot),
1105            (b'<', b'<', b'=', _) => (3, ShlEq),
1106            (b'<', b'<', ..) => (2, Shl),
1107            (b'<', b'=', ..) => (2, LtEq),
1108            (b'<', ..) => (1, Lt),
1109            (b'>', b'>', b'>', b'=') => (4, UShrEq),
1110            (b'>', b'>', b'>', _) => (3, UShr),
1111            (b'>', b'>', b'=', _) => (3, ShrEq),
1112            (b'>', b'>', ..) => (2, Shr),
1113            (b'>', b'=', ..) => (2, GtEq),
1114            (b'>', ..) => (1, Gt),
1115            (b'=', b'=', b'=', _) => (3, EqEqEq),
1116            (b'=', b'=', ..) => (2, EqEq),
1117            (b'=', b'>', ..) => (2, Arrow),
1118            (b'=', ..) => (1, Eq),
1119            (b'!', b'=', b'=', _) => (3, NotEqEq),
1120            (b'!', b'=', ..) => (2, NotEq),
1121            (b'!', ..) => (1, Bang),
1122            (b'+', b'+', ..) => (2, PlusPlus),
1123            (b'+', b'=', ..) => (2, PlusEq),
1124            (b'+', ..) => (1, Plus),
1125            (b'-', b'-', ..) => (2, MinusMinus),
1126            (b'-', b'=', ..) => (2, MinusEq),
1127            (b'-', ..) => (1, Minus),
1128            (b'*', b'*', b'=', _) => (3, StarStarEq),
1129            (b'*', b'*', ..) => (2, StarStar),
1130            (b'*', b'=', ..) => (2, StarEq),
1131            (b'*', ..) => (1, Star),
1132            (b'%', b'=', ..) => (2, PercentEq),
1133            (b'%', ..) => (1, Percent),
1134            (b'&', b'&', b'=', _) => (3, AmpAmpEq),
1135            (b'&', b'&', ..) => (2, AmpAmp),
1136            (b'&', b'=', ..) => (2, AmpEq),
1137            (b'&', ..) => (1, Amp),
1138            (b'|', b'|', b'=', _) => (3, PipePipeEq),
1139            (b'|', b'|', ..) => (2, PipePipe),
1140            (b'|', b'=', ..) => (2, PipeEq),
1141            (b'|', ..) => (1, Pipe),
1142            (b'^', b'=', ..) => (2, CaretEq),
1143            (b'^', ..) => (1, Caret),
1144            (b'?', b'?', b'=', _) => (3, QuestionQuestionEq),
1145            (b'?', b'?', ..) => (2, QuestionQuestion),
1146            // `?.` isn't optional chaining before a digit: `a?.5:b`.
1147            (b'?', b'.', c, _) if !c.is_ascii_digit() => (2, QuestionDot),
1148            (b'?', ..) => (1, Question),
1149            _ => return None,
1150        };
1151        self.pos += len;
1152        Some(p)
1153    }
1154}
1155
1156/// How many bytes from the start of `b` are none of `quote`, `\\`, LF
1157/// and CR: what a string literal holds before it ends, or might end or
1158/// escape. Eight bytes at a time, by the bit trick that finds a zero
1159/// byte in a word (a byte equal to `t` is a zero byte of `word ^ t`).
1160#[inline(always)]
1161fn string_run(b: &[u8], quote: u8) -> usize {
1162    const ONES: u64 = u64::from_ne_bytes([0x01; 8]);
1163    const HIGHS: u64 = u64::from_ne_bytes([0x80; 8]);
1164    // Its lowest set bit is the high bit of the first zero byte; bits
1165    // above that may be wrong, and aren't looked at.
1166    let zero_bytes = |v: u64| v.wrapping_sub(ONES) & !v & HIGHS;
1167    let stops = [quote, b'\\', b'\n', b'\r'].map(|t| ONES * u64::from(t));
1168    let mut i = 0;
1169    while let Some(&chunk) = b.get(i..).and_then(|r| r.first_chunk::<8>()) {
1170        let w = u64::from_le_bytes(chunk);
1171        let found = stops.iter().fold(0, |m, &t| m | zero_bytes(w ^ t));
1172        if found != 0 {
1173            return i + (found.trailing_zeros() / 8) as usize;
1174        }
1175        i += 8;
1176    }
1177    i + b[i..]
1178        .iter()
1179        .position(|&c| c == quote || matches!(c, b'\\' | b'\n' | b'\r'))
1180        .unwrap_or(b.len() - i)
1181}
1182
1183/// How many bytes from the start of `b` are ASCII IdentifierPart
1184/// characters: letters, digits, `$` and `_`. Eight bytes at a time, so
1185/// the loop doesn't branch on every byte and the end of a short name
1186/// isn't a guess the processor gets wrong.
1187fn ident_run(b: &[u8]) -> usize {
1188    const L: u64 = u64::from_ne_bytes([0x01; 8]);
1189    const LOW7: u64 = L * 0x7F;
1190    const HIGHS: u64 = L * 0x80;
1191    // Lowercase for letters, and `$` and `_` in every byte.
1192    const CASE: u64 = L * 0x20;
1193    const DOLLARS: u64 = L * b'$' as u64;
1194    const UNDERSCORES: u64 = L * b'_' as u64;
1195    // The high bit of each byte of `x` that's above `lo` and below `hi`,
1196    // exactly, for bytes below 0x80 (Sean Anderson's bit hacks).
1197    let between = |x: u64, lo: u64, hi: u64| {
1198        let low = x & LOW7;
1199        (L * (127 + hi)).wrapping_sub(low) & !x & (low + L * (127 - lo)) & HIGHS
1200    };
1201    // The high bit of each zero byte of `v`, exactly: no borrow crosses
1202    // bytes, as it does in the trick `string_run` uses.
1203    let zero = |v: u64| !(((v & LOW7) + LOW7) | v | LOW7);
1204    let mut i = 0;
1205    while let Some(&chunk) = b.get(i..).and_then(|r| r.first_chunk::<8>()) {
1206        let w = u64::from_le_bytes(chunk);
1207        let part = between(w | CASE, 0x60, 0x7B)
1208            | between(w, 0x2F, 0x3A)
1209            | zero(w ^ DOLLARS)
1210            | zero(w ^ UNDERSCORES);
1211        let stop = !part & HIGHS;
1212        if stop != 0 {
1213            return i + (stop.trailing_zeros() / 8) as usize;
1214        }
1215        i += 8;
1216    }
1217    let rest = b.get(i..).unwrap_or_default();
1218    i + rest
1219        .iter()
1220        .position(|&c| c >= 0x80 || !ID_CONTINUE_ASCII[c as usize])
1221        .unwrap_or(rest.len())
1222}
1223
1224/// U+2028 or U+2029 at the start of `b`.
1225fn is_separator(b: &[u8]) -> bool {
1226    b.len() >= 3 && b[0] == 0xE2 && b[1] == 0x80 && (b[2] == 0xA8 || b[2] == 0xA9)
1227}
1228
1229/// WhiteSpace above ASCII: ZWNBSP and the Space_Separator characters.
1230fn is_whitespace(c: char) -> bool {
1231    matches!(
1232        c,
1233        '\u{A0}' | '\u{1680}' | '\u{2000}'
1234            ..='\u{200A}' | '\u{202F}' | '\u{205F}' | '\u{3000}' | '\u{FEFF}'
1235    )
1236}
1237
1238/// IdentifierPart in ASCII: letters, digits, `$` and `_`.
1239static ID_CONTINUE_ASCII: [bool; 128] = {
1240    let mut t = [false; 128];
1241    let mut c = 0;
1242    while c < 128 {
1243        let b = c as u8;
1244        t[c] = b.is_ascii_alphanumeric() || b == b'$' || b == b'_';
1245        c += 1;
1246    }
1247    t
1248};
1249
1250fn in_table(table: &[u32], c: u32) -> bool {
1251    // The last range starting at or before `c`.
1252    let pairs = table.len() / 2;
1253    let i = {
1254        let (mut lo, mut hi) = (0, pairs);
1255        while lo < hi {
1256            let mid = (lo + hi) / 2;
1257            if table[2 * mid] <= c {
1258                lo = mid + 1;
1259            } else {
1260                hi = mid;
1261            }
1262        }
1263        lo
1264    };
1265    i > 0 && c <= table[2 * (i - 1) + 1]
1266}
1267
1268/// IdentifierStartChar without `\`: ID_Start, `$` or `_`.
1269pub(crate) fn is_id_start(c: char) -> bool {
1270    match c {
1271        'a'..='z' | 'A'..='Z' | '$' | '_' => true,
1272        '\0'..='\x7F' => false,
1273        _ => in_table(unicode::ID_START, c as u32),
1274    }
1275}
1276
1277/// IdentifierPartChar without `\`: ID_Continue, `$`, ZWNJ or ZWJ.
1278pub(crate) fn is_id_continue(c: char) -> bool {
1279    match c {
1280        '\0'..='\x7F' => ID_CONTINUE_ASCII[c as usize],
1281        '\u{200C}' | '\u{200D}' => true,
1282        _ => in_table(unicode::ID_CONTINUE, c as u32),
1283    }
1284}
1285
1286#[cfg(test)]
1287mod tests {
1288    use super::*;
1289
1290    #[test]
1291    fn string_runs() {
1292        let naive = |b: &[u8], q: u8| {
1293            b.iter()
1294                .position(|&c| c == q || matches!(c, b'\\' | b'\n' | b'\r'))
1295                .unwrap_or(b.len())
1296        };
1297        // Every stop byte at every offset of inputs around the word size,
1298        // with near misses (0x80, the bytes one off) around it.
1299        for len in 0..20 {
1300            for at in 0..=len {
1301                for stop in *b"\"'\\\n\r" {
1302                    let mut b: Vec<u8> = (0..len)
1303                        .map(|i| [b'a', 0x80, b'#', b'[', 0xFF][i % 5])
1304                        .collect();
1305                    if at < len {
1306                        b[at] = stop;
1307                    }
1308                    for q in *b"\"'" {
1309                        assert_eq!(string_run(&b, q), naive(&b, q), "{b:?} {q}");
1310                    }
1311                }
1312            }
1313        }
1314    }
1315
1316    #[test]
1317    fn ident_runs() {
1318        let naive = |b: &[u8]| {
1319            b.iter()
1320                .position(|&c| c >= 0x80 || !ID_CONTINUE_ASCII[c as usize])
1321                .unwrap_or(b.len())
1322        };
1323        // Every byte value at every offset of names around the word size,
1324        // after every byte that may come before it.
1325        for len in 0..20 {
1326            for at in 0..=len {
1327                for stop in 0..=255u8 {
1328                    for before in [b'a', b'z', b'0', b'9', b'$', b'_', b'%', 0xFF] {
1329                        let mut b = vec![b'k'; len];
1330                        if at < len {
1331                            b[at] = stop;
1332                            if at > 0 {
1333                                b[at - 1] = before;
1334                            }
1335                        }
1336                        assert_eq!(ident_run(&b), naive(&b), "{b:?}");
1337                    }
1338                }
1339            }
1340        }
1341    }
1342
1343    #[test]
1344    fn unicode_tables() {
1345        for c in [
1346            'é',
1347            'Ω',
1348            'ж',
1349            '中',
1350            'ㄱ',
1351            '\u{2118}',
1352            '\u{1E900}',
1353            '\u{30000}',
1354        ] {
1355            assert!(is_id_start(c), "{c:?}");
1356            assert!(is_id_continue(c), "{c:?}");
1357        }
1358        // Continue only: combining marks and digits of other scripts.
1359        for c in ['\u{300}', '\u{660}', '\u{200C}', '\u{200D}', '\u{B7}'] {
1360            assert!(!is_id_start(c) && is_id_continue(c), "{c:?}");
1361        }
1362        for c in ['\u{A0}', '€', '😀', '\u{2028}', '\u{FEFF}', '\u{10FFFF}'] {
1363            assert!(!is_id_start(c) && !is_id_continue(c), "{c:?}");
1364        }
1365        // The tables are sorted ranges.
1366        for t in [unicode::ID_START, unicode::ID_CONTINUE] {
1367            assert!(t.len() % 2 == 0);
1368            assert!(t.windows(2).all(|w| w[0] <= w[1]));
1369        }
1370    }
1371}