parsec-js 0.3.0

JavaScript for Parsec: a parser for ECMAScript 2025 scripts and modules to a syntax tree with a span on every node, ESTree JSON out, and the lexer under it.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 James Conway

//! The lexer: ECMA-262's lexical grammar (clause 12) and Annex B's
//! additions to it (B.1), one token per call.

use parsec_base::{Diagnostic, Limits, Severity, Span};

use crate::token::{Flags, Keyword, Kind, Punct, Token};
use crate::unicode;

/// Which of the lexical grammar's goal symbols to read the next token
/// with. The grammar is ambiguous without one: `/` divides after an
/// expression and starts a regular expression anywhere else, and `}`
/// closes a block unless it ends a template substitution. The parser
/// knows which; the lexer is told and never guesses.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Goal {
    /// InputElementDiv: `/` and `/=` are punctuators, `}` is a punctuator.
    Div,
    /// InputElementRegExp: `/` starts a regular expression.
    RegExp,
    /// InputElementTemplateTail: `}` starts a TemplateMiddle or TemplateTail.
    TemplateTail,
    /// InputElementRegExpOrTemplateTail: both.
    RegExpOrTemplateTail,
}

impl Goal {
    const fn regexp(self) -> bool {
        matches!(self, Goal::RegExp | Goal::RegExpOrTemplateTail)
    }

    const fn template_tail(self) -> bool {
        matches!(self, Goal::TemplateTail | Goal::RegExpOrTemplateTail)
    }
}

/// Whether the source is a Script or a Module. Modules are strict, and
/// Annex B's HTML-like comments are a syntax error in them.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SourceType {
    #[default]
    Script,
    Module,
}

/// Reads tokens from a source, one per [`Lexer::next_token`].
///
/// It never fails: a token it can't read whole comes back as far as it
/// goes (a string with no closing quote ends at the end of the line), or
/// as [`Kind::Invalid`], and a [`Diagnostic`] says what was wrong. Time is
/// linear in the input, and nothing is allocated per token; only a
/// diagnostic is.
///
/// ```
/// use parsec_js::{Goal, Kind, Lexer, Punct, SourceType};
///
/// let src = "a / b; /b/g";
/// let mut lexer = Lexer::new(src, SourceType::Script);
/// let kinds: Vec<Kind> = [Goal::RegExp, Goal::Div, Goal::RegExp, Goal::Div, Goal::RegExp]
///     .into_iter()
///     .map(|goal| lexer.next_token(goal).kind)
///     .collect();
/// assert_eq!(kinds[1], Kind::Punct(Punct::Slash));
/// assert_eq!(kinds[4], Kind::RegExp);
/// assert!(lexer.diagnostics().is_empty());
/// ```
#[derive(Clone, Debug)]
pub struct Lexer<'a> {
    src: &'a str,
    pos: usize,
    source: SourceType,
    /// A line terminator since the last token that wasn't trivia.
    newline: bool,
    /// Only whitespace and comments without line terminators since the
    /// last line terminator: where Annex B lets `-->` start a comment.
    line_start: bool,
    /// An identifier with an escape has been read, so a name's text may
    /// not be its name.
    escaped_ident: bool,
    diagnostics: Vec<Diagnostic>,
}

impl<'a> Lexer<'a> {
    pub fn new(src: &'a str, source: SourceType) -> Lexer<'a> {
        Lexer::with_limits(src, source, &Limits::default())
    }

    /// A lexer that refuses input longer than `limits.max_input`, or than
    /// spans can hold: it reports `input-too-large` and gives only
    /// [`Kind::Eof`].
    pub fn with_limits(src: &'a str, source: SourceType, limits: &Limits) -> Lexer<'a> {
        let mut diagnostics = Vec::new();
        let src = match limits.check_input(src.len()) {
            Ok(()) => src,
            Err(d) => {
                diagnostics.push(d);
                ""
            }
        };
        Lexer {
            src,
            pos: 0,
            source,
            newline: false,
            // InputElementHashbangOrRegExp, the goal at the start, has
            // HTMLCloseComment: `-->` can start the first line too.
            line_start: true,
            escaped_ident: false,
            diagnostics,
        }
    }

    pub fn source(&self) -> &'a str {
        self.src
    }

    /// The byte offset the next token is read from.
    pub fn position(&self) -> u32 {
        self.pos as u32
    }

    /// What's been reported so far, in the order it was found.
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }

    /// Whether any identifier read so far had an escape in it. Until one
    /// has, every identifier's text is its name.
    pub(crate) fn escaped_ident(&self) -> bool {
        self.escaped_ident
    }

    pub fn take_diagnostics(&mut self) -> Vec<Diagnostic> {
        std::mem::take(&mut self.diagnostics)
    }

    /// Reads `token`, the last token read, again with `goal`: the parser
    /// read a `/` or `}` with [`Goal::Div`] and then found it starts a
    /// regular expression or carries a template on. Reading either with
    /// `Div` reports nothing, so there's nothing to take back.
    pub(crate) fn rescan(&mut self, token: Token, goal: Goal) -> Token {
        debug_assert_eq!(self.pos, token.span.end as usize);
        self.pos = token.span.start as usize;
        self.newline = token.newline_before();
        self.line_start = false;
        self.next_token(goal)
    }

