Skip to main content

parsec_js/parser/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 James Conway
3
4//! The parser: ECMA-262's syntactic grammar, clauses 13 to 16, with
5//! Annex B's additions for scripts, by recursive descent.
6//!
7//! The parser asks the lexer for one token at a time, always with
8//! [`Goal::Div`], and reads a `/` or `}` again with the goal it turns
9//! out to need: a regular expression where an expression starts, a
10//! template's next part after a substitution. Nothing else is ever read
11//! twice.
12//!
13//! The cover grammars are parsed once, as what they cover: `(a, b)` is
14//! parsed as an expression and turned into arrow parameters in place when
15//! `=>` follows, `[a, b]` into a pattern when `=` does. Errors that only
16//! the expression reading has, like `{a = 1}` outside a pattern, wait in
17//! [`Parser::pending`] until it's known which reading it is.
18//!
19//! The first error ends the parse, unless it's [`parse_recovering`]:
20//! then a statement that fails is skipped to where the next one starts,
21//! and the parse goes on to report more. Recursion is counted against a
22//! depth limit, and tokens against the step budget, so no input
23//! overflows the stack or runs past what it was allowed, recovering or
24//! not.
25
26mod expr;
27mod function;
28mod module;
29mod pattern;
30mod stmt;
31
32use std::borrow::Cow;
33use std::cell::Cell;
34use std::collections::HashMap;
35
36use parsec_base::{Budget, Diagnostic, Limits, Severity, Span};
37
38use crate::ast::{Ast, Comment, CommentKind, List, Node, NodeId};
39use crate::lexer::{Goal, Lexer, SourceType};
40use crate::text;
41use crate::token::{Flags, Keyword, Kind, Punct, Token};
42
43/// How deep the parser recurses when [`Limits::max_depth`] doesn't say.
44/// A level is a statement, a function or class, an operand of a prefix
45/// operator or `**`, or an expression or pattern nested in brackets.
46/// Real code stays far below it (typescript.js, 9 MB, needs 53), and at
47/// the limit the parser uses at most about 250 KB of stack in a release
48/// build and 700 KB in a debug one, so it fits a 1 MB thread. A higher
49/// limit needs a thread with more: about 1 KB a level in a release
50/// build, 3 KB in a debug one.
51pub const DEFAULT_MAX_DEPTH: u32 = 256;
52
53/// What to parse and how much it may cost.
54#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
55pub struct Options {
56    /// A module is strict, may `await` at the top, and has `import` and
57    /// `export` declarations there.
58    pub source_type: SourceType,
59    /// `max_depth` is how deep the tree may nest, [`DEFAULT_MAX_DEPTH`]
60    /// without one; `max_steps` bounds the tokens read; `max_input` the
61    /// bytes.
62    pub limits: Limits,
63}
64
65/// Parses `src` as a Script or a Module, as `options` says. The first
66/// syntax error is the `Err`.
67///
68/// ```
69/// use parsec_js::{Node, Options, parse};
70///
71/// let ast = parse("let x = a?.b ?? 1;", &Options::default()).unwrap();
72/// let Node::Program { body, .. } = *ast.node(ast.root()) else { unreachable!() };
73/// assert_eq!(ast.get(body).len(), 1);
74///
75/// let err = parse("let x = ;", &Options::default()).unwrap_err();
76/// assert_eq!((err.code, err.span.start), ("unexpected-token", 8));
77/// ```
78pub fn parse(src: &str, options: &Options) -> Result<Ast, Diagnostic> {
79    Parser::new(src, options).parse()
80}
81
82/// Parses `src` as a Script.
83pub fn parse_script(src: &str) -> Result<Ast, Diagnostic> {
84    parse(src, &Options::default())
85}
86
87/// Parses `src` as [`parse`] does, but goes on after a syntax error to
88/// find the rest: every error, in the order found, is the `Err`.
89///
90/// After an error the parser skips to where the next statement starts:
91/// past a `;`, to a `}` that closes the block it's in, or to a statement
92/// keyword at the start of a line. Errors after the first can follow
93/// from it, as with any compiler; the first is the one [`parse`] gives.
94/// A program with no errors parses to the same tree as with [`parse`].
95///
96/// ```
97/// use parsec_js::{Options, parse_recovering};
98///
99/// let src = "let a = ;\nlet b = 2;\nif (b { go() }\n";
100/// let errors = parse_recovering(src, &Options::default()).unwrap_err();
101/// let codes: Vec<_> = errors.iter().map(|d| (d.code, d.span.start)).collect();
102/// assert_eq!(codes, [("unexpected-token", 8), ("unexpected-token", 27)]);
103/// ```
104pub fn parse_recovering(src: &str, options: &Options) -> Result<Ast, Vec<Diagnostic>> {
105    let mut p = Parser::new(src, options);
106    p.recover = true;
107    p.parse_all()
108}
109
110/// Where [`parse_piece`] starts, and what the parser knew there when it
111/// parsed the whole source.
112pub(crate) struct Resume {
113    pub start: u32,
114    /// A function body from its `{`, or else a StatementListItem.
115    pub body: bool,
116    pub ctx: Ctx,
117    /// The labels around it in its function: name, where, on a loop.
118    pub labels: Vec<(String, Span, bool)>,
119    /// How many class bodies are around it.
120    pub classes: usize,
121    /// The depth to start at, and the most allowed.
122    pub depth: u32,
123    pub max_depth: u32,
124}
125
126/// What [`parse_piece`] parsed: its nodes, lists, comments and warnings,
127/// the root last; where it ends; and the private names it uses that a
128/// class around it has to declare.
129pub(crate) struct Piece {
130    pub ast: Ast,
131    pub end: u32,
132    pub private_names: Vec<String>,
133}
134
135/// Parses one function body or statement of `src` from `r.start`, as
136/// the whole parse would there, into a tree of its own: `None` if it
137/// fails. Its lists start at 1, so an empty one made there and one
138/// that's `List::default()` stay apart.
139pub(crate) fn parse_piece(src: &str, options: &Options, r: Resume) -> Option<Piece> {
140    let mut p = Parser::with_room(src, options, 64);
141    p.ast.lists.push(NodeId::new(1));
142    p.lexer = p.lexer.starting_at(r.start, false);
143    p.ctx = r.ctx;
144    p.labels = r
145        .labels
146        .into_iter()
147        .map(|(name, span, is_loop)| Label {
148            name,
149            span,
150            is_loop,
151        })
152        .collect();
153    p.classes = (0..r.classes).map(|_| ClassScope::default()).collect();
154    p.depth = r.depth;
155    p.max_depth = r.max_depth;
156    let root = p.piece(r.body).ok()?;
157    if root.index() + 1 != p.ast.nodes.len() {
158        return None;
159    }
160    let end = p.prev_end;
161    let mut private_names = Vec::new();
162    for scope in p.classes.drain(..) {
163        private_names.extend(scope.used.into_iter().map(|(name, _)| name));
164    }
165    let mut ast = p.ast;
166    // The token after the piece was read too, and its comments.
167    ast.comments.retain(|c| c.span.start < end);
168    ast.warnings = p
169        .lexer
170        .take_diagnostics()
171        .into_iter()
172        .filter(|d| d.severity == Severity::Warning && d.span.start < end)
173        .collect();
174    ast.root = Some(root);
175    Some(Piece {
176        ast,
177        end,
178        private_names,
179    })
180}
181
182/// The parse ended; the diagnostic is in [`Parser::error`].
183#[derive(Debug)]
184pub(crate) struct Stop;
185
186pub(crate) type R<T> = Result<T, Stop>;
187
188/// What the grammar's parameters and the enclosing function allow here.
189#[derive(Clone, Copy, Debug, Default)]
190pub(crate) struct Ctx {
191    pub strict: bool,
192    /// `[Yield]`: `yield` is an operator.
193    pub yield_: bool,
194    /// `[Await]`: `await` is an operator.
195    pub await_: bool,
196    /// `[Return]`.
197    pub ret: bool,
198    pub new_target: bool,
199    pub super_prop: bool,
200    pub super_call: bool,
201    /// In a class field's initializer or a static block, where
202    /// `arguments` is an error.
203    pub no_arguments: bool,
204    /// In a class static block, where `await` is reserved.
205    pub static_block: bool,
206    /// Enclosing loops, and loops and switches, in this function.
207    pub loops: u32,
208    pub breakable: u32,
209    /// Where this function's labels start in [`Parser::labels`].
210    pub labels: usize,
211}
212
213/// A label in scope, where it is, and whether it labels a loop.
214struct Label {
215    name: String,
216    span: Span,
217    is_loop: bool,
218}
219
220/// What kind of class element a private name names.
221#[derive(Clone, Copy, PartialEq, Eq)]
222enum Private {
223    Field,
224    Method,
225    Get,
226    Set,
227    GetSet,
228}
229
230/// A class body being parsed: its private names, and the ones used in
231/// it that might be declared later in it or in a class around it.
232#[derive(Default)]
233struct ClassScope {
234    declared: HashMap<String, (Private, bool, Span)>,
235    used: Vec<(String, Span)>,
236}
237
238thread_local! {
239    /// The last parse's list scratch, empty, for the next on this thread.
240    static SPARE_SCRATCH: Cell<Vec<NodeId>> = const { Cell::new(Vec::new()) };
241}
242
243/// The parser's list scratch, the items of every list still being
244/// parsed. It never leaves the parser, so each thread keeps one for its
245/// next parse: allocating and freeing it was a sixth of what a parse of
246/// a few bytes cost. One grown past 4,096 items isn't kept.
247struct Scratch(Vec<NodeId>);
248
249impl Scratch {
250    fn take() -> Scratch {
251        // `try_with`: a parse in a thread-local's destructor has no spare.
252        let mut v = SPARE_SCRATCH.try_with(Cell::take).unwrap_or_default();
253        if v.capacity() == 0 {
254            v.reserve(64);
255        }
256        Scratch(v)
257    }
258}
259
260impl Drop for Scratch {
261    fn drop(&mut self) {
262        let mut v = std::mem::take(&mut self.0);
263        if v.capacity() <= 4096 {
264            v.clear();
265            let _ = SPARE_SCRATCH.try_with(|spare| spare.set(v));
266        }
267    }
268}
269
270impl std::ops::Deref for Scratch {
271    type Target = Vec<NodeId>;
272
273    fn deref(&self) -> &Vec<NodeId> {
274        &self.0
275    }
276}
277
278impl std::ops::DerefMut for Scratch {
279    fn deref_mut(&mut self) -> &mut Vec<NodeId> {
280        &mut self.0
281    }
282}
283
284pub(crate) struct Parser<'a> {
285    src: &'a str,
286    lexer: Lexer<'a>,
287    /// The token being looked at.
288    tok: Token,
289    /// The end of the last token consumed.
290    prev_end: u32,
291    ast: Ast,
292    /// Children of lists being built, innermost at the end.
293    scratch: Scratch,
294    /// Buffers for the early errors on bound names, kept between uses so
295    /// checking a declaration allocates nothing.
296    names: Vec<Span>,
297    sorted_names: Vec<(Cow<'a, str>, Span)>,
298    /// The `if`s of `else if` chains being parsed, innermost at the end.
299    if_chain: Vec<(u32, NodeId, NodeId)>,
300    error: Option<Diagnostic>,
301    /// Going on after errors, for [`parse_recovering`], and the errors
302    /// found so far.
303    recover: bool,
304    errors: Vec<Diagnostic>,
305    /// How many of the lexer's diagnostics have been looked at.
306    seen: usize,
307    module: bool,
308    ctx: Ctx,
309    depth: u32,
310    max_depth: u32,
311    budget: Budget,
312    labels: Vec<Label>,
313    /// Where the labels directly on the statement about to be parsed
314    /// start, so a loop can mark them all as labelling a loop.
315    label_chain: Option<usize>,
316    /// Where the expression statement being parsed starts, whose first
317    /// identifier may be a label rather than a reference.
318    label_candidate: Option<u32>,
319    /// The statement about to be parsed is the body of an `if`, a loop
320    /// or a `with`, where a labelled function declaration is an error.
321    in_body: bool,
322    /// Object literals with something only a pattern may have (`{a = 1}`,
323    /// a second `__proto__`), and where. An entry stands until the object
324    /// turns into a pattern; one still an object when its expression ends
325    /// is an error.
326    pending: Vec<(NodeId, Span, &'static str)>,
327    classes: Vec<ClassScope>,
328    /// The names a module exports so far, and where.
329    exports: HashMap<String, Span>,
330    /// Where the last `yield` and `await` expressions, and the last
331    /// `await` read as an identifier, started, for the parameter lists
332    /// that may hold none of them.
333    last_yield: Option<u32>,
334    last_await: Option<u32>,
335    last_await_ident: Option<u32>,
336}
337
338impl<'a> Parser<'a> {
339    pub(crate) fn new(src: &'a str, options: &Options) -> Parser<'a> {
340        // About one node per eight bytes of a large bundle, but small
341        // scripts run denser, one per four or five, and growing the
342        // vectors costs a short parse more than the room does: the first
343        // 64 KB are sized at one per four, with 16 more for the tiniest.
344        let len = match options.limits.check_input(src.len()) {
345            Ok(()) => src.len(),
346            Err(_) => 0,
347        };
348        Parser::with_room(
349            src,
350            options,
351            16 + len.min(1 << 16) / 4 + len.saturating_sub(1 << 16) / 8,
352        )
353    }
354
355    /// A parser whose tree has room for `nodes` nodes to start with.
356    fn with_room(src: &'a str, options: &Options, nodes: usize) -> Parser<'a> {
357        let lexer = Lexer::with_limits(src, options.source_type, &options.limits);
358        let ast = Ast::new(nodes);
359        let module = options.source_type == SourceType::Module;
360        Parser {
361            src: lexer.source(),
362            lexer,
363            tok: Token {
364                kind: Kind::Eof,
365                flags: Flags::empty(),
366                span: Span::at(0),
367            },
368            prev_end: 0,
369            ast,
370            scratch: Scratch::take(),
371            names: Vec::new(),
372            sorted_names: Vec::new(),
373            if_chain: Vec::new(),
374            error: None,
375            recover: false,
376            errors: Vec::new(),
377            seen: 0,
378            module,
379            ctx: Ctx {
380                strict: module,
381                await_: module,
382                ..Ctx::default()
383            },
384            depth: 0,
385            max_depth: options.limits.max_depth.unwrap_or(DEFAULT_MAX_DEPTH),
386            budget: options.limits.budget(),
387            labels: Vec::new(),
388            label_chain: None,
389            label_candidate: None,
390            in_body: false,
391            pending: Vec::new(),
392            classes: Vec::new(),
393            exports: HashMap::new(),
394            last_yield: None,
395            last_await: None,
396            last_await_ident: None,
397        }
398    }
399
400    pub(crate) fn parse(mut self) -> Result<Ast, Diagnostic> {
401        let result = self.program();
402        if let Err(Stop) = result {
403            return Err(self.error.take().expect("a stop has a diagnostic"));
404        }
405        let mut ast = self.ast;
406        ast.warnings = self
407            .lexer
408            .take_diagnostics()
409            .into_iter()
410            .filter(|d| d.severity == Severity::Warning)
411            .collect();
412        Ok(ast)
413    }
414
415    /// The piece [`parse_piece`] parses.
416    fn piece(&mut self, body: bool) -> R<NodeId> {
417        if let Some(d) = self.lexer.diagnostics().first() {
418            return self.fail(d.clone());
419        }
420        self.advance()?;
421        if body {
422            self.function_body(List::default(), true, false, None)
423        } else {
424            self.statement_list_item()
425        }
426    }
427
428    /// The parse for [`parse_recovering`].
429    fn parse_all(mut self) -> Result<Ast, Vec<Diagnostic>> {
430        let result = self.program();
431        let mut errors = std::mem::take(&mut self.errors);
432        if let Err(Stop) = result {
433            errors.extend(self.error.take());
434        }
435        if !errors.is_empty() {
436            return Err(errors);
437        }
438        let mut ast = self.ast;
439        ast.warnings = self
440            .lexer
441            .take_diagnostics()
442            .into_iter()
443            .filter(|d| d.severity == Severity::Warning)
444            .collect();
445        Ok(ast)
446    }
447
448    fn program(&mut self) -> R<()> {
449        // A lexer that refused the input has said why.
450        if let Some(d) = self.lexer.diagnostics().first() {
451            return self.fail(d.clone());
452        }
453        self.advance()?;
454        let mark = self.scratch.len();
455        self.statement_list(true)?;
456        // Recovering, a `}` with nothing to close is one more error.
457        while self.recover && self.at(Punct::RBrace) {
458            let d = self.unexpected_diagnostic();
459            self.errors.push(d);
460            self.skip_token()?;
461            self.statement_list(false)?;
462        }
463        if self.tok.kind != Kind::Eof {
464            return self.unexpected();
465        }
466        let body = self.take_list(mark);
467        let source_type = if self.module {
468            SourceType::Module
469        } else {
470            SourceType::Script
471        };
472        let root = self.ast.push(
473            Span::new(0, self.src.len() as u32),
474            Node::Program { body, source_type },
475        );
476        self.ast.root = Some(root);
477        Ok(())
478    }
479
480    // Errors.
481
482    fn fail<T>(&mut self, d: Diagnostic) -> R<T> {
483        if self.error.is_none() {
484            self.error = Some(d);
485        }
486        Err(Stop)
487    }
488
489    fn err<T>(
490        &mut self,
491        code: &'static str,
492        span: Span,
493        message: impl Into<Cow<'static, str>>,
494    ) -> R<T> {
495        self.fail(Diagnostic::error(code, span, message))
496    }
497
498    /// An error at the token being looked at, which nothing here expects.
499    fn unexpected<T>(&mut self) -> R<T> {
500        let d = self.unexpected_diagnostic();
501        self.fail(d)
502    }
503
504    fn unexpected_diagnostic(&self) -> Diagnostic {
505        let t = self.tok;
506        if t.kind == Kind::Eof {
507            return Diagnostic::error(
508                "unexpected-end",
509                t.span,
510                "the input ends in the middle of something",
511            );
512        }
513        let text = t.text(self.src);
514        let shown: String = text.chars().take(40).collect();
515        Diagnostic::error(
516            "unexpected-token",
517            t.span,
518            format!("`{shown}` can't go here"),
519        )
520    }
521
522    /// `p`, inside the bracket `open` opened: an error here points back
523    /// at it.
524    fn expect_in(&mut self, p: Punct, open: Token) -> R<Token> {
525        if self.at(p) {
526            return self.bump();
527        }
528        self.unclosed(open)
529    }
530
531    #[cold]
532    #[inline(never)]
533    fn unclosed<T>(&mut self, open: Token) -> R<T> {
534        let what = match open.kind {
535            Kind::Punct(Punct::LParen) => "this `(` is still open",
536            Kind::Punct(Punct::LBracket) => "this `[` is still open",
537            _ => "this `{` is still open",
538        };
539        let d = self.unexpected_diagnostic().with_label(open.span, what);
540        self.fail(d)
541    }
542
543    // Tokens.
544
545    /// Reads the next token that isn't a comment, with [`Goal::Div`],
546    /// into `tok`: straight there, and not through a `Result` and a
547    /// copy or two on the stack.
548    fn advance(&mut self) -> R<()> {
549        self.tok = self.lexer.next_token(Goal::Div);
550        self.check_lexer()?;
551        if self.tok.is_trivia() {
552            return self.after_comments();
553        }
554        Ok(())
555    }
556
557    /// Keeps `tok`, a comment, and any more after it, and reads the token
558    /// that follows them into `tok`. Out of line, so the path for a token
559    /// with no comment before it stays short.
560    #[inline(never)]
561    fn after_comments(&mut self) -> R<()> {
562        loop {
563            let t = self.tok;
564            let kind = match t.kind {
565                Kind::LineComment => CommentKind::Line,
566                Kind::BlockComment => CommentKind::Block,
567                Kind::Hashbang => CommentKind::Hashbang,
568                Kind::HtmlOpenComment => CommentKind::HtmlOpen,
569                Kind::HtmlCloseComment => CommentKind::HtmlClose,
570                _ => return Ok(()),
571            };
572            self.ast.comments.push(Comment { kind, span: t.span });
573            self.tok = self.lexer.next_token(Goal::Div);
574            self.check_lexer()?;
575        }
576    }
577
578    /// Stops at the first error the lexer has reported since last asked.
579    /// It runs once a token, so the check is inlined and the rest isn't.
580    #[inline(always)]
581    fn check_lexer(&mut self) -> R<()> {
582        if self.lexer.diagnostics().len() > self.seen {
583            return self.lexer_reported();
584        }
585        Ok(())
586    }
587
588    #[cold]
589    #[inline(never)]
590    fn lexer_reported(&mut self) -> R<()> {
591        let diagnostics = self.lexer.diagnostics();
592        if diagnostics.len() > self.seen {
593            let new = &diagnostics[self.seen..];
594            self.seen = diagnostics.len();
595            if let Some(d) = new.iter().find(|d| d.is_error()) {
596                let d = d.clone();
597                return self.fail(d);
598            }
599        }
600        Ok(())
601    }
602
603    /// Consumes the token being looked at and returns it. Inlined, so a
604    /// caller that wants the token keeps it, and `skip` keeps nothing
605    /// across the call into the lexer.
606    #[inline(always)]
607    fn bump(&mut self) -> R<Token> {
608        let t = self.tok;
609        self.skip()?;
610        Ok(t)
611    }
612
613    /// Consumes the token being looked at.
614    #[inline(never)]
615    fn skip(&mut self) -> R<()> {
616        let spent = self.budget.spend(1).is_ok();
617        if !spent || (self.tok.flags.contains(Flags::LEGACY_OCTAL) && self.ctx.strict) {
618            return self.refuse_token(spent);
619        }
620        self.prev_end = self.tok.span.end;
621        self.advance()
622    }
623
624    /// Why the token being looked at can't be consumed: the step budget
625    /// ran out before it, or it's a legacy octal in strict code.
626    #[cold]
627    #[inline(never)]
628    fn refuse_token(&mut self, spent: bool) -> R<()> {
629        let span = self.tok.span;
630        if !spent {
631            return self.err(
632                "step-budget",
633                span,
634                "the parse used up its step budget here",
635            );
636        }
637        self.err(
638            "legacy-octal-in-strict",
639            span,
640            "legacy octal literals and escapes aren't allowed in strict code",
641        )
642    }
643
644    /// Reads the token being looked at, a `/` or `}`, again with `goal`.
645    fn rescan(&mut self, goal: Goal) -> R<()> {
646        self.tok = self.lexer.rescan(self.tok, goal);
647        self.check_lexer()
648    }
649
650    /// The token after the one being looked at.
651    fn peek(&self) -> Token {
652        let mut lexer = self.lexer.fork();
653        loop {
654            let t = lexer.next_token(Goal::Div);
655            if !t.is_trivia() {
656                return t;
657            }
658        }
659    }
660
661    fn at(&self, p: Punct) -> bool {
662        self.tok.kind == Kind::Punct(p)
663    }
664
665    /// The token is the keyword `k`, spelled without escapes.
666    fn at_kw(&self, k: Keyword) -> bool {
667        self.tok.kind == Kind::Keyword(k)
668    }
669
670    fn eat(&mut self, p: Punct) -> R<bool> {
671        if self.at(p) {
672            self.bump()?;
673            return Ok(true);
674        }
675        Ok(false)
676    }
677
678    fn expect(&mut self, p: Punct) -> R<Token> {
679        if self.at(p) {
680            return self.bump();
681        }
682        self.unexpected()
683    }
684
685    fn expect_kw(&mut self, k: Keyword) -> R<Token> {
686        if self.at_kw(k) {
687            return self.bump();
688        }
689        self.unexpected()
690    }
691
692    /// A `;`, or where automatic semicolon insertion puts one: before a
693    /// line break, a `}` or the end.
694    fn semicolon(&mut self) -> R<()> {
695        if self.eat(Punct::Semicolon)? {
696            return Ok(());
697        }
698        if self.can_insert_semicolon() {
699            return Ok(());
700        }
701        self.unexpected()
702    }
703
704    fn can_insert_semicolon(&self) -> bool {
705        self.tok.newline_before() || self.at(Punct::RBrace) || self.tok.kind == Kind::Eof
706    }
707
708    // Nodes and lists.
709
710    fn finish(&mut self, start: u32, node: Node) -> NodeId {
711        self.ast
712            .push(Span::new(start, self.prev_end.max(start)), node)
713    }
714
715    fn take_list(&mut self, mark: usize) -> List {
716        self.ast.list(self.scratch.drain(mark..))
717    }
718
719    fn node(&self, id: NodeId) -> Node {
720        *self.ast.node(id)
721    }
722
723    fn span(&self, id: NodeId) -> Span {
724        self.ast.span(id)
725    }
726
727    // Limits.
728
729    /// One level deeper, or an error past the limit.
730    fn enter(&mut self) -> R<()> {
731        self.depth += 1;
732        if self.depth > self.max_depth {
733            let span = self.tok.span;
734            return self.err(
735                "too-deep",
736                span,
737                format!("this nests deeper than the limit of {}", self.max_depth),
738            );
739        }
740        Ok(())
741    }
742
743    fn leave(&mut self) {
744        self.depth -= 1;
745    }
746
747    // Identifiers.
748
749    /// An identifier's name, escapes decoded. Until the lexer has read
750    /// an identifier with an escape, none has one to look for.
751    fn name(&self, span: Span) -> Cow<'a, str> {
752        let raw = span.text(self.src);
753        if !self.lexer.escaped_ident() {
754            return Cow::Borrowed(raw);
755        }
756        text::ident_name(raw)
757    }
758
759    /// Whether the identifier at `span` is `name`, escapes decoded. Only a
760    /// longer spelling can hold an escape that decodes to `name`, and only
761    /// once the lexer has read one, so most answers come from the lengths
762    /// without decoding.
763    fn name_is(&self, span: Span, name: &str) -> bool {
764        let raw = span.text(self.src);
765        match raw.len().cmp(&name.len()) {
766            std::cmp::Ordering::Less => false,
767            std::cmp::Ordering::Equal => raw == name,
768            std::cmp::Ordering::Greater => {
769                self.lexer.escaped_ident() && raw.contains('\\') && text::ident_name(raw) == name
770            }
771        }
772    }
773
774    /// The token is an IdentifierName: an identifier or any keyword.
775    fn at_ident_name(&self) -> bool {
776        matches!(self.tok.kind, Kind::Ident | Kind::Keyword(_))
777    }
778
779    /// The token could be an identifier reference here, though it may
780    /// still be an error as one (a reserved word escaped, `yield` in
781    /// strict code).
782    fn at_identifier(&self) -> bool {
783        match self.tok.kind {
784            Kind::Ident => true,
785            Kind::Keyword(k) => !k.is_reserved() || matches!(k, Keyword::Yield | Keyword::Await),
786            _ => false,
787        }
788    }
789
790    /// The word an identifier token spells, if it's one of [`Keyword`]'s,
791    /// escapes decoded.
792    fn word(&self, t: Token) -> Option<Keyword> {
793        match t.kind {
794            Kind::Keyword(k) => Some(k),
795            Kind::Ident if t.flags.contains(Flags::ESCAPED) => {
796                Keyword::from_str(&self.name(t.span))
797            }
798            _ => None,
799        }
800    }
801
802    /// Checks `t` as an IdentifierReference, a BindingIdentifier when
803    /// `binding`, or a LabelIdentifier, in this context. Most are a plain
804    /// name with nothing to check, and that answer comes first, inline.
805    #[inline(always)]
806    fn check_identifier(&mut self, t: Token, binding: bool) -> R<()> {
807        if t.kind == Kind::Ident
808            && !t.flags.contains(Flags::ESCAPED)
809            && !(binding && self.ctx.strict)
810        {
811            return Ok(());
812        }
813        self.check_word(t, binding)
814    }
815
816    /// [`Parser::check_identifier`] for a word, an escape, or a binding in
817    /// strict code.
818    #[inline(never)]
819    fn check_word(&mut self, t: Token, binding: bool) -> R<()> {
820        let word = self.word(t);
821        let reserved = match word {
822            None => false,
823            Some(Keyword::Await) => {
824                self.last_await_ident = Some(t.span.start);
825                self.ctx.await_ || self.module || self.ctx.static_block
826            }
827            Some(Keyword::Yield) => self.ctx.yield_ || self.ctx.strict,
828            Some(k) if k.is_strict_reserved() => self.ctx.strict,
829            Some(k) => k.is_reserved(),
830        };
831        if reserved {
832            let name = self.name(t.span).into_owned();
833            return self.err(
834                "reserved-word",
835                t.span,
836                format!("`{name}` is reserved here, so it can't be an identifier"),
837            );
838        }
839        if word.is_none() && binding && self.ctx.strict {
840            let name = self.name(t.span);
841            if name == "eval" || name == "arguments" {
842                return self.err(
843                    "strict-binding",
844                    t.span,
845                    format!("strict code can't bind or assign `{name}`"),
846                );
847            }
848        }
849        Ok(())
850    }
851
852    /// `arguments` can't be referred to in a class field's initializer or
853    /// a static block.
854    fn check_arguments(&mut self, span: Span) -> R<()> {
855        if self.ctx.no_arguments && self.name_is(span, "arguments") {
856            return self.err(
857                "arguments-in-class-init",
858                span,
859                "`arguments` isn't allowed in a class field or static block",
860            );
861        }
862        Ok(())
863    }
864
865    /// The token as an identifier reference or binding, checked, as a node.
866    fn identifier(&mut self, binding: bool) -> R<NodeId> {
867        // A reserved word spelled plainly is no identifier, and saying
868        // it's reserved would only confuse `if (a) else`.
869        if !self.at_identifier() {
870            return self.unexpected();
871        }
872        let t = self.tok;
873        self.check_identifier(t, binding)?;
874        self.bump()?;
875        Ok(self.ast.push(t.span, Node::Identifier))
876    }
877
878    /// The token as an IdentifierName, any word at all, as a node.
879    fn identifier_name(&mut self) -> R<NodeId> {
880        if !self.at_ident_name() {
881            return self.unexpected();
882        }
883        let t = self.bump()?;
884        Ok(self.ast.push(t.span, Node::Identifier))
885    }
886
887    // Private names.
888
889    fn declare_private(&mut self, span: Span, kind: Private, is_static: bool) -> R<()> {
890        let name = self.name(Span::new(span.start + 1, span.end)).into_owned();
891        if name == "constructor" {
892            return self.err(
893                "private-constructor",
894                span,
895                "a private name can't be #constructor",
896            );
897        }
898        let Some(scope) = self.classes.last_mut() else {
899            return self.err(
900                "private-outside-class",
901                span,
902                "private names are only declared in classes",
903            );
904        };
905        let first = match scope.declared.get_mut(&name) {
906            None => {
907                scope.declared.insert(name, (kind, is_static, span));
908                return Ok(());
909            }
910            Some((had, was_static, first)) if *was_static == is_static => match (*had, kind) {
911                (Private::Get, Private::Set) | (Private::Set, Private::Get) => {
912                    *had = Private::GetSet;
913                    return Ok(());
914                }
915                _ => *first,
916            },
917            Some((.., first)) => *first,
918        };
919        self.fail(
920            Diagnostic::error(
921                "duplicate-private-name",
922                span,
923                format!("#{name} is declared twice"),
924            )
925            .with_label(first, "declared here first"),
926        )
927    }
928
929    fn use_private(&mut self, span: Span) -> R<()> {
930        let name = self.name(Span::new(span.start + 1, span.end)).into_owned();
931        match self.classes.last_mut() {
932            Some(scope) => {
933                scope.used.push((name, span));
934                Ok(())
935            }
936            None => self.err(
937                "undeclared-private-name",
938                span,
939                format!("#{name} isn't declared in a class around it"),
940            ),
941        }
942    }
943
944    /// Ends a class body: each private name it used is declared in it, or
945    /// passed out to the class around it.
946    fn end_class_scope(&mut self) -> R<()> {
947        let scope = self.classes.pop().unwrap_or_default();
948        for (name, span) in scope.used {
949            if scope.declared.contains_key(&name) {
950                continue;
951            }
952            match self.classes.last_mut() {
953                Some(outer) => outer.used.push((name, span)),
954                None => {
955                    return self.err(
956                        "undeclared-private-name",
957                        span,
958                        format!("#{name} isn't declared in a class around it"),
959                    );
960                }
961            }
962        }
963        Ok(())
964    }
965
966    // Cover grammar.
967
968    /// Fails on the first object literal since `mark` that has something
969    /// only a pattern can have and didn't turn into a pattern.
970    fn check_pending(&mut self, mark: usize) -> R<()> {
971        if self.pending.len() <= mark {
972            return Ok(());
973        }
974        let found = self.pending[mark..]
975            .iter()
976            .find(|(id, ..)| matches!(self.ast.node(*id), Node::Object { .. }))
977            .copied();
978        self.pending.truncate(mark);
979        match found {
980            Some((_, span, "shorthand-init")) => self.err(
981                "shorthand-init",
982                span,
983                "`{a = 1}` is only allowed as a pattern, like `({a = 1} = b)`",
984            ),
985            Some((_, span, _)) => self.err(
986                "duplicate-proto",
987                span,
988                "an object literal can set __proto__ only once",
989            ),
990            None => Ok(()),
991        }
992    }
993}
994
995/// Whether a token of this kind can start an expression, for `yield`,
996/// whose operand is optional.
997fn starts_expression(kind: Kind) -> bool {
998    match kind {
999        Kind::Eof => false,
1000        Kind::Keyword(Keyword::In | Keyword::Instanceof) => false,
1001        Kind::Punct(p) => matches!(
1002            p,
1003            Punct::LParen
1004                | Punct::LBracket
1005                | Punct::LBrace
1006                | Punct::Plus
1007                | Punct::Minus
1008                | Punct::Bang
1009                | Punct::Tilde
1010                | Punct::PlusPlus
1011                | Punct::MinusMinus
1012                | Punct::Slash
1013                | Punct::SlashEq
1014        ),
1015        _ => true,
1016    }
1017}