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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 James Conway

//! The parser: ECMA-262's syntactic grammar, clauses 13 to 16, with
//! Annex B's additions for scripts, by recursive descent.
//!
//! The parser asks the lexer for one token at a time, always with
//! [`Goal::Div`], and reads a `/` or `}` again with the goal it turns
//! out to need: a regular expression where an expression starts, a
//! template's next part after a substitution. Nothing else is ever read
//! twice.
//!
//! The cover grammars are parsed once, as what they cover: `(a, b)` is
//! parsed as an expression and turned into arrow parameters in place when
//! `=>` follows, `[a, b]` into a pattern when `=` does. Errors that only
//! the expression reading has, like `{a = 1}` outside a pattern, wait in
//! [`Parser::pending`] until it's known which reading it is.
//!
//! The first error ends the parse, unless it's [`parse_recovering`]:
//! then a statement that fails is skipped to where the next one starts,
//! and the parse goes on to report more. Recursion is counted against a
//! depth limit, and tokens against the step budget, so no input
//! overflows the stack or runs past what it was allowed, recovering or
//! not.

mod expr;
mod function;
mod module;
mod pattern;
mod stmt;

use std::borrow::Cow;
use std::cell::Cell;
use std::collections::HashMap;

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

use crate::ast::{Ast, Comment, CommentKind, List, Node, NodeId};
use crate::lexer::{Goal, Lexer, SourceType};
use crate::text;
use crate::token::{Flags, Keyword, Kind, Punct, Token};

/// How deep the parser recurses when [`Limits::max_depth`] doesn't say.
/// A level is a statement, a function or class, an operand of a prefix
/// operator or `**`, or an expression or pattern nested in brackets.
/// Real code stays far below it (typescript.js, 9 MB, needs 53), and at
/// the limit the parser uses at most about 250 KB of stack in a release
/// build and 700 KB in a debug one, so it fits a 1 MB thread. A higher
/// limit needs a thread with more: about 1 KB a level in a release
/// build, 3 KB in a debug one.
pub const DEFAULT_MAX_DEPTH: u32 = 256;

/// What to parse and how much it may cost.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Options {
    /// A module is strict, may `await` at the top, and has `import` and
    /// `export` declarations there.
    pub source_type: SourceType,
    /// `max_depth` is how deep the tree may nest, [`DEFAULT_MAX_DEPTH`]
    /// without one; `max_steps` bounds the tokens read; `max_input` the
    /// bytes.
    pub limits: Limits,
}

/// Parses `src` as a Script or a Module, as `options` says. The first
/// syntax error is the `Err`.
///
/// ```
/// use parsec_js::{Node, Options, parse};
///
/// let ast = parse("let x = a?.b ?? 1;", &Options::default()).unwrap();
/// let Node::Program { body, .. } = *ast.node(ast.root()) else { unreachable!() };
/// assert_eq!(ast.get(body).len(), 1);
///
/// let err = parse("let x = ;", &Options::default()).unwrap_err();
/// assert_eq!((err.code, err.span.start), ("unexpected-token", 8));
/// ```
pub fn parse(src: &str, options: &Options) -> Result<Ast, Diagnostic> {
    Parser::new(src, options).parse()
}

/// Parses `src` as a Script.
pub fn parse_script(src: &str) -> Result<Ast, Diagnostic> {
    parse(src, &Options::default())
}

/// Parses `src` as [`parse`] does, but goes on after a syntax error to
/// find the rest: every error, in the order found, is the `Err`.
///
/// After an error the parser skips to where the next statement starts:
/// past a `;`, to a `}` that closes the block it's in, or to a statement
/// keyword at the start of a line. Errors after the first can follow
/// from it, as with any compiler; the first is the one [`parse`] gives.
/// A program with no errors parses to the same tree as with [`parse`].
///
/// ```
/// use parsec_js::{Options, parse_recovering};
///
/// let src = "let a = ;\nlet b = 2;\nif (b { go() }\n";
/// let errors = parse_recovering(src, &Options::default()).unwrap_err();
/// let codes: Vec<_> = errors.iter().map(|d| (d.code, d.span.start)).collect();
/// assert_eq!(codes, [("unexpected-token", 8), ("unexpected-token", 27)]);
/// ```
pub fn parse_recovering(src: &str, options: &Options) -> Result<Ast, Vec<Diagnostic>> {
    let mut p = Parser::new(src, options);
    p.recover = true;
    p.parse_all()
}