    /// A lexer reading on from here, with none of the diagnostics so far,
    /// for looking a token ahead.
    pub(crate) fn fork(&self) -> Lexer<'a> {
        Lexer {
            src: self.src,
            pos: self.pos,
            source: self.source,
            newline: self.newline,
            line_start: self.line_start,
            escaped_ident: self.escaped_ident,
            diagnostics: Vec::new(),
        }
    }

    /// A lexer reading from byte `pos`, as from the start of a line when
    /// `newline` says one is before it.
    pub(crate) fn starting_at(&self, pos: u32, newline: bool) -> Lexer<'a> {
        Lexer {
            src: self.src,
            pos: pos as usize,
            source: self.source,
            newline,
            line_start: newline,
            escaped_ident: self.escaped_ident,
            diagnostics: Vec::new(),
        }
    }

    /// The next token, read with `goal`. Comments and a hashbang come
    /// back as tokens too ([`Kind::is_trivia`]); whitespace and line
    /// terminators don't, but [`Token::newline_before`] says where a line
    /// terminator was.
    pub fn next_token(&mut self, goal: Goal) -> Token {
        if self.pos == 0 && self.src.starts_with("#!") {
            return self.rest_of_line(Kind::Hashbang, 0, 2);
        }
        if !self.skip_whitespace() {
            return self.after_unicode(goal);
        }
        let start = self.pos;
        let b = self.src.as_bytes();
        let Some(&c) = b.get(start) else {
            return self.token(Kind::Eof, start, Flags::empty());
        };
        let script = self.source == SourceType::Script;
        let kind = match c {
            b'/' => match b.get(start + 1) {
                Some(b'/') => return self.rest_of_line(Kind::LineComment, start, 2),
                Some(b'*') => return self.block_comment(start),
                _ if goal.regexp() => return self.regexp(start),
                Some(b'=') => self.punct(2, Punct::SlashEq),
                _ => self.punct(1, Punct::Slash),
            },
            // Annex B's HTML-like comments, in scripts only: in a module
            // `<!--` is `<` `!` `--` and `-->` is `--` `>`.
            b'<' if script && b[start..].starts_with(b"<!--") => {
                return self.rest_of_line(Kind::HtmlOpenComment, start, 4);
            }
            b'-' if script && self.line_start && b[start..].starts_with(b"-->") => {
                return self.rest_of_line(Kind::HtmlCloseComment, start, 3);
            }
            b'a'..=b'z' | b'A'..=b'Z' | b'$' | b'_' | b'\\' => return self.ident(start),
            b'0'..=b'9' => return self.number(start),
            b'.' if b.get(start + 1).is_some_and(u8::is_ascii_digit) => return self.number(start),
            b'"' | b'\'' => return self.string(start, c),
            b'`' => return self.template(start, false),
            b'}' if goal.template_tail() => return self.template(start, true),
            b'#' => return self.private_name(start),
            // The punctuators that are one character whatever follows,
            // most of them, without the lookahead the others need.
            b'{' => self.punct(1, Punct::LBrace),
            b'}' => self.punct(1, Punct::RBrace),
            b'(' => self.punct(1, Punct::LParen),
            b')' => self.punct(1, Punct::RParen),
            b'[' => self.punct(1, Punct::LBracket),
            b']' => self.punct(1, Punct::RBracket),
            b';' => self.punct(1, Punct::Semicolon),
            b',' => self.punct(1, Punct::Comma),
            b':' => self.punct(1, Punct::Colon),
            b'~' => self.punct(1, Punct::Tilde),
            0x80.. => return self.non_ascii(start),
            _ => match self.punctuator(start) {
                Some(p) => Kind::Punct(p),
                None => return self.unexpected_character(start, 1),
            },
        };
        self.token(kind, start, Flags::empty())
    }

    // What `next_token` leaves out of line, so the registers these need
    // aren't saved and restored for every token.

    /// A comment or hashbang `skip` bytes long to start, to the end of
    /// its line.
    #[inline(never)]
    fn rest_of_line(&mut self, kind: Kind, start: usize, skip: usize) -> Token {
        self.pos = self.line_end(start + skip);
        self.trivia(kind, start, false)
    }

    /// A token starting with a character above ASCII.
    #[inline(never)]
    fn non_ascii(&mut self, start: usize) -> Token {
        let ch = self.char_at(start);
        if is_id_start(ch) {
            return self.ident(start);
        }
        self.unexpected_character(start, ch.len_utf8())
    }

    #[cold]
    #[inline(never)]
    fn unexpected_character(&mut self, start: usize, len: usize) -> Token {
        self.pos += len;
        self.error(
            "unexpected-character",
            start,
            "this character can't start a token",
        );
        self.token(Kind::Invalid, start, Flags::empty())
    }

    // Helpers that end a token.

    fn token(&mut self, kind: Kind, start: usize, mut flags: Flags) -> Token {
        if self.newline {
            flags.insert(Flags::NEWLINE_BEFORE);
        }
        self.newline = false;
        self.line_start = false;
        Token {
            kind,
            flags,
            span: Span::new(start as u32, self.pos as u32),
        }
    }

    /// A comment, which leaves the newline flag for the token after it,
    /// and sets it if the comment held a line terminator.
    fn trivia(&mut self, kind: Kind, start: usize, holds_newline: bool) -> Token {
        let flags = if self.newline {
            Flags::NEWLINE_BEFORE
        } else {
            Flags::empty()
        };
        if holds_newline {
            self.newline = true;
            self.line_start = true;
        } else if kind != Kind::BlockComment {
            // A line comment runs to a line terminator, which sets
            // line_start again when it's skipped.
            self.line_start = false;
        }
        Token {
            kind,
            flags,
            span: Span::new(start as u32, self.pos as u32),
        }
    }

    fn punct(&mut self, len: usize, p: Punct) -> Kind {
        self.pos += len;
        Kind::Punct(p)
    }

    fn report(
        &mut self,
        code: &'static str,
        severity: Severity,
        start: usize,
        message: &'static str,
    ) {
        let span = Span::new(start as u32, self.pos.max(start) as u32);
        self.diagnostics
            .push(Diagnostic::new(code, severity, span, message));
    }

    fn error(&mut self, code: &'static str, start: usize, message: &'static str) {
        self.report(code, Severity::Error, start, message);
    }

    /// A legacy form: an error in a module, a warning in a script, whose
    /// strictness only the parser knows.
    fn legacy(&mut self, code: &'static str, start: usize, message: &'static str) {
        let severity = match self.source {
            SourceType::Module => Severity::Error,
            SourceType::Script => Severity::Warning,
        };
        self.report(code, severity, start, message);
    }

    // Characters.

    fn char_at(&self, at: usize) -> char {
        self.src[at..].chars().next().unwrap_or('\0')
    }

    /// The offset of the first line terminator at or after `from`, or the
    /// end.
    fn line_end(&self, from: usize) -> usize {
        let b = self.src.as_bytes();
        let mut i = from;
        while i < b.len() {
            match b[i] {
                b'\n' | b'\r' => return i,
                0xE2 if is_separator(&b[i..]) => return i,
                _ => i += 1,
            }
        }
        i
    }

    /// Whitespace and line terminators (12.2, 12.3) in ASCII. False if it
    /// stopped at a character above ASCII, which may be either.
    #[inline(always)]
    fn skip_whitespace(&mut self) -> bool {
        let b = self.src.as_bytes();
        while let Some(&c) = b.get(self.pos) {
            match c {
                b' ' | b'\t' | 0x0B | 0x0C => self.pos += 1,
                b'\n' | b'\r' => {
                    self.pos += 1;
                    self.newline = true;
                    self.line_start = true;
                    // The spaces of the indent after it, a word at a time:
                    // the count is the run of zero bytes at the bottom of
                    // the word with the spaces taken out.
                    const SPACES: u64 = u64::from_ne_bytes([b' '; 8]);
                    while let Some(&w) = b.get(self.pos..).and_then(|r| r.first_chunk::<8>()) {
                        let n = (u64::from_le_bytes(w) ^ SPACES).trailing_zeros() as usize / 8;
                        self.pos += n;
                        if n < 8 {
                            break;
                        }
                    }
                }
                0x80.. => return false,
                _ => return true,
            }
        }
        true
    }

    /// The next token from a character above ASCII, after any whitespace
    /// and line terminators from there. Out of line, so `next_token`
    /// calls nothing before it reads a token and saves no registers.
    #[inline(never)]
    fn after_unicode(&mut self, goal: Goal) -> Token {
        while self.unicode_space() {
            if self.skip_whitespace() {
                // At ASCII that isn't whitespace, or the end: one call
                // deep, as there's nothing to skip there.
                return self.next_token(goal);
            }
        }
        self.non_ascii(self.pos)
    }

    /// Skips the whitespace or line terminator above ASCII at `pos`, if
    /// that's what's there.
    fn unicode_space(&mut self) -> bool {
        let ch = self.char_at(self.pos);
        if matches!(ch, '\u{2028}' | '\u{2029}') {
            self.newline = true;
            self.line_start = true;
        } else if !is_whitespace(ch) {
            return false;
        }
        self.pos += ch.len_utf8();
        true
    }

    // Comments (12.4, B.1.1).

    fn block_comment(&mut self, start: usize) -> Token {
        let b = self.src.as_bytes();
        let mut i = start + 2;
        let mut newline = false;
        loop {
            match b.get(i) {
                None => {
                    self.pos = i;
                    self.error(
                        "unterminated-comment",
                        start,
                        "a /* comment has no closing */",
                    );
                    break;
                }
                Some(b'*') if b.get(i + 1) == Some(&b'/') => {
                    self.pos = i + 2;
                    break;
                }
                Some(b'\n' | b'\r') => newline = true,
                Some(0xE2) if is_separator(&b[i..]) => newline = true,
                _ => {}
            }
            i += 1;
        }
        self.trivia(Kind::BlockComment, start, newline)
    }

    // Identifiers (12.7) and private names.

    fn private_name(&mut self, start: usize) -> Token {
        let next = self.pos + 1;
        let starts_ident = match self.src.as_bytes().get(next) {
            Some(b'a'..=b'z' | b'A'..=b'Z' | b'$' | b'_' | b'\\') => true,
            Some(0x80..) => is_id_start(self.char_at(next)),
            _ => false,
        };
        if !starts_ident {
            self.pos = next;
            self.error(
                "unexpected-character",
                start,
                "# starts a private name, like #x",
            );
            return self.token(Kind::Invalid, start, Flags::empty());
        }
        let ident = self.ident(next);
        // An escape that isn't one is reported already; the name is still
        // a name.
        Token {
            kind: Kind::PrivateName,
            span: Span::new(start as u32, ident.span.end),
            ..ident
        }
    }

    fn ident(&mut self, start: usize) -> Token {
        let b = self.src.as_bytes();
        // Most identifiers are plain ASCII: read those in a tight loop,
        // and leave escapes and other characters to the loop below.
        // No indexing that could panic either: that's a call to save
        // registers for.
        let rest = b.get(start..).unwrap_or_default();
        if let Some((b'a'..=b'z' | b'A'..=b'Z' | b'$' | b'_', tail)) = rest.split_first() {
            let len = 1 + ident_run(tail);
            if !matches!(rest.get(len), Some(b'\\' | 0x80..)) {
                self.pos = start + len;
                let kind = Keyword::from_prefix(rest, len).map_or(Kind::Ident, Kind::Keyword);
                return self.token(kind, start, Flags::empty());
            }
        }
        self.ident_slow(start)
    }

    /// An identifier with an escape or a character above ASCII in it.
    /// Out of line, so plain ones save no registers for it.
    #[inline(never)]
    fn ident_slow(&mut self, start: usize) -> Token {
        let b = self.src.as_bytes();
        let mut flags = Flags::empty();
        self.pos = start;
        let mut first = true;
        loop {
            match b.get(self.pos) {
                Some(&c) if c < 0x80 && ID_CONTINUE_ASCII[c as usize] => {
                    if first && c.is_ascii_digit() {
                        break;
                    }
                    self.pos += 1;
                }
                Some(b'\\') => {
                    let at = self.pos;
                    flags.insert(Flags::ESCAPED);
                    self.pos += 1;
                    let ok = if b.get(self.pos) == Some(&b'u') {
                        self.pos += 1;
                        self.unicode_escape()
                            .and_then(char::from_u32)
                            .is_some_and(|ch| {
                                if first {
                                    is_id_start(ch) || ch == '$' || ch == '_'
                                } else {
                                    is_id_continue(ch)
                                }
                            })
                    } else {
                        false
                    };
                    if !ok {
                        if first && self.pos == at + 1 {
                            // A lone `\`: no identifier at all.
                            self.error("invalid-escape", at, "\\ here has to start a \\u escape");
                            return self.token(Kind::Invalid, start, Flags::empty());
                        }
                        self.error(
                            "invalid-identifier-escape",
                            at,
                            "this escape isn't a character an identifier can have here",
                        );
                    }
                }
                Some(0x80..) => {
                    let ch = self.char_at(self.pos);
                    if !(if first {
                        is_id_start(ch)
                    } else {
                        is_id_continue(ch)
                    }) {
                        break;
                    }
                    self.pos += ch.len_utf8();
                }
                _ => break,
            }
            first = false;
        }
        self.escaped_ident |= flags.contains(Flags::ESCAPED);
        let kind = match flags.contains(Flags::ESCAPED) {
            false => Keyword::from_bytes(&b[start..self.pos]).map_or(Kind::Ident, Kind::Keyword),
            true => Kind::Ident,
        };
        self.token(kind, start, flags)
    }

    /// After `\u`: four hex digits, or hex digits in braces up to
    /// 10FFFF. It consumes only hex digits and the braces, so a bad escape
    /// never swallows the quote or backtick after it.
    fn unicode_escape(&mut self) -> Option<u32> {
        let b = self.src.as_bytes();
        if b.get(self.pos) == Some(&b'{') {
            self.pos += 1;
            let mut value: u32 = 0;
            let mut digits = 0;
            while let Some(d) = b.get(self.pos).and_then(|&c| (c as char).to_digit(16)) {
                value = value.saturating_mul(16).saturating_add(d).min(0x11_0000);
                digits += 1;
                self.pos += 1;
            }
            if digits == 0 || b.get(self.pos) != Some(&b'}') {
                return None;
            }
            self.pos += 1;
            (value <= 0x10_FFFF).then_some(value)
        } else {
            self.hex_digits(4)
        }
    }

    /// Exactly `n` hex digits, consuming the ones there are up to `n`.
    fn hex_digits(&mut self, n: usize) -> Option<u32> {
        let b = self.src.as_bytes();
        let mut value = 0;
        for _ in 0..n {
            let d = b.get(self.pos).and_then(|&c| (c as char).to_digit(16))?;
            value = value * 16 + d;
            self.pos += 1;
        }
        Some(value)
    }

    // Numeric literals (12.9.3, B.1.1).

    fn number(&mut self, start: usize) -> Token {
        // Most numbers are decimal digits with nothing after them that
        // could go on with the number: those need none of the registers
        // the rest does.
        let b = self.src.as_bytes();
        if b[start] != b'.' {
            let mut end = start + 1;
            if b[start] != b'0' {
                while b.get(end).is_some_and(u8::is_ascii_digit) {
                    end += 1;
                }
            }
            let plain = b.get(end).is_none_or(|&c| {
                c < 0x80 && !c.is_ascii_alphanumeric() && !matches!(c, b'.' | b'$' | b'_' | b'\\')
            });
            if plain {
                self.pos = end;
                return self.token(Kind::Number, start, Flags::empty());
            }
        }
        self.number_rest(start)
    }

    /// A number from `start` that isn't only decimal digits.
    #[inline(never)]
    fn number_rest(&mut self, start: usize) -> Token {
        let b = self.src.as_bytes();
        let mut flags = Flags::empty();
        let mut kind = Kind::Number;
        self.pos = start;
        let radix = match (b[start], b.get(start + 1).map(u8::to_ascii_lowercase)) {
            (b'0', Some(b'x')) => 16,
            (b'0', Some(b'o')) => 8,
            (b'0', Some(b'b')) => 2,
            _ => 10,
        };
        if radix != 10 {
            self.pos += 2;
            if self.digits(radix) == 0 {
                self.error(
                    "missing-digits",
                    start,
                    "a number needs digits after its prefix",
                );
            }
            if b.get(self.pos) == Some(&b'n') {
                self.pos += 1;
                kind = Kind::BigInt;
            }
        } else if b[start] == b'0' && b.get(start + 1).is_some_and(u8::is_ascii_digit) {
            // A legacy octal literal (017), or a decimal one with a leading
            // zero (08, 09.5), which has a fraction and exponent like any.
            self.pos += 1;
            let mut octal = true;
            while let Some(&c) = b.get(self.pos).filter(|c| c.is_ascii_digit()) {
                octal &= c < b'8';
                self.pos += 1;
            }
            flags.insert(Flags::LEGACY_OCTAL);
            if octal {
                self.legacy(
                    "legacy-octal-literal",
                    start,
                    "legacy octal literals like 017 aren't allowed in strict code; write 0o17",
                );
            } else {
                self.legacy(
                    "leading-zero-literal",
                    start,
                    "decimal literals with a leading zero aren't allowed in strict code",
                );
                self.fraction_and_exponent();
            }
        } else {
            let mut integer = true;
            if b[start] == b'0' {
                self.pos += 1;
            } else if b[start] != b'.' {
                self.digits(10);
            }
            if b.get(self.pos) == Some(&b'.') {
                integer = false;
            }
            integer &= !self.fraction_and_exponent();
            if integer && b.get(self.pos) == Some(&b'n') {
                self.pos += 1;
                kind = Kind::BigInt;
            }
        }
        // The SourceCharacter after a NumericLiteral can't be an
        // IdentifierStart or a digit: `3in`, `1_`, `0b12` and `1.5n` are all
        // errors. The rest of the word goes in the token.
        let bad = match b.get(self.pos) {
            Some(c) if c.is_ascii_digit() => true,
            Some(b'a'..=b'z' | b'A'..=b'Z' | b'$' | b'_' | b'\\') => true,
            Some(0x80..) => is_id_start(self.char_at(self.pos)),
            _ => false,
        };
        if bad {
            let at = self.pos;
            while let Some(&c) = b.get(self.pos) {
                if c < 0x80 && ID_CONTINUE_ASCII[c as usize] {
                    self.pos += 1;
                } else if c >= 0x80 && is_id_continue(self.char_at(self.pos)) {
                    self.pos += self.char_at(self.pos).len_utf8();
                } else {
                    break;
                }
            }
            self.pos = self.pos.max(at + 1);
            self.error(
                "identifier-after-number",
                at,
                "a number can't be followed straight away by a letter or digit",
            );
        }
        self.token(kind, start, flags)
    }

    /// `.digits` and `e±digits`, if they're there. Whether either was.
    fn fraction_and_exponent(&mut self) -> bool {
        let b = self.src.as_bytes();
        let mut any = false;
        if b.get(self.pos) == Some(&b'.') {
            self.pos += 1;
            self.digits(10);
            any = true;
        }
        if matches!(b.get(self.pos), Some(b'e' | b'E')) {
            let at = self.pos;
            self.pos += 1;
            if matches!(b.get(self.pos), Some(b'+' | b'-')) {
                self.pos += 1;
            }
            if self.digits(10) == 0 {
                self.error("missing-exponent", at, "an exponent needs digits");
            }
            any = true;
        }
        any
    }

    /// Digits in `radix`, with `_` separators between two of them. How
    /// many digits there were.
    fn digits(&mut self, radix: u32) -> usize {
        let b = self.src.as_bytes();
        let mut count = 0;
        loop {
            match b.get(self.pos) {
                Some(&c) if (c as char).is_digit(radix) => {
                    count += 1;
                    self.pos += 1;
                }
                Some(b'_') => {
                    let next_digit = b
                        .get(self.pos + 1)
                        .is_some_and(|&c| (c as char).is_digit(radix));
                    let prev_digit = count > 0 && b[self.pos - 1] != b'_';
                    if !(prev_digit && next_digit) {
                        let at = self.pos;
                        self.pos += 1;
                        self.error(
                            "invalid-numeric-separator",
                            at,
                            "a _ in a number has to be between two digits",
                        );
                        if !next_digit {
                            return count;
                        }
                    } else {
                        self.pos += 1;
                    }
                }
                _ => return count,
            }
        }
    }

    // String literals (12.9.4, B.1.2).

    #[inline(never)]
    fn string(&mut self, start: usize, quote: u8) -> Token {
        // Most strings end at the first byte that might end one, with no
        // escape: those need none of the registers the rest does.
        let b = self.src.as_bytes();
        let end = start + 1 + string_run(&b[start + 1..], quote);
        if b.get(end) == Some(&quote) {
            self.pos = end + 1;
            return self.token(Kind::String, start, Flags::empty());
        }
        self.pos = end;
        self.string_rest(start, quote)
    }

    /// The rest of a string from `start`, from a byte at `pos` that
    /// might end it or start an escape.
    #[inline(never)]
    fn string_rest(&mut self, start: usize, quote: u8) -> Token {
        let b = self.src.as_bytes();
        let mut flags = Flags::empty();
        loop {
            // Skip what can't end the string or start an escape at once:
            // long strings in inline scripts are mostly that.
            self.pos += string_run(&b[self.pos..], quote);
            match b.get(self.pos) {
                None | Some(b'\n' | b'\r') => {
                    self.error(
                        "unterminated-string",
                        start,
                        "a string has no closing quote on its line",
                    );
                    break;
                }
                Some(&c) if c == quote => {
                    self.pos += 1;
                    break;
                }
                Some(b'\\') => {
                    flags.insert(Flags::ESCAPED);
                    self.pos += 1;
                    self.string_escape(&mut flags);
                }
                Some(_) => self.pos += 1,
            }
        }
        self.token(Kind::String, start, flags)
    }

    /// After a `\` in a string.
    fn string_escape(&mut self, flags: &mut Flags) {
        let b = self.src.as_bytes();
        let at = self.pos - 1;
        match b.get(self.pos) {
            None => {}
            Some(b'\r') => {
                self.pos += 1;
                if b.get(self.pos) == Some(&b'\n') {
                    self.pos += 1;
                }
            }
            Some(b'x') => {
                self.pos += 1;
                if self.hex_digits(2).is_none() {
                    self.error("invalid-escape", at, "\\x needs two hex digits");
                }
            }
            Some(b'u') => {
                self.pos += 1;
                if self.unicode_escape().is_none() {
                    self.error(
                        "invalid-escape",
                        at,
                        "\\u needs four hex digits, or hex digits in braces up to 10FFFF",
                    );
                }
            }
            Some(b'0') if !b.get(self.pos + 1).is_some_and(u8::is_ascii_digit) => self.pos += 1,
            Some(&c @ b'0'..=b'7') => {
                // ZeroToThree OctalDigit OctalDigit at most, or FourToSeven
                // OctalDigit.
                let max = if c <= b'3' { 3 } else { 2 };
                let mut n = 0;
                while n < max && b.get(self.pos).is_some_and(|c| (b'0'..=b'7').contains(c)) {
                    self.pos += 1;
                    n += 1;
                }
                flags.insert(Flags::LEGACY_OCTAL);
                self.legacy(
                    "legacy-octal-escape",
                    at,
                    "octal escapes like \\01 aren't allowed in strict code",
                );
            }
            Some(b'8' | b'9') => {
                self.pos += 1;
                flags.insert(Flags::LEGACY_OCTAL);
                self.legacy(
                    "legacy-octal-escape",
                    at,
                    "\\8 and \\9 aren't allowed in strict code",
                );
            }
            Some(_) => self.pos += self.char_at(self.pos).len_utf8(),
        }
    }

    // Templates (12.9.6).

    /// From `` ` `` or, for a middle or tail, from `}`.
    fn template(&mut self, start: usize, continued: bool) -> Token {
        // Most templates in minified code are strings in backquotes, with
        // no escape or substitution: those need none of the registers
        // the rest does.
        let b = self.src.as_bytes();
        let mut end = start + 1;
        while b
            .get(end)
            .is_some_and(|c| !matches!(c, b'`' | b'\\' | b'$'))
        {
            end += 1;
        }
        self.pos = end;
        if b.get(end) == Some(&b'`') {
            self.pos += 1;
            let kind = if continued {
                Kind::TemplateTail
            } else {
                Kind::Template
            };
            return self.token(kind, start, Flags::empty());
        }
        self.template_rest(start, continued)
    }

    /// The rest of a template part from `start`, from a `\`, a `$` or the
    /// end of the input at `pos`.
    #[inline(never)]
    fn template_rest(&mut self, start: usize, continued: bool) -> Token {
        let b = self.src.as_bytes();
        let mut flags = Flags::empty();
        let kind = loop {
            match b.get(self.pos) {
                None => {
                    self.error(
                        "unterminated-template",
                        start,
                        "a template has no closing `",
                    );
                    break if continued {
                        Kind::TemplateTail
                    } else {
                        Kind::Template
                    };
                }
                Some(b'`') => {
                    self.pos += 1;
                    break if continued {
                        Kind::TemplateTail
                    } else {
                        Kind::Template
                    };
                }
                Some(b'$') if b.get(self.pos + 1) == Some(&b'{') => {
                    self.pos += 2;
                    break if continued {
                        Kind::TemplateMiddle
                    } else {
                        Kind::TemplateHead
                    };
                }
                Some(b'\\') => {
                    flags.insert(Flags::ESCAPED);
                    self.pos += 1;
                    if !self.template_escape() {
                        flags.insert(Flags::INVALID_ESCAPE);
                    }
                }
                Some(_) => self.pos += 1,
            }
        };
        self.token(kind, start, flags)
    }

    /// After a `\` in a template: whether it's an escape sequence and not
    /// a NotEscapeSequence.
    fn template_escape(&mut self) -> bool {
        let b = self.src.as_bytes();
        match b.get(self.pos) {
            None => true,
            Some(b'x') => {
                self.pos += 1;
                self.hex_digits(2).is_some()
            }
            Some(b'u') => {
                self.pos += 1;
                self.unicode_escape().is_some()
            }
            Some(b'0') if !b.get(self.pos + 1).is_some_and(u8::is_ascii_digit) => {
                self.pos += 1;
                true
            }
            // `\0` before a digit, and `\1` to `\9`: the digit is the
            // escape, and what follows is template text again.
            Some(b'0'..=b'9') => {
                self.pos += 1;
                false
            }
            // A line continuation, CRLF included, or any other character.
            Some(_) => {
                self.pos += self.char_at(self.pos).len_utf8();
                if b[self.pos - 1] == b'\r' && b.get(self.pos) == Some(&b'\n') {
                    self.pos += 1;
                }
                true
            }
        }
    }

    // Regular expression literals (12.9.5).

    fn regexp(&mut self, start: usize) -> Token {
        let b = self.src.as_bytes();
        self.pos = start + 1;
        let mut class = false;
        loop {
            match b.get(self.pos) {
                None | Some(b'\n' | b'\r') => {
                    self.error(
                        "unterminated-regexp",
                        start,
                        "a regular expression has no closing / on its line",
                    );
                    return self.token(Kind::RegExp, start, Flags::empty());
                }
                Some(0xE2) if is_separator(&b[self.pos..]) => {
                    self.error(
                        "unterminated-regexp",
                        start,
                        "a regular expression has no closing / on its line",
                    );
                    return self.token(Kind::RegExp, start, Flags::empty());
                }
                Some(b'\\') => {
                    self.pos += 1;
                    match b.get(self.pos) {
                        None | Some(b'\n' | b'\r') => {}
                        Some(0xE2) if is_separator(&b[self.pos..]) => {}
                        Some(_) => self.pos += self.char_at(self.pos).len_utf8(),
                    }
                }
                Some(b'[') => {
                    class = true;
                    self.pos += 1;
                }
                Some(b']') => {
                    class = false;
                    self.pos += 1;
                }
                Some(b'/') if !class => {
                    self.pos += 1;
                    break;
                }
                Some(_) => self.pos += 1,
            }
        }
        // The flags: IdentifierPartChars, of which only dgimsuyv mean
        // anything, each once, and not u with v.
        let flags_at = self.pos;
        let mut seen = 0u8;
        let mut bad = false;
        while let Some(&c) = b.get(self.pos) {
            if c == b'\\' {
                let at = self.pos;
                self.pos += 1;
                if b.get(self.pos) == Some(&b'u') {
                    self.pos += 1;
                    self.unicode_escape();
                }
                self.error(
                    "invalid-regexp-flags",
                    at,
                    "regular expression flags can't be escaped",
                );
                continue;
            }
            let ch = self.char_at(self.pos);
            if !(c < 0x80 && ID_CONTINUE_ASCII[c as usize] || c >= 0x80 && is_id_continue(ch)) {
                break;
            }
            let bit = "dgimsuyv".find(ch).map(|i| 1u8 << i);
            match bit {
                Some(bit) if seen & bit == 0 => seen |= bit,
                _ => bad = true,
            }
            self.pos += ch.len_utf8();
        }
        if bad || seen & 0b1010_0000 == 0b1010_0000 {
            self.error(
                "invalid-regexp-flags",
                flags_at,
                "regular expression flags are d, g, i, m, s, u, v and y, each at most once, and not both u and v",
            );
        }
        self.token(Kind::RegExp, start, Flags::empty())
    }

    // Punctuators (12.8).

    /// The longest punctuator at `start` of those that can be longer
    /// than one character; the caller has handled the rest, and `/`,
    /// `/=` and `}` with a template goal.
    fn punctuator(&mut self, start: usize) -> Option<Punct> {
        let b = &self.src.as_bytes()[start..];
        let at = |i: usize| b.get(i).copied().unwrap_or(0);
        use Punct::*;
        let (len, p) = match (b[0], at(1), at(2), at(3)) {
            (b'.', b'.', b'.', _) => (3, Ellipsis),
            (b'.', ..) => (1, Dot),
            (b'<', b'<', b'=', _) => (3, ShlEq),
            (b'<', b'<', ..) => (2, Shl),
            (b'<', b'=', ..) => (2, LtEq),
            (b'<', ..) => (1, Lt),
            (b'>', b'>', b'>', b'=') => (4, UShrEq),
            (b'>', b'>', b'>', _) => (3, UShr),
            (b'>', b'>', b'=', _) => (3, ShrEq),
            (b'>', b'>', ..) => (2, Shr),
            (b'>', b'=', ..) => (2, GtEq),
            (b'>', ..) => (1, Gt),
            (b'=', b'=', b'=', _) => (3, EqEqEq),
            (b'=', b'=', ..) => (2, EqEq),
            (b'=', b'>', ..) => (2, Arrow),
            (b'=', ..) => (1, Eq),
            (b'!', b'=', b'=', _) => (3, NotEqEq),
            (b'!', b'=', ..) => (2, NotEq),
            (b'!', ..) => (1, Bang),
            (b'+', b'+', ..) => (2, PlusPlus),
            (b'+', b'=', ..) => (2, PlusEq),
            (b'+', ..) => (1, Plus),
            (b'-', b'-', ..) => (2, MinusMinus),
            (b'-', b'=', ..) => (2, MinusEq),
            (b'-', ..) => (1, Minus),
            (b'*', b'*', b'=', _) => (3, StarStarEq),
            (b'*', b'*', ..) => (2, StarStar),
            (b'*', b'=', ..) => (2, StarEq),
            (b'*', ..) => (1, Star),
            (b'%', b'=', ..) => (2, PercentEq),
            (b'%', ..) => (1, Percent),
            (b'&', b'&', b'=', _) => (3, AmpAmpEq),
            (b'&', b'&', ..) => (2, AmpAmp),
            (b'&', b'=', ..) => (2, AmpEq),
            (b'&', ..) => (1, Amp),
            (b'|', b'|', b'=', _) => (3, PipePipeEq),
            (b'|', b'|', ..) => (2, PipePipe),
            (b'|', b'=', ..) => (2, PipeEq),
            (b'|', ..) => (1, Pipe),
            (b'^', b'=', ..) => (2, CaretEq),
            (b'^', ..) => (1, Caret),
            (b'?', b'?', b'=', _) => (3, QuestionQuestionEq),
            (b'?', b'?', ..) => (2, QuestionQuestion),
            // `?.` isn't optional chaining before a digit: `a?.5:b`.
            (b'?', b'.', c, _) if !c.is_ascii_digit() => (2, QuestionDot),
            (b'?', ..) => (1, Question),
            _ => return None,
        };
        self.pos += len;
        Some(p)
    }
}