/// Where [`parse_piece`] starts, and what the parser knew there when it
/// parsed the whole source.
pub(crate) struct Resume {
    pub start: u32,
    /// A function body from its `{`, or else a StatementListItem.
    pub body: bool,
    pub ctx: Ctx,
    /// The labels around it in its function: name, where, on a loop.
    pub labels: Vec<(String, Span, bool)>,
    /// How many class bodies are around it.
    pub classes: usize,
    /// The depth to start at, and the most allowed.
    pub depth: u32,
    pub max_depth: u32,
}

/// What [`parse_piece`] parsed: its nodes, lists, comments and warnings,
/// the root last; where it ends; and the private names it uses that a
/// class around it has to declare.
pub(crate) struct Piece {
    pub ast: Ast,
    pub end: u32,
    pub private_names: Vec<String>,
}

/// Parses one function body or statement of `src` from `r.start`, as
/// the whole parse would there, into a tree of its own: `None` if it
/// fails. Its lists start at 1, so an empty one made there and one
/// that's `List::default()` stay apart.
pub(crate) fn parse_piece(src: &str, options: &Options, r: Resume) -> Option<Piece> {
    let mut p = Parser::with_room(src, options, 64);
    p.ast.lists.push(NodeId::new(1));
    p.lexer = p.lexer.starting_at(r.start, false);
    p.ctx = r.ctx;
    p.labels = r
        .labels
        .into_iter()
        .map(|(name, span, is_loop)| Label {
            name,
            span,
            is_loop,
        })
        .collect();
    p.classes = (0..r.classes).map(|_| ClassScope::default()).collect();
    p.depth = r.depth;
    p.max_depth = r.max_depth;
    let root = p.piece(r.body).ok()?;
    if root.index() + 1 != p.ast.nodes.len() {
        return None;
    }
    let end = p.prev_end;
    let mut private_names = Vec::new();
    for scope in p.classes.drain(..) {
        private_names.extend(scope.used.into_iter().map(|(name, _)| name));
    }
    let mut ast = p.ast;
    // The token after the piece was read too, and its comments.
    ast.comments.retain(|c| c.span.start < end);
    ast.warnings = p
        .lexer
        .take_diagnostics()
        .into_iter()
        .filter(|d| d.severity == Severity::Warning && d.span.start < end)
        .collect();
    ast.root = Some(root);
    Some(Piece {
        ast,
        end,
        private_names,
    })
}

/// The parse ended; the diagnostic is in [`Parser::error`].
#[derive(Debug)]
pub(crate) struct Stop;

pub(crate) type R<T> = Result<T, Stop>;

/// What the grammar's parameters and the enclosing function allow here.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct Ctx {
    pub strict: bool,
    /// `[Yield]`: `yield` is an operator.
    pub yield_: bool,
    /// `[Await]`: `await` is an operator.
    pub await_: bool,
    /// `[Return]`.
    pub ret: bool,
    pub new_target: bool,
    pub super_prop: bool,
    pub super_call: bool,
    /// In a class field's initializer or a static block, where
    /// `arguments` is an error.
    pub no_arguments: bool,
    /// In a class static block, where `await` is reserved.
    pub static_block: bool,
    /// Enclosing loops, and loops and switches, in this function.
    pub loops: u32,
    pub breakable: u32,
    /// Where this function's labels start in [`Parser::labels`].
    pub labels: usize,
}

/// A label in scope, where it is, and whether it labels a loop.
struct Label {
    name: String,
    span: Span,
    is_loop: bool,
}

/// What kind of class element a private name names.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Private {
    Field,
    Method,
    Get,
    Set,
    GetSet,
}

/// A class body being parsed: its private names, and the ones used in
/// it that might be declared later in it or in a class around it.
#[derive(Default)]
struct ClassScope {
    declared: HashMap<String, (Private, bool, Span)>,
    used: Vec<(String, Span)>,
}

thread_local! {
    /// The last parse's list scratch, empty, for the next on this thread.
    static SPARE_SCRATCH: Cell<Vec<NodeId>> = const { Cell::new(Vec::new()) };
}

/// The parser's list scratch, the items of every list still being
/// parsed. It never leaves the parser, so each thread keeps one for its
/// next parse: allocating and freeing it was a sixth of what a parse of
/// a few bytes cost. One grown past 4,096 items isn't kept.
struct Scratch(Vec<NodeId>);

impl Scratch {
    fn take() -> Scratch {
        // `try_with`: a parse in a thread-local's destructor has no spare.
        let mut v = SPARE_SCRATCH.try_with(Cell::take).unwrap_or_default();
        if v.capacity() == 0 {
            v.reserve(64);
        }
        Scratch(v)
    }
}

impl Drop for Scratch {
    fn drop(&mut self) {
        let mut v = std::mem::take(&mut self.0);
        if v.capacity() <= 4096 {
            v.clear();
            let _ = SPARE_SCRATCH.try_with(|spare| spare.set(v));
        }
    }
}

impl std::ops::Deref for Scratch {
    type Target = Vec<NodeId>;

    fn deref(&self) -> &Vec<NodeId> {
        &self.0
    }
}

impl std::ops::DerefMut for Scratch {
    fn deref_mut(&mut self) -> &mut Vec<NodeId> {
        &mut self.0
    }
}