/// How many bytes from the start of `b` are none of `quote`, `\\`, LF
/// and CR: what a string literal holds before it ends, or might end or
/// escape. Eight bytes at a time, by the bit trick that finds a zero
/// byte in a word (a byte equal to `t` is a zero byte of `word ^ t`).
#[inline(always)]
fn string_run(b: &[u8], quote: u8) -> usize {
    const ONES: u64 = u64::from_ne_bytes([0x01; 8]);
    const HIGHS: u64 = u64::from_ne_bytes([0x80; 8]);
    // Its lowest set bit is the high bit of the first zero byte; bits
    // above that may be wrong, and aren't looked at.
    let zero_bytes = |v: u64| v.wrapping_sub(ONES) & !v & HIGHS;
    let stops = [quote, b'\\', b'\n', b'\r'].map(|t| ONES * u64::from(t));
    let mut i = 0;
    while let Some(&chunk) = b.get(i..).and_then(|r| r.first_chunk::<8>()) {
        let w = u64::from_le_bytes(chunk);
        let found = stops.iter().fold(0, |m, &t| m | zero_bytes(w ^ t));
        if found != 0 {
            return i + (found.trailing_zeros() / 8) as usize;
        }
        i += 8;
    }
    i + b[i..]
        .iter()
        .position(|&c| c == quote || matches!(c, b'\\' | b'\n' | b'\r'))
        .unwrap_or(b.len() - i)
}

/// How many bytes from the start of `b` are ASCII IdentifierPart
/// characters: letters, digits, `$` and `_`. Eight bytes at a time, so
/// the loop doesn't branch on every byte and the end of a short name
/// isn't a guess the processor gets wrong.
fn ident_run(b: &[u8]) -> usize {
    const L: u64 = u64::from_ne_bytes([0x01; 8]);
    const LOW7: u64 = L * 0x7F;
    const HIGHS: u64 = L * 0x80;
    // Lowercase for letters, and `$` and `_` in every byte.
    const CASE: u64 = L * 0x20;
    const DOLLARS: u64 = L * b'$' as u64;
    const UNDERSCORES: u64 = L * b'_' as u64;
    // The high bit of each byte of `x` that's above `lo` and below `hi`,
    // exactly, for bytes below 0x80 (Sean Anderson's bit hacks).
    let between = |x: u64, lo: u64, hi: u64| {
        let low = x & LOW7;
        (L * (127 + hi)).wrapping_sub(low) & !x & (low + L * (127 - lo)) & HIGHS
    };
    // The high bit of each zero byte of `v`, exactly: no borrow crosses
    // bytes, as it does in the trick `string_run` uses.
    let zero = |v: u64| !(((v & LOW7) + LOW7) | v | LOW7);
    let mut i = 0;
    while let Some(&chunk) = b.get(i..).and_then(|r| r.first_chunk::<8>()) {
        let w = u64::from_le_bytes(chunk);
        let part = between(w | CASE, 0x60, 0x7B)
            | between(w, 0x2F, 0x3A)
            | zero(w ^ DOLLARS)
            | zero(w ^ UNDERSCORES);
        let stop = !part & HIGHS;
        if stop != 0 {
            return i + (stop.trailing_zeros() / 8) as usize;
        }
        i += 8;
    }
    let rest = b.get(i..).unwrap_or_default();
    i + rest
        .iter()
        .position(|&c| c >= 0x80 || !ID_CONTINUE_ASCII[c as usize])
        .unwrap_or(rest.len())
}

/// U+2028 or U+2029 at the start of `b`.
fn is_separator(b: &[u8]) -> bool {
    b.len() >= 3 && b[0] == 0xE2 && b[1] == 0x80 && (b[2] == 0xA8 || b[2] == 0xA9)
}

/// WhiteSpace above ASCII: ZWNBSP and the Space_Separator characters.
fn is_whitespace(c: char) -> bool {
    matches!(
        c,
        '\u{A0}' | '\u{1680}' | '\u{2000}'
            ..='\u{200A}' | '\u{202F}' | '\u{205F}' | '\u{3000}' | '\u{FEFF}'
    )
}

/// IdentifierPart in ASCII: letters, digits, `$` and `_`.
static ID_CONTINUE_ASCII: [bool; 128] = {
    let mut t = [false; 128];
    let mut c = 0;
    while c < 128 {
        let b = c as u8;
        t[c] = b.is_ascii_alphanumeric() || b == b'$' || b == b'_';
        c += 1;
    }
    t
};

fn in_table(table: &[u32], c: u32) -> bool {
    // The last range starting at or before `c`.
    let pairs = table.len() / 2;
    let i = {
        let (mut lo, mut hi) = (0, pairs);
        while lo < hi {
            let mid = (lo + hi) / 2;
            if table[2 * mid] <= c {
                lo = mid + 1;
            } else {
                hi = mid;
            }
        }
        lo
    };
    i > 0 && c <= table[2 * (i - 1) + 1]
}

/// IdentifierStartChar without `\`: ID_Start, `$` or `_`.
pub(crate) fn is_id_start(c: char) -> bool {
    match c {
        'a'..='z' | 'A'..='Z' | '$' | '_' => true,
        '\0'..='\x7F' => false,
        _ => in_table(unicode::ID_START, c as u32),
    }
}

/// IdentifierPartChar without `\`: ID_Continue, `$`, ZWNJ or ZWJ.
pub(crate) fn is_id_continue(c: char) -> bool {
    match c {
        '\0'..='\x7F' => ID_CONTINUE_ASCII[c as usize],
        '\u{200C}' | '\u{200D}' => true,
        _ => in_table(unicode::ID_CONTINUE, c as u32),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn string_runs() {
        let naive = |b: &[u8], q: u8| {
            b.iter()
                .position(|&c| c == q || matches!(c, b'\\' | b'\n' | b'\r'))
                .unwrap_or(b.len())
        };
        // Every stop byte at every offset of inputs around the word size,
        // with near misses (0x80, the bytes one off) around it.
        for len in 0..20 {
            for at in 0..=len {
                for stop in *b"\"'\\\n\r" {
                    let mut b: Vec<u8> = (0..len)
                        .map(|i| [b'a', 0x80, b'#', b'[', 0xFF][i % 5])
                        .collect();
                    if at < len {
                        b[at] = stop;
                    }
                    for q in *b"\"'" {
                        assert_eq!(string_run(&b, q), naive(&b, q), "{b:?} {q}");
                    }
                }
            }
        }
    }

    #[test]
    fn ident_runs() {
        let naive = |b: &[u8]| {
            b.iter()
                .position(|&c| c >= 0x80 || !ID_CONTINUE_ASCII[c as usize])
                .unwrap_or(b.len())
        };
        // Every byte value at every offset of names around the word size,
        // after every byte that may come before it.
        for len in 0..20 {
            for at in 0..=len {
                for stop in 0..=255u8 {
                    for before in [b'a', b'z', b'0', b'9', b'$', b'_', b'%', 0xFF] {
                        let mut b = vec![b'k'; len];
                        if at < len {
                            b[at] = stop;
                            if at > 0 {
                                b[at - 1] = before;
                            }
                        }
                        assert_eq!(ident_run(&b), naive(&b), "{b:?}");
                    }
                }
            }
        }
    }

    #[test]
    fn unicode_tables() {
        for c in [
            'é',
            'Ω',
            'ж',
            '中',
            'ㄱ',
            '\u{2118}',
            '\u{1E900}',
            '\u{30000}',
        ] {
            assert!(is_id_start(c), "{c:?}");
            assert!(is_id_continue(c), "{c:?}");
        }
        // Continue only: combining marks and digits of other scripts.
        for c in ['\u{300}', '\u{660}', '\u{200C}', '\u{200D}', '\u{B7}'] {
            assert!(!is_id_start(c) && is_id_continue(c), "{c:?}");
        }
        for c in ['\u{A0}', '€', '😀', '\u{2028}', '\u{FEFF}', '\u{10FFFF}'] {
            assert!(!is_id_start(c) && !is_id_continue(c), "{c:?}");
        }
        // The tables are sorted ranges.
        for t in [unicode::ID_START, unicode::ID_CONTINUE] {
            assert!(t.len() % 2 == 0);
            assert!(t.windows(2).all(|w| w[0] <= w[1]));
        }
    }
}