pub(crate) struct Parser<'a> {
    src: &'a str,
    lexer: Lexer<'a>,
    /// The token being looked at.
    tok: Token,
    /// The end of the last token consumed.
    prev_end: u32,
    ast: Ast,
    /// Children of lists being built, innermost at the end.
    scratch: Scratch,
    /// Buffers for the early errors on bound names, kept between uses so
    /// checking a declaration allocates nothing.
    names: Vec<Span>,
    sorted_names: Vec<(Cow<'a, str>, Span)>,
    /// The `if`s of `else if` chains being parsed, innermost at the end.
    if_chain: Vec<(u32, NodeId, NodeId)>,
    error: Option<Diagnostic>,
    /// Going on after errors, for [`parse_recovering`], and the errors
    /// found so far.
    recover: bool,
    errors: Vec<Diagnostic>,
    /// How many of the lexer's diagnostics have been looked at.
    seen: usize,
    module: bool,
    ctx: Ctx,
    depth: u32,
    max_depth: u32,
    budget: Budget,
    labels: Vec<Label>,
    /// Where the labels directly on the statement about to be parsed
    /// start, so a loop can mark them all as labelling a loop.
    label_chain: Option<usize>,
    /// Where the expression statement being parsed starts, whose first
    /// identifier may be a label rather than a reference.
    label_candidate: Option<u32>,
    /// The statement about to be parsed is the body of an `if`, a loop
    /// or a `with`, where a labelled function declaration is an error.
    in_body: bool,
    /// Object literals with something only a pattern may have (`{a = 1}`,
    /// a second `__proto__`), and where. An entry stands until the object
    /// turns into a pattern; one still an object when its expression ends
    /// is an error.
    pending: Vec<(NodeId, Span, &'static str)>,
    classes: Vec<ClassScope>,
    /// The names a module exports so far, and where.
    exports: HashMap<String, Span>,
    /// Where the last `yield` and `await` expressions, and the last
    /// `await` read as an identifier, started, for the parameter lists
    /// that may hold none of them.
    last_yield: Option<u32>,
    last_await: Option<u32>,
    last_await_ident: Option<u32>,
}

impl<'a> Parser<'a> {
    pub(crate) fn new(src: &'a str, options: &Options) -> Parser<'a> {
        // About one node per eight bytes of a large bundle, but small
        // scripts run denser, one per four or five, and growing the
        // vectors costs a short parse more than the room does: the first
        // 64 KB are sized at one per four, with 16 more for the tiniest.
        let len = match options.limits.check_input(src.len()) {
            Ok(()) => src.len(),
            Err(_) => 0,
        };
        Parser::with_room(
            src,
            options,
            16 + len.min(1 << 16) / 4 + len.saturating_sub(1 << 16) / 8,
        )
    }

    /// A parser whose tree has room for `nodes` nodes to start with.
    fn with_room(src: &'a str, options: &Options, nodes: usize) -> Parser<'a> {
        let lexer = Lexer::with_limits(src, options.source_type, &options.limits);
        let ast = Ast::new(nodes);
        let module = options.source_type == SourceType::Module;
        Parser {
            src: lexer.source(),
            lexer,
            tok: Token {
                kind: Kind::Eof,
                flags: Flags::empty(),
                span: Span::at(0),
            },
            prev_end: 0,
            ast,
            scratch: Scratch::take(),
            names: Vec::new(),
            sorted_names: Vec::new(),
            if_chain: Vec::new(),
            error: None,
            recover: false,
            errors: Vec::new(),
            seen: 0,
            module,
            ctx: Ctx {
                strict: module,
                await_: module,
                ..Ctx::default()
            },
            depth: 0,
            max_depth: options.limits.max_depth.unwrap_or(DEFAULT_MAX_DEPTH),
            budget: options.limits.budget(),
            labels: Vec::new(),
            label_chain: None,
            label_candidate: None,
            in_body: false,
            pending: Vec::new(),
            classes: Vec::new(),
            exports: HashMap::new(),
            last_yield: None,
            last_await: None,
            last_await_ident: None,
        }
    }

    pub(crate) fn parse(mut self) -> Result<Ast, Diagnostic> {
        let result = self.program();
        if let Err(Stop) = result {
            return Err(self.error.take().expect("a stop has a diagnostic"));
        }
        let mut ast = self.ast;
        ast.warnings = self
            .lexer
            .take_diagnostics()
            .into_iter()
            .filter(|d| d.severity == Severity::Warning)
            .collect();
        Ok(ast)
    }

    /// The piece [`parse_piece`] parses.
    fn piece(&mut self, body: bool) -> R<NodeId> {
        if let Some(d) = self.lexer.diagnostics().first() {
            return self.fail(d.clone());
        }
        self.advance()?;
        if body {
            self.function_body(List::default(), true, false, None)
        } else {
            self.statement_list_item()
        }
    }

    /// The parse for [`parse_recovering`].
    fn parse_all(mut self) -> Result<Ast, Vec<Diagnostic>> {
        let result = self.program();
        let mut errors = std::mem::take(&mut self.errors);
        if let Err(Stop) = result {
            errors.extend(self.error.take());
        }
        if !errors.is_empty() {
            return Err(errors);
        }
        let mut ast = self.ast;
        ast.warnings = self
            .lexer
            .take_diagnostics()
            .into_iter()
            .filter(|d| d.severity == Severity::Warning)
            .collect();
        Ok(ast)
    }

    fn program(&mut self) -> R<()> {
        // A lexer that refused the input has said why.
        if let Some(d) = self.lexer.diagnostics().first() {
            return self.fail(d.clone());
        }
        self.advance()?;
        let mark = self.scratch.len();
        self.statement_list(true)?;
        // Recovering, a `}` with nothing to close is one more error.
        while self.recover && self.at(Punct::RBrace) {
            let d = self.unexpected_diagnostic();
            self.errors.push(d);
            self.skip_token()?;
            self.statement_list(false)?;
        }
        if self.tok.kind != Kind::Eof {
            return self.unexpected();
        }
        let body = self.take_list(mark);
        let source_type = if self.module {
            SourceType::Module
        } else {
            SourceType::Script
        };
        let root = self.ast.push(
            Span::new(0, self.src.len() as u32),
            Node::Program { body, source_type },
        );
        self.ast.root = Some(root);
        Ok(())
    }

    // Errors.

    fn fail<T>(&mut self, d: Diagnostic) -> R<T> {
        if self.error.is_none() {
            self.error = Some(d);
        }
        Err(Stop)
    }

    fn err<T>(
        &mut self,
        code: &'static str,
        span: Span,
        message: impl Into<Cow<'static, str>>,
    ) -> R<T> {
        self.fail(Diagnostic::error(code, span, message))
    }

    /// An error at the token being looked at, which nothing here expects.
    fn unexpected<T>(&mut self) -> R<T> {
        let d = self.unexpected_diagnostic();
        self.fail(d)
    }

    fn unexpected_diagnostic(&self) -> Diagnostic {
        let t = self.tok;
        if t.kind == Kind::Eof {
            return Diagnostic::error(
                "unexpected-end",
                t.span,
                "the input ends in the middle of something",
            );
        }
        let text = t.text(self.src);
        let shown: String = text.chars().take(40).collect();
        Diagnostic::error(
            "unexpected-token",
            t.span,
            format!("`{shown}` can't go here"),
        )
    }

    /// `p`, inside the bracket `open` opened: an error here points back
    /// at it.
    fn expect_in(&mut self, p: Punct, open: Token) -> R<Token> {
        if self.at(p) {
            return self.bump();
        }
        self.unclosed(open)
    }

    #[cold]
    #[inline(never)]
    fn unclosed<T>(&mut self, open: Token) -> R<T> {
        let what = match open.kind {
            Kind::Punct(Punct::LParen) => "this `(` is still open",
            Kind::Punct(Punct::LBracket) => "this `[` is still open",
            _ => "this `{` is still open",
        };
        let d = self.unexpected_diagnostic().with_label(open.span, what);
        self.fail(d)
    }

    // Tokens.

    /// Reads the next token that isn't a comment, with [`Goal::Div`],
    /// into `tok`: straight there, and not through a `Result` and a
    /// copy or two on the stack.
    fn advance(&mut self) -> R<()> {
        self.tok = self.lexer.next_token(Goal::Div);
        self.check_lexer()?;
        if self.tok.is_trivia() {
            return self.after_comments();
        }
        Ok(())
    }

    /// Keeps `tok`, a comment, and any more after it, and reads the token
    /// that follows them into `tok`. Out of line, so the path for a token
    /// with no comment before it stays short.
    #[inline(never)]
    fn after_comments(&mut self) -> R<()> {
        loop {
            let t = self.tok;
            let kind = match t.kind {
                Kind::LineComment => CommentKind::Line,
                Kind::BlockComment => CommentKind::Block,
                Kind::Hashbang => CommentKind::Hashbang,
                Kind::HtmlOpenComment => CommentKind::HtmlOpen,
                Kind::HtmlCloseComment => CommentKind::HtmlClose,
                _ => return Ok(()),
            };
            self.ast.comments.push(Comment { kind, span: t.span });
            self.tok = self.lexer.next_token(Goal::Div);
            self.check_lexer()?;
        }
    }

    /// Stops at the first error the lexer has reported since last asked.
    /// It runs once a token, so the check is inlined and the rest isn't.
    #[inline(always)]
    fn check_lexer(&mut self) -> R<()> {
        if self.lexer.diagnostics().len() > self.seen {
            return self.lexer_reported();
        }
        Ok(())
    }

    #[cold]
    #[inline(never)]
    fn lexer_reported(&mut self) -> R<()> {
        let diagnostics = self.lexer.diagnostics();
        if diagnostics.len() > self.seen {
            let new = &diagnostics[self.seen..];
            self.seen = diagnostics.len();
            if let Some(d) = new.iter().find(|d| d.is_error()) {
                let d = d.clone();
                return self.fail(d);
            }
        }
        Ok(())
    }

    /// Consumes the token being looked at and returns it. Inlined, so a
    /// caller that wants the token keeps it, and `skip` keeps nothing
    /// across the call into the lexer.
    #[inline(always)]
    fn bump(&mut self) -> R<Token> {
        let t = self.tok;
        self.skip()?;
        Ok(t)
    }

    /// Consumes the token being looked at.
    #[inline(never)]
    fn skip(&mut self) -> R<()> {
        let spent = self.budget.spend(1).is_ok();
        if !spent || (self.tok.flags.contains(Flags::LEGACY_OCTAL) && self.ctx.strict) {
            return self.refuse_token(spent);
        }
        self.prev_end = self.tok.span.end;
        self.advance()
    }

    /// Why the token being looked at can't be consumed: the step budget
    /// ran out before it, or it's a legacy octal in strict code.
    #[cold]
    #[inline(never)]
    fn refuse_token(&mut self, spent: bool) -> R<()> {
        let span = self.tok.span;
        if !spent {
            return self.err(
                "step-budget",
                span,
                "the parse used up its step budget here",
            );
        }
        self.err(
            "legacy-octal-in-strict",
            span,
            "legacy octal literals and escapes aren't allowed in strict code",
        )
    }

    /// Reads the token being looked at, a `/` or `}`, again with `goal`.
    fn rescan(&mut self, goal: Goal) -> R<()> {
        self.tok = self.lexer.rescan(self.tok, goal);
        self.check_lexer()
    }

    /// The token after the one being looked at.
    fn peek(&self) -> Token {
        let mut lexer = self.lexer.fork();
        loop {
            let t = lexer.next_token(Goal::Div);
            if !t.is_trivia() {
                return t;
            }
        }
    }

    fn at(&self, p: Punct) -> bool {
        self.tok.kind == Kind::Punct(p)
    }

    /// The token is the keyword `k`, spelled without escapes.
    fn at_kw(&self, k: Keyword) -> bool {
        self.tok.kind == Kind::Keyword(k)
    }

    fn eat(&mut self, p: Punct) -> R<bool> {
        if self.at(p) {
            self.bump()?;
            return Ok(true);
        }
        Ok(false)
    }

    fn expect(&mut self, p: Punct) -> R<Token> {
        if self.at(p) {
            return self.bump();
        }
        self.unexpected()
    }

    fn expect_kw(&mut self, k: Keyword) -> R<Token> {
        if self.at_kw(k) {
            return self.bump();
        }
        self.unexpected()
    }

    /// A `;`, or where automatic semicolon insertion puts one: before a
    /// line break, a `}` or the end.
    fn semicolon(&mut self) -> R<()> {
        if self.eat(Punct::Semicolon)? {
            return Ok(());
        }
        if self.can_insert_semicolon() {
            return Ok(());
        }
        self.unexpected()
    }

    fn can_insert_semicolon(&self) -> bool {
        self.tok.newline_before() || self.at(Punct::RBrace) || self.tok.kind == Kind::Eof
    }

    // Nodes and lists.

    fn finish(&mut self, start: u32, node: Node) -> NodeId {
        self.ast
            .push(Span::new(start, self.prev_end.max(start)), node)
    }

    fn take_list(&mut self, mark: usize) -> List {
        self.ast.list(self.scratch.drain(mark..))
    }

    fn node(&self, id: NodeId) -> Node {
        *self.ast.node(id)
    }

    fn span(&self, id: NodeId) -> Span {
        self.ast.span(id)
    }

    // Limits.

    /// One level deeper, or an error past the limit.
    fn enter(&mut self) -> R<()> {
        self.depth += 1;
        if self.depth > self.max_depth {
            let span = self.tok.span;
            return self.err(
                "too-deep",
                span,
                format!("this nests deeper than the limit of {}", self.max_depth),
            );
        }
        Ok(())
    }

    fn leave(&mut self) {
        self.depth -= 1;
    }

    // Identifiers.

    /// An identifier's name, escapes decoded. Until the lexer has read
    /// an identifier with an escape, none has one to look for.
    fn name(&self, span: Span) -> Cow<'a, str> {
        let raw = span.text(self.src);
        if !self.lexer.escaped_ident() {
            return Cow::Borrowed(raw);
        }
        text::ident_name(raw)
    }

    /// Whether the identifier at `span` is `name`, escapes decoded. Only a
    /// longer spelling can hold an escape that decodes to `name`, and only
    /// once the lexer has read one, so most answers come from the lengths
    /// without decoding.
    fn name_is(&self, span: Span, name: &str) -> bool {
        let raw = span.text(self.src);
        match raw.len().cmp(&name.len()) {
            std::cmp::Ordering::Less => false,
            std::cmp::Ordering::Equal => raw == name,
            std::cmp::Ordering::Greater => {
                self.lexer.escaped_ident() && raw.contains('\\') && text::ident_name(raw) == name
            }
        }
    }

    /// The token is an IdentifierName: an identifier or any keyword.
    fn at_ident_name(&self) -> bool {
        matches!(self.tok.kind, Kind::Ident | Kind::Keyword(_))
    }

    /// The token could be an identifier reference here, though it may
    /// still be an error as one (a reserved word escaped, `yield` in
    /// strict code).
    fn at_identifier(&self) -> bool {
        match self.tok.kind {
            Kind::Ident => true,
            Kind::Keyword(k) => !k.is_reserved() || matches!(k, Keyword::Yield | Keyword::Await),
            _ => false,
        }
    }

    /// The word an identifier token spells, if it's one of [`Keyword`]'s,
    /// escapes decoded.
    fn word(&self, t: Token) -> Option<Keyword> {
        match t.kind {
            Kind::Keyword(k) => Some(k),
            Kind::Ident if t.flags.contains(Flags::ESCAPED) => {
                Keyword::from_str(&self.name(t.span))
            }
            _ => None,
        }
    }

    /// Checks `t` as an IdentifierReference, a BindingIdentifier when
    /// `binding`, or a LabelIdentifier, in this context. Most are a plain
    /// name with nothing to check, and that answer comes first, inline.
    #[inline(always)]
    fn check_identifier(&mut self, t: Token, binding: bool) -> R<()> {
        if t.kind == Kind::Ident
            && !t.flags.contains(Flags::ESCAPED)
            && !(binding && self.ctx.strict)
        {
            return Ok(());
        }
        self.check_word(t, binding)
    }

    /// [`Parser::check_identifier`] for a word, an escape, or a binding in
    /// strict code.
    #[inline(never)]
    fn check_word(&mut self, t: Token, binding: bool) -> R<()> {
        let word = self.word(t);
        let reserved = match word {
            None => false,
            Some(Keyword::Await) => {
                self.last_await_ident = Some(t.span.start);
                self.ctx.await_ || self.module || self.ctx.static_block
            }
            Some(Keyword::Yield) => self.ctx.yield_ || self.ctx.strict,
            Some(k) if k.is_strict_reserved() => self.ctx.strict,
            Some(k) => k.is_reserved(),
        };
        if reserved {
            let name = self.name(t.span).into_owned();
            return self.err(
                "reserved-word",
                t.span,
                format!("`{name}` is reserved here, so it can't be an identifier"),
            );
        }
        if word.is_none() && binding && self.ctx.strict {
            let name = self.name(t.span);
            if name == "eval" || name == "arguments" {
                return self.err(
                    "strict-binding",
                    t.span,
                    format!("strict code can't bind or assign `{name}`"),
                );
            }
        }
        Ok(())
    }

    /// `arguments` can't be referred to in a class field's initializer or
    /// a static block.
    fn check_arguments(&mut self, span: Span) -> R<()> {
        if self.ctx.no_arguments && self.name_is(span, "arguments") {
            return self.err(
                "arguments-in-class-init",
                span,
                "`arguments` isn't allowed in a class field or static block",
            );
        }
        Ok(())
    }

    /// The token as an identifier reference or binding, checked, as a node.
    fn identifier(&mut self, binding: bool) -> R<NodeId> {
        // A reserved word spelled plainly is no identifier, and saying
        // it's reserved would only confuse `if (a) else`.
        if !self.at_identifier() {
            return self.unexpected();
        }
        let t = self.tok;
        self.check_identifier(t, binding)?;
        self.bump()?;
        Ok(self.ast.push(t.span, Node::Identifier))
    }

    /// The token as an IdentifierName, any word at all, as a node.
    fn identifier_name(&mut self) -> R<NodeId> {
        if !self.at_ident_name() {
            return self.unexpected();
        }
        let t = self.bump()?;
        Ok(self.ast.push(t.span, Node::Identifier))
    }

    // Private names.

    fn declare_private(&mut self, span: Span, kind: Private, is_static: bool) -> R<()> {
        let name = self.name(Span::new(span.start + 1, span.end)).into_owned();
        if name == "constructor" {
            return self.err(
                "private-constructor",
                span,
                "a private name can't be #constructor",
            );
        }
        let Some(scope) = self.classes.last_mut() else {
            return self.err(
                "private-outside-class",
                span,
                "private names are only declared in classes",
            );
        };
        let first = match scope.declared.get_mut(&name) {
            None => {
                scope.declared.insert(name, (kind, is_static, span));
                return Ok(());
            }
            Some((had, was_static, first)) if *was_static == is_static => match (*had, kind) {
                (Private::Get, Private::Set) | (Private::Set, Private::Get) => {
                    *had = Private::GetSet;
                    return Ok(());
                }
                _ => *first,
            },
            Some((.., first)) => *first,
        };
        self.fail(
            Diagnostic::error(
                "duplicate-private-name",
                span,
                format!("#{name} is declared twice"),
            )
            .with_label(first, "declared here first"),
        )
    }

    fn use_private(&mut self, span: Span) -> R<()> {
        let name = self.name(Span::new(span.start + 1, span.end)).into_owned();
        match self.classes.last_mut() {
            Some(scope) => {
                scope.used.push((name, span));
                Ok(())
            }
            None => self.err(
                "undeclared-private-name",
                span,
                format!("#{name} isn't declared in a class around it"),
            ),
        }
    }

    /// Ends a class body: each private name it used is declared in it, or
    /// passed out to the class around it.
    fn end_class_scope(&mut self) -> R<()> {
        let scope = self.classes.pop().unwrap_or_default();
        for (name, span) in scope.used {
            if scope.declared.contains_key(&name) {
                continue;
            }
            match self.classes.last_mut() {
                Some(outer) => outer.used.push((name, span)),
                None => {
                    return self.err(
                        "undeclared-private-name",
                        span,
                        format!("#{name} isn't declared in a class around it"),
                    );
                }
            }
        }
        Ok(())
    }

    // Cover grammar.

    /// Fails on the first object literal since `mark` that has something
    /// only a pattern can have and didn't turn into a pattern.
    fn check_pending(&mut self, mark: usize) -> R<()> {
        if self.pending.len() <= mark {
            return Ok(());
        }
        let found = self.pending[mark..]
            .iter()
            .find(|(id, ..)| matches!(self.ast.node(*id), Node::Object { .. }))
            .copied();
        self.pending.truncate(mark);
        match found {
            Some((_, span, "shorthand-init")) => self.err(
                "shorthand-init",
                span,
                "`{a = 1}` is only allowed as a pattern, like `({a = 1} = b)`",
            ),
            Some((_, span, _)) => self.err(
                "duplicate-proto",
                span,
                "an object literal can set __proto__ only once",
            ),
            None => Ok(()),
        }
    }
}

/// Whether a token of this kind can start an expression, for `yield`,
/// whose operand is optional.
fn starts_expression(kind: Kind) -> bool {
    match kind {
        Kind::Eof => false,
        Kind::Keyword(Keyword::In | Keyword::Instanceof) => false,
        Kind::Punct(p) => matches!(
            p,
            Punct::LParen
                | Punct::LBracket
                | Punct::LBrace
                | Punct::Plus
                | Punct::Minus
                | Punct::Bang
                | Punct::Tilde
                | Punct::PlusPlus
                | Punct::MinusMinus
                | Punct::Slash
                | Punct::SlashEq
        ),
        _ => true,
    }
}