Skip to main content

js_parse/
ast.rs

1//! The ECMAScript 2025 abstract syntax tree.
2//!
3//! The tree is a straightforward Box/Vec tree: the compiler (M2) walks it once
4//! per function body and immediately lowers it to bytecode, so an arena or
5//! visitor infrastructure would not pay for itself yet.
6//!
7//! Naming follows the specification: `Script`/`Module` bodies, `StatementListItem`
8//! (a statement or a declaration), `BindingIdentifier`, `AssignmentTarget`,
9//! `PropertyDefinition`, `ClassStaticBlock`, … Where the spec covers two
10//! productions with one node (a function declaration and a function expression,
11//! a script and a module), the node carries a discriminant instead of being
12//! duplicated.
13
14use crate::token::{Position, Punct, Span};
15use crate::wtf8::Wtf8;
16use std::fmt;
17
18/// A whole program: a script or a module.
19#[derive(Debug, Clone, PartialEq)]
20pub struct Program {
21    /// Script or module.
22    pub kind: ProgramKind,
23    /// Top-level statements (`ScriptBody` / `ModuleItemList`).
24    pub body: Vec<Stmt>,
25    /// Whole-source range.
26    pub span: Span,
27    /// Whether the program is strict (modules always are).
28    pub strict: bool,
29}
30
31/// Which grammar production a [`Program`] is.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum ProgramKind {
34    /// `Script`
35    Script,
36    /// `Module`
37    Module,
38}
39
40/// An identifier (binding, reference, label or private name).
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Ident {
43    /// Name as written, escapes already decoded.
44    pub name: String,
45    /// Source range.
46    pub span: Span,
47}
48
49impl Ident {
50    /// Shorthand for tests.
51    pub fn new(name: impl Into<String>) -> Ident {
52        Ident {
53            name: name.into(),
54            span: Span::default(),
55        }
56    }
57}
58
59impl fmt::Display for Ident {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        f.write_str(&self.name)
62    }
63}
64
65// ---------------------------------------------------------------------------
66// Statements
67// ---------------------------------------------------------------------------
68
69/// A statement or declaration.
70#[derive(Debug, Clone, PartialEq)]
71pub struct Stmt {
72    /// Statement payload.
73    pub kind: StmtKind,
74    /// Source range.
75    pub span: Span,
76}
77
78impl Stmt {
79    /// Build a statement node.
80    pub fn new(kind: StmtKind, span: Span) -> Stmt {
81        Stmt { kind, span }
82    }
83
84    /// Whether this is an empty statement (`;`) or a block containing only
85    /// empty declarations, which ASI treats specially.
86    pub fn is_empty(&self) -> bool {
87        matches!(self.kind, StmtKind::Empty)
88    }
89}
90
91/// Statement and declaration nodes (`StatementListItem`).
92#[derive(Debug, Clone, PartialEq)]
93pub enum StmtKind {
94    /// `;`
95    Empty,
96    /// `{ ... }`
97    Block(Vec<Stmt>),
98    /// `expr;`
99    Expr(Box<Expr>),
100    /// `if (test) cons else alt`
101    If {
102        /// Condition.
103        test: Box<Expr>,
104        /// Then branch.
105        cons: Box<Stmt>,
106        /// Else branch.
107        alt: Option<Box<Stmt>>,
108    },
109    /// `do body while (test);`
110    DoWhile {
111        /// Loop body.
112        body: Box<Stmt>,
113        /// Loop condition.
114        test: Box<Expr>,
115    },
116    /// `while (test) body`
117    While {
118        /// Loop condition.
119        test: Box<Expr>,
120        /// Loop body.
121        body: Box<Stmt>,
122    },
123    /// `for (init; test; update) body`
124    For {
125        /// `null` for `for (;;)`, otherwise a var/let/const declaration or an
126        /// expression.
127        init: Option<ForInit>,
128        /// Loop condition.
129        test: Option<Box<Expr>>,
130        /// Per-iteration update expression.
131        update: Option<Box<Expr>>,
132        /// Loop body.
133        body: Box<Stmt>,
134    },
135    /// `for (decl|lhs in expr) body`
136    ForIn {
137        /// Left-hand side.
138        left: ForHead,
139        /// Enumerated object.
140        right: Box<Expr>,
141        /// Loop body.
142        body: Box<Stmt>,
143    },
144    /// `for (decl|lhs of expr) body`, plus `for await (…)`
145    ForOf {
146        /// Whether `await` was present.
147        is_await: bool,
148        /// Left-hand side.
149        left: ForHead,
150        /// Iterated value.
151        right: Box<Expr>,
152        /// Loop body.
153        body: Box<Stmt>,
154    },
155    /// `continue;` / `continue label;`
156    Continue(Option<Ident>),
157    /// `break;` / `break label;`
158    Break(Option<Ident>),
159    /// `return;` / `return expr;`
160    Return(Option<Box<Expr>>),
161    /// `with (obj) body`
162    With {
163        /// Object to put on the scope chain.
164        object: Box<Expr>,
165        /// Statement executed inside the `with`.
166        body: Box<Stmt>,
167    },
168    /// `label: stmt`
169    Labeled {
170        /// Label name.
171        label: Ident,
172        /// Labelled statement.
173        body: Box<Stmt>,
174    },
175    /// `switch (disc) { cases }`
176    Switch {
177        /// Discriminant.
178        discriminant: Box<Expr>,
179        /// Cases in source order.
180        cases: Vec<SwitchCase>,
181    },
182    /// `throw expr;`
183    Throw(Box<Expr>),
184    /// `try { } catch (e) { } finally { }`
185    Try {
186        /// Guarded block.
187        block: Vec<Stmt>,
188        /// Catch clause, if present.
189        handler: Option<CatchClause>,
190        /// Finalizer block, if present.
191        finalizer: Option<Vec<Stmt>>,
192    },
193    /// `debugger;`
194    Debugger,
195    /// `var`/`let`/`const` declaration.
196    VarDecl(VarDecl),
197    /// `function` declaration.
198    FuncDecl(Box<Function>),
199    /// `class` declaration.
200    ClassDecl(Box<Class>),
201    /// `import` declaration (modules only).
202    Import(Box<ImportDecl>),
203    /// `export` declaration (modules only).
204    Export(Box<ExportDecl>),
205}
206
207/// One `case`/`default` clause.
208#[derive(Debug, Clone, PartialEq)]
209pub struct SwitchCase {
210    /// Case selector; `None` for `default`.
211    pub test: Option<Box<Expr>>,
212    /// Statements of the clause.
213    pub body: Vec<Stmt>,
214    /// Source range of the whole clause.
215    pub span: Span,
216}
217
218/// The `catch` half of a `try` statement.
219#[derive(Debug, Clone, PartialEq)]
220pub struct CatchClause {
221    /// Bound error, if any (`catch { }` has none).
222    pub param: Option<Pattern>,
223    /// Handler body.
224    pub body: Vec<Stmt>,
225    /// Source range.
226    pub span: Span,
227}
228
229/// The `init` slot of a classic `for` statement.
230#[derive(Debug, Clone, PartialEq)]
231pub enum ForInit {
232    /// `for (var i = 0; …)`
233    VarDecl(VarDecl),
234    /// `for (i = 0; …)`
235    Expr(Box<Expr>),
236}
237
238/// The left-hand side of a `for-in`/`for-of` head.
239#[derive(Debug, Clone, PartialEq)]
240pub enum ForHead {
241    /// `for (let x of …)`, including single-declarator declarations.
242    VarDecl(VarDecl),
243    /// `for (x of …)`, `for ([a, b] of …)`, `for (obj.x of …)`.
244    Assign(Box<Pattern>),
245}
246
247/// `var`/`let`/`const`.
248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249pub enum VarDeclKind {
250    /// `var`
251    Var,
252    /// `let`
253    Let,
254    /// `const`
255    Const,
256    /// `using`
257    ///
258    /// A lexical binding whose value is disposed at the end of the enclosing block. The
259    /// await form is a separate variant so that the await-ness travels with the
260    /// declaration the way the other keywords do.
261    Using,
262    /// `await using`
263    AwaitUsing,
264}
265
266impl VarDeclKind {
267    /// The keyword.
268    pub fn as_str(self) -> &'static str {
269        match self {
270            VarDeclKind::Var => "var",
271            VarDeclKind::Let => "let",
272            VarDeclKind::Const => "const",
273            // A message that uses this only names the binding kind, and `await using` is
274            // still a `using`.
275            VarDeclKind::Using | VarDeclKind::AwaitUsing => "using",
276        }
277    }
278
279    /// Whether the declaration is block-scoped.
280    pub fn is_lexical(self) -> bool {
281        !matches!(self, VarDeclKind::Var)
282    }
283
284    /// Whether this declaration disposes its binding at the end of the block.
285    pub fn is_using(self) -> bool {
286        matches!(self, VarDeclKind::Using | VarDeclKind::AwaitUsing)
287    }
288
289    /// Whether the disposal is awaited.
290    pub fn is_await_using(self) -> bool {
291        matches!(self, VarDeclKind::AwaitUsing)
292    }
293}
294
295/// A declaration statement, with all of its declarators.
296#[derive(Debug, Clone, PartialEq)]
297pub struct VarDecl {
298    /// `var`, `let` or `const`.
299    pub kind: VarDeclKind,
300    /// Declarators in source order.
301    pub declarators: Vec<Declarator>,
302    /// Source range.
303    pub span: Span,
304}
305
306/// One `pattern = init` declarator.
307#[derive(Debug, Clone, PartialEq)]
308pub struct Declarator {
309    /// Bound names.
310    pub target: Pattern,
311    /// Initialiser.
312    pub init: Option<Box<Expr>>,
313    /// Source range.
314    pub span: Span,
315}
316
317// ---------------------------------------------------------------------------
318// Functions and classes
319// ---------------------------------------------------------------------------
320
321/// A function in any of its forms (declaration, expression, arrow, method).
322#[derive(Debug, Clone, PartialEq)]
323pub struct Function {
324    /// Name: required for declarations, optional for expressions and arrows.
325    pub name: Option<Ident>,
326    /// Parameters, in source order; a rest parameter is [`Pattern::Rest`].
327    pub params: Vec<Pattern>,
328    /// Body.
329    pub body: FunctionBody,
330    /// `async`
331    pub is_async: bool,
332    /// `function*` / `*method` / `async function*`
333    pub is_generator: bool,
334    /// Whether the body is strict: either an enclosing strict context or the
335    /// function's own `"use strict"` directive.
336    ///
337    /// Recorded per function because strictness is not a property of the source but of
338    /// the enclosing context: a `"use strict"` inside one function body leaves the code
339    /// after it sloppy, so the compiler cannot infer a body's mode from the program's.
340    pub strict: bool,
341    /// `=>`
342    pub is_arrow: bool,
343    /// Whether the body contains a call whose callee is the identifier `eval`.
344    ///
345    /// A *direct* `eval` can declare `var`s in this function's variable environment, so a
346    /// name that resolves into an enclosing one today may resolve to a fresh binding after
347    /// the eval runs. Anything that resolves a binding once and uses it twice — a compound
348    /// assignment, `x = (eval("var x"), 1)` — needs to know that *before* it emits the first
349    /// half, which is why the parser records it rather than the compiler discovering it
350    /// part-way through the right-hand side.
351    ///
352    /// Deliberately over-approximate: `eval?.()`, `(0, eval)()` and an `eval` inside a
353    /// nested function all set it, and none of them can actually declare anything here.
354    /// The cost is a reference object in a function that already contains one.
355    pub has_direct_eval: bool,
356    /// Source range.
357    pub span: Span,
358    /// Range of the parameter list, for error messages and `length`.
359    pub params_span: Span,
360    /// The range `Function.prototype.toString` reports, when it is **not** `span`.
361    ///
362    /// A class is the constructor function object, so `A.toString()` reports the whole
363    /// class definition while the constructor's own `span` — which the line table and
364    /// `params_span` are built from — stays on the `constructor(){}` member
365    /// (`class-declaration-explicit-ctor`).
366    pub source_span: Option<Span>,
367}
368
369/// The body of a [`Function`].
370#[derive(Debug, Clone, PartialEq)]
371pub enum FunctionBody {
372    /// `{ … }`
373    Block(Vec<Stmt>),
374    /// An arrow's expression body (no braces).
375    Expr(Box<Expr>),
376}
377
378impl FunctionBody {
379    /// Statements of a block body, if this is one.
380    pub fn statements(&self) -> Option<&[Stmt]> {
381        match self {
382            FunctionBody::Block(body) => Some(body),
383            FunctionBody::Expr(_) => None,
384        }
385    }
386}
387
388/// A class body.
389#[derive(Debug, Clone, PartialEq)]
390pub struct Class {
391    /// Class name: required for declarations, optional for expressions.
392    pub name: Option<Ident>,
393    /// `extends` clause.
394    pub super_class: Option<Box<Expr>>,
395    /// Members, in source order.
396    pub elements: Vec<ClassElement>,
397    /// Source range.
398    pub span: Span,
399    /// The closing `}` of the body.
400    ///
401    /// A class that writes no constructor still gets one, and the reference creates that
402    /// synthetic function *at* the closing brace: `js_parse_class_default_ctor` runs with
403    /// the `}` as its current token and hands `s->token.ptr` to `js_new_function_def`. The
404    /// position is the function's own `source_pos`, which is the first entry of its
405    /// line table — so `class B extends BigInt {}` constructed as `new B(1)` reports its
406    /// frame at the `}`, not at `class`. `span.end` cannot stand in: it is one *past* the
407    /// brace, and the brace may be the last character of a line.
408    pub body_end: Position,
409}
410
411impl Class {
412    /// Whether the class body itself defines `name`, which an anonymous class then keeps.
413    ///
414    /// `class { static name(){} }` has an own `name` property, so assigning one from the
415    /// binding would either fail or be shadowed — `NamedEvaluation` checks for it and
416    /// leaves the class alone.
417    pub fn has_own_name(&self) -> bool {
418        self.elements.iter().any(|element| match element {
419            ClassElement::Method { key, is_static, .. }
420            | ClassElement::Field { key, is_static, .. } => {
421                *is_static
422                    && matches!(key.static_name(), Some(PropKeyRef::Str(name)) if name.as_str() == Some("name"))
423            }
424            ClassElement::StaticBlock { .. } => false,
425        })
426    }
427}
428
429/// The binding a computed field key is stored in.
430///
431/// `js_atom_concat_num(ctx, JS_ATOM_computed_field + is_static, n)` produces
432/// `computed_field0`/`computed_field_static0`; the dump prints them as `<computed_field>0` and
433/// `<computed_field_static>0`, which is the reference's own bracket convention for a hidden
434/// name.
435pub fn computed_field_binding(index: usize, is_static: bool) -> String {
436    if is_static {
437        format!("<computed_field_static>{index}")
438    } else {
439        format!("<computed_field>{index}")
440    }
441}
442
443/// One member of a class body.
444#[derive(Debug, Clone, PartialEq)]
445pub enum ClassElement {
446    /// A method (`constructor`, ordinary, `get`, `set`, generator or async).
447    Method {
448        /// Property key.
449        key: PropName,
450        /// `static`
451        is_static: bool,
452        /// Which kind of method this is.
453        kind: MethodKind,
454        /// The method itself.
455        func: Box<Function>,
456        /// Source range.
457        span: Span,
458    },
459    /// A field (`x = 1`, `#x`, `static x`).
460    Field {
461        /// Property key.
462        key: PropName,
463        /// `static`
464        is_static: bool,
465        /// Initialiser expression.
466        value: Option<Box<Expr>>,
467        /// Source range.
468        span: Span,
469    },
470    /// `static { … }`
471    StaticBlock {
472        /// Block body.
473        body: Vec<Stmt>,
474        /// Position of the opening `{`, which is where the reference puts the function it
475        /// compiles the body into — the seed for the block's line table.
476        body_start: Position,
477        /// Source range.
478        span: Span,
479    },
480}
481
482/// Which kind of method a class member or object literal property defines.
483#[derive(Debug, Clone, Copy, PartialEq, Eq)]
484pub enum MethodKind {
485    /// `constructor`
486    Constructor,
487    /// An ordinary method.
488    Method,
489    /// `get name()`
490    Get,
491    /// `set name(v)`
492    Set,
493}
494
495/// A property key.
496#[derive(Debug, Clone, PartialEq)]
497pub enum PropName {
498    /// A bare identifier, string or numeric key. The variant records which
499    /// spelling was used, because `{ 1e2: x }` needs the numeric value while
500    /// `{ "1e2": x }` needs the string.
501    Literal(PropKey),
502    /// `[expr]`
503    Computed(Box<Expr>),
504    /// `#name` (classes only).
505    Private(Ident),
506}
507
508impl PropName {
509    /// Static name of the key, when it is not computed.
510    pub fn static_name(&self) -> Option<PropKeyRef<'_>> {
511        match self {
512            PropName::Literal(k) => Some(k.as_ref()),
513            PropName::Private(id) => Some(PropKeyRef::Private(&id.name)),
514            PropName::Computed(_) => None,
515        }
516    }
517}
518
519/// A literal property key.
520#[derive(Debug, Clone, PartialEq)]
521pub enum PropKey {
522    /// `foo` or `"foo"` — identical once the value is interned.
523    ///
524    /// A [`Wtf8`]: the quoted form can hold a surrogate the identifier form cannot, so
525    /// the wider type is the one that has to hold both.
526    Str(Wtf8),
527    /// `1`, `1.5`, `0x10` — the numeric value matters for array indexing.
528    Num(f64),
529}
530
531impl PropKey {
532    /// Borrow as [`PropKeyRef`].
533    pub fn as_ref(&self) -> PropKeyRef<'_> {
534        match self {
535            PropKey::Str(s) => PropKeyRef::Str(s),
536            PropKey::Num(n) => PropKeyRef::Num(*n),
537        }
538    }
539}
540
541/// Borrowed view of a [`PropKey`], used by the compiler.
542#[derive(Debug, Clone, Copy, PartialEq)]
543pub enum PropKeyRef<'a> {
544    /// A string key.
545    Str(&'a Wtf8),
546    /// A numeric key.
547    Num(f64),
548    /// A private name.
549    Private(&'a str),
550}
551
552// ---------------------------------------------------------------------------
553// Patterns
554// ---------------------------------------------------------------------------
555
556/// A binding pattern or assignment target.
557#[derive(Debug, Clone, PartialEq)]
558pub struct Pattern {
559    /// Pattern payload.
560    pub kind: PatternKind,
561    /// Source range.
562    pub span: Span,
563}
564
565impl Pattern {
566    /// Build a pattern node.
567    pub fn new(kind: PatternKind, span: Span) -> Pattern {
568        Pattern { kind, span }
569    }
570
571    /// Collect every name bound by this pattern, in source order.
572    pub fn bound_names(&self, out: &mut Vec<Ident>) {
573        match &self.kind {
574            PatternKind::Ident(id) => out.push(id.clone()),
575            PatternKind::Array { elements, rest, .. }
576            | PatternKind::Object {
577                properties: elements,
578                rest,
579                ..
580            } => {
581                for element in elements.iter().flatten() {
582                    match element {
583                        PatternElement::Pattern(p) => p.bound_names(out),
584                        PatternElement::Property { value, .. } => value.bound_names(out),
585                    }
586                }
587                if let Some(rest) = rest {
588                    match &**rest {
589                        RestElement::Pattern(p) => p.bound_names(out),
590                        RestElement::Member(m) => m.bound_names(out),
591                    }
592                }
593            }
594            PatternKind::Assign { target, .. } => target.bound_names(out),
595            PatternKind::Rest(target) => target.bound_names(out),
596            PatternKind::Invalid(_) => {}
597            PatternKind::Member(m) => m.bound_names(out),
598        }
599    }
600}
601
602/// Pattern payloads.
603#[derive(Debug, Clone, PartialEq)]
604pub enum PatternKind {
605    /// A binding identifier.
606    Ident(Ident),
607    /// `[a, , b, ...rest]`
608    Array {
609        /// Element patterns; `None` for an elision (`,,`).
610        elements: Vec<Option<PatternElement>>,
611        /// Trailing rest element.
612        rest: Option<Box<RestElement>>,
613    },
614    /// `{ a, b: c, [k]: d, ...rest }`
615    Object {
616        /// Properties, in source order.
617        properties: Vec<Option<PatternElement>>,
618        /// Trailing rest element.
619        rest: Option<Box<RestElement>>,
620    },
621    /// `target = default`
622    Assign {
623        /// Pattern being defaulted.
624        target: Box<Pattern>,
625        /// Default value expression.
626        default: Box<Expr>,
627    },
628    /// `obj.prop` / `obj[k]` — only valid as an assignment target, never as a
629    /// binding pattern.
630    Member(Box<MemberPattern>),
631    /// `...target` — a rest element of a parameter list or pattern.
632    Rest(Box<Pattern>),
633    /// An assignment target that is not assignable (`a() = 1`). QuickJS rejects
634    /// this at run time rather than at parse time, so the compiler has to raise
635    /// the error while evaluating the expression.
636    Invalid(Box<Expr>),
637}
638
639/// An element of an array or object pattern.
640#[derive(Debug, Clone, PartialEq)]
641pub enum PatternElement {
642    /// A nested pattern (array element, or an object property's value).
643    Pattern(Pattern),
644    /// An object property with an explicit key.
645    Property {
646        /// Property key.
647        key: PropName,
648        /// Bound pattern.
649        value: Pattern,
650        /// Whether the source used shorthand (`{a}` versus `{a: a}`).
651        shorthand: bool,
652        /// Source range.
653        span: Span,
654    },
655}
656
657/// `...` in a pattern.
658#[derive(Debug, Clone, PartialEq)]
659pub enum RestElement {
660    /// `...rest` where `rest` is a binding/assignment pattern.
661    Pattern(Pattern),
662    /// `...[a, b]` style member target inside an assignment pattern.
663    Member(Box<MemberPattern>),
664}
665
666/// A member expression used as an assignment target.
667#[derive(Debug, Clone, PartialEq)]
668pub struct MemberPattern {
669    /// Object being accessed.
670    pub object: Box<Expr>,
671    /// Property selector.
672    pub property: MemberProp,
673    /// Source range.
674    pub span: Span,
675    /// Where the selector punctuator (`.` or `[`) sits, carried over from the
676    /// expression this pattern came from.
677    ///
678    /// A store is blamed on that token, not on the `=` and not on the base object, so
679    /// the compiler needs the position after the expression has been turned into a
680    /// pattern.
681    pub op_pos: Option<Position>,
682}
683
684impl MemberPattern {
685    /// Member targets never bind names; provided so patterns can be walked
686    /// uniformly.
687    pub fn bound_names(&self, _out: &mut Vec<Ident>) {}
688}
689
690// ---------------------------------------------------------------------------
691// Expressions
692// ---------------------------------------------------------------------------
693
694/// An expression.
695#[derive(Debug, Clone, PartialEq)]
696pub struct Expr {
697    /// Expression payload.
698    pub kind: ExprKind,
699    /// Source range.
700    pub span: Span,
701    /// Where the operator or punctuator that produced this node sits.
702    ///
703    /// Stack traces report the position of the token that failed, not the start of
704    /// the enclosing expression: `1 + null[0]` blames the `[`, and `o.foo = 1` blames
705    /// the `.`. `span.start` cannot stand in for it — the base expression starts
706    /// earlier — so the parser records the token here for the node kinds that emit an
707    /// instruction at an operator, and the compiler puts it in the position table.
708    pub op_pos: Option<Position>,
709}
710
711impl Expr {
712    /// Build an expression node.
713    pub fn new(kind: ExprKind, span: Span) -> Expr {
714        Expr {
715            kind,
716            span,
717            op_pos: None,
718        }
719    }
720
721    /// Build an expression node whose failing instruction sits at `pos`.
722    pub fn at_operator(kind: ExprKind, span: Span, pos: Position) -> Expr {
723        Expr {
724            kind,
725            span,
726            op_pos: Some(pos),
727        }
728    }
729
730    /// Strip any `( … )` wrappers, which carry no runtime meaning.
731    pub fn unparen(&self) -> &Expr {
732        let mut expr = self;
733        while let ExprKind::Paren(inner) = &expr.kind {
734            expr = inner;
735        }
736        expr
737    }
738
739    /// Whether this expression is an anonymous function definition, which takes
740    /// its name from the binding it is assigned to (`var f = function(){}`).
741    ///
742    /// Parentheses are looked through: `[f = (function(){})] = []` still names the
743    /// function `f`. A sequence expression does **not** — `(0, function(){})` is an
744    /// anonymous function used as a value, and `NamedEvaluation` only reaches a form
745    /// that *is* a function definition.
746    pub fn is_anonymous_function_definition(&self) -> bool {
747        match &self.unparen().kind {
748            ExprKind::Function(f) => f.name.is_none() && !f.is_arrow,
749            // An arrow is anonymous by construction — it has no name of its own to
750            // write — and still takes one from the binding: `var f = () => {}` leaves
751            // `f.name === "f"`, which is what a stack frame prints.
752            ExprKind::Arrow(_) => true,
753            // A class that already has an own `name` — `class { static name(){} }` — keeps
754            // it: `NamedEvaluation` only sets the name when the class has none.
755            ExprKind::Class(c) => c.name.is_none() && !c.has_own_name(),
756            _ => false,
757        }
758    }
759}
760
761/// Expression payloads.
762#[derive(Debug, Clone, PartialEq)]
763pub enum ExprKind {
764    /// An identifier reference (not resolved to a binding yet).
765    Ident(Ident),
766    /// `null`
767    Null,
768    /// `true` / `false`
769    Bool(bool),
770    /// `1.5`
771    Number(f64),
772    /// `1n`
773    BigInt {
774        /// Digits without prefix or separators.
775        digits: String,
776        /// 2, 8, 10 or 16.
777        radix: u32,
778    },
779    /// `"text"`
780    ///
781    /// A [`Wtf8`] because a literal may hold an unpaired surrogate, which `String` cannot.
782    String(Wtf8),
783    /// `/pattern/flags`
784    RegExp {
785        /// Pattern source.
786        pattern: String,
787        /// Flag letters.
788        flags: String,
789    },
790    /// `this`
791    This,
792    /// `[a, b, ...c]`
793    Array {
794        /// Elements; `None` for an elision.
795        elements: Vec<Option<ArrayElement>>,
796    },
797    /// `{ a, b: c, ...d }`
798    Object(Vec<ObjectProperty>),
799    /// `function name() {}`
800    Function(Box<Function>),
801    /// `(params) => body`
802    Arrow(Box<Function>),
803    /// `class { }`
804    Class(Box<Class>),
805    /// `` `a${b}c` ``
806    Template(Box<TemplateLiteral>),
807    /// `` tag`a${b}c` ``
808    TaggedTemplate {
809        /// Tag function.
810        tag: Box<Expr>,
811        /// Template parts.
812        quasi: Box<TemplateLiteral>,
813    },
814    /// `a.b`, `a[b]`, `a?.b`, `super.x`
815    Member {
816        /// Base object.
817        object: Box<Expr>,
818        /// Selector.
819        property: MemberProp,
820        /// Whether `?.` was used.
821        optional: bool,
822    },
823    /// `f(args)`
824    Call {
825        /// Callee.
826        callee: Box<Expr>,
827        /// Arguments.
828        arguments: Vec<Expr>,
829        /// Whether `?.()` was used.
830        optional: bool,
831    },
832    /// `new C(args)` / `new C`
833    New {
834        /// Constructor.
835        callee: Box<Expr>,
836        /// Arguments; `None` for `new C` without a list.
837        arguments: Option<Vec<Expr>>,
838    },
839    /// `new.target`
840    NewTarget,
841    /// `import.meta`
842    ImportMeta,
843    /// `import(specifier)` / `import(specifier, options)`
844    ///
845    /// The second field is the import-attributes bag, which is `Some` only when the source
846    /// wrote one. It is kept in the tree rather than dropped at parse time because
847    /// §13.3.10.1 step 4 makes it an expression that must still be **evaluated** — its side
848    /// effects happen, in that order, even though this loader reads no attributes
849    /// (`dynamic-import/import-attributes/2nd-param-evaluation-sequence`).
850    ImportCall(Box<Expr>, Option<Box<Expr>>),
851    /// `super()` — only valid in a derived constructor.
852    SuperCall(Vec<Expr>),
853    /// `super.x` / `super[x]` base (never standalone).
854    SuperProp,
855    /// `op expr`
856    Unary {
857        /// Operator.
858        op: UnaryOp,
859        /// Operand.
860        argument: Box<Expr>,
861    },
862    /// `++x`, `x--`
863    Update {
864        /// Operator.
865        op: UpdateOp,
866        /// Operand.
867        argument: Box<Expr>,
868        /// Whether the operator came before the operand.
869        prefix: bool,
870    },
871    /// `a + b`, `a instanceof b`, `a in b`, …
872    Binary {
873        /// Operator.
874        op: BinaryOp,
875        /// Left operand.
876        left: Box<Expr>,
877        /// Right operand.
878        right: Box<Expr>,
879    },
880    /// `a && b`, `a || b`, `a ?? b` (kept separate for mixing rules and
881    /// short-circuit code generation).
882    Logical {
883        /// Operator.
884        op: LogicalOp,
885        /// Left operand.
886        left: Box<Expr>,
887        /// Right operand.
888        right: Box<Expr>,
889    },
890    /// `a ? b : c`
891    Conditional {
892        /// Condition.
893        test: Box<Expr>,
894        /// Consequent.
895        cons: Box<Expr>,
896        /// Alternate.
897        alt: Box<Expr>,
898    },
899    /// `target op= value`
900    Assign {
901        /// Assignment operator.
902        op: AssignOp,
903        /// Assignment target (converted from the cover grammar).
904        target: Box<Pattern>,
905        /// Right-hand side.
906        value: Box<Expr>,
907    },
908    /// `(expr)` — kept as a node so that early errors can tell `(a ?? b) || c`
909    /// (legal) from `a ?? b || c` (SyntaxError), and `(a) = 1` from `(a, b) = 1`.
910    Paren(Box<Expr>),
911    /// `(a, b, c)`
912    Sequence(Vec<Expr>),
913    /// `yield expr` / `yield* expr`
914    Yield {
915        /// Operand; `None` for `yield;`.
916        argument: Option<Box<Expr>>,
917        /// Whether `yield*` was used.
918        delegate: bool,
919    },
920    /// `await expr`
921    Await(Box<Expr>),
922    /// `...expr` — only valid in call arguments, arrays and object literals.
923    Spread(Box<Expr>),
924    /// A member/call chain that contains at least one `?.`. Compiling the
925    /// wrapper short-circuits the whole spine when a link's base is nullish.
926    OptionalChain(Box<Expr>),
927    /// `#x in obj`
928    PrivateIn {
929        /// Private name.
930        name: Ident,
931        /// Tested object.
932        object: Box<Expr>,
933    },
934}
935
936/// One element of an array literal.
937#[derive(Debug, Clone, PartialEq)]
938pub enum ArrayElement {
939    /// An ordinary element.
940    Expr(Box<Expr>),
941    /// `...iterable`
942    Spread(Box<Expr>),
943}
944
945/// What an object-literal property does with its value.
946///
947/// Distinct from [`MethodKind`] on purpose: an object literal can never contain a
948/// `constructor`, and the compiler needs to tell `{a: 1}` from `{a() {}}` — the two
949/// compile to different instructions (`define_field` vs `define_method`), even though
950/// both hold a value on the stack.
951#[derive(Debug, Clone, Copy, PartialEq, Eq)]
952pub enum PropertyKind {
953    /// `key: value` or the `{key}` shorthand — stores a data property.
954    Value,
955    /// `m() {}` — defines a method.
956    Method,
957    /// `get m() {}` — the value is the getter.
958    Get,
959    /// `set m(v) {}` — the value is the setter.
960    Set,
961}
962
963/// One property of an object literal.
964#[derive(Debug, Clone, PartialEq)]
965pub enum ObjectProperty {
966    /// `key: value`, `key`, `get key() {}`, `[key]: value`, …
967    Property {
968        /// Property key.
969        key: PropName,
970        /// Value expression; for `get`/`set` it is the function.
971        value: Box<Expr>,
972        /// Whether this stores a value or defines an accessor/method.
973        kind: PropertyKind,
974        /// Whether the source used shorthand (`{a}` / `{a = 1}`).
975        shorthand: bool,
976        /// Source range.
977        span: Span,
978    },
979    /// `...spread`
980    Spread(Box<Expr>),
981}
982
983/// A template literal: `quasis.len() == expressions.len() + 1`.
984#[derive(Debug, Clone, PartialEq)]
985pub struct TemplateLiteral {
986    /// Literal chunks, in source order.
987    pub quasis: Vec<TemplateChunk>,
988    /// Substitution expressions, in source order.
989    pub expressions: Vec<Expr>,
990}
991
992/// One chunk of a [`TemplateLiteral`].
993#[derive(Debug, Clone, PartialEq, Eq)]
994pub struct TemplateChunk {
995    /// Escape-expanded text; `None` when the chunk has an invalid escape
996    /// sequence (legal in tagged templates only, where it becomes `undefined`).
997    ///
998    /// A [`Wtf8`] because a template may hold an unpaired surrogate, just as a string
999    /// literal may.
1000    pub cooked: Option<Wtf8>,
1001    /// Source text, verbatim.
1002    pub raw: String,
1003    /// Whether this chunk ends with the closing backtick.
1004    pub tail: bool,
1005}
1006
1007/// Property selector of a member expression.
1008#[derive(Debug, Clone, PartialEq)]
1009pub enum MemberProp {
1010    /// `.name`
1011    Ident(Ident),
1012    /// `[expr]`
1013    Computed(Box<Expr>),
1014    /// `.#name`
1015    Private(Ident),
1016}
1017
1018/// Unary operators.
1019#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1020pub enum UnaryOp {
1021    /// `-`
1022    Minus,
1023    /// `+`
1024    Plus,
1025    /// `!`
1026    Not,
1027    /// `~`
1028    BitNot,
1029    /// `typeof`
1030    Typeof,
1031    /// `void`
1032    Void,
1033    /// `delete`
1034    Delete,
1035}
1036
1037impl UnaryOp {
1038    /// The operator text.
1039    pub fn as_str(self) -> &'static str {
1040        match self {
1041            UnaryOp::Minus => "-",
1042            UnaryOp::Plus => "+",
1043            UnaryOp::Not => "!",
1044            UnaryOp::BitNot => "~",
1045            UnaryOp::Typeof => "typeof",
1046            UnaryOp::Void => "void",
1047            UnaryOp::Delete => "delete",
1048        }
1049    }
1050}
1051
1052/// `++`/`--`.
1053#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1054pub enum UpdateOp {
1055    /// `++`
1056    Increment,
1057    /// `--`
1058    Decrement,
1059}
1060
1061impl UpdateOp {
1062    /// The operator text.
1063    pub fn as_str(self) -> &'static str {
1064        match self {
1065            UpdateOp::Increment => "++",
1066            UpdateOp::Decrement => "--",
1067        }
1068    }
1069}
1070
1071/// Non-short-circuiting binary operators.
1072#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1073pub enum BinaryOp {
1074    /// `==`
1075    Eq,
1076    /// `!=`
1077    NotEq,
1078    /// `===`
1079    StrictEq,
1080    /// `!==`
1081    StrictNotEq,
1082    /// `<`
1083    Lt,
1084    /// `<=`
1085    LtEq,
1086    /// `>`
1087    Gt,
1088    /// `>=`
1089    GtEq,
1090    /// `<<`
1091    Shl,
1092    /// `>>`
1093    Shr,
1094    /// `>>>`
1095    UShr,
1096    /// `+`
1097    Add,
1098    /// `-`
1099    Sub,
1100    /// `*`
1101    Mul,
1102    /// `/`
1103    Div,
1104    /// `%`
1105    Mod,
1106    /// `**`
1107    Pow,
1108    /// `|`
1109    BitOr,
1110    /// `^`
1111    BitXor,
1112    /// `&`
1113    BitAnd,
1114    /// `in`
1115    In,
1116    /// `instanceof`
1117    Instanceof,
1118}
1119
1120impl BinaryOp {
1121    /// The operator text.
1122    pub fn as_str(self) -> &'static str {
1123        match self {
1124            BinaryOp::Eq => "==",
1125            BinaryOp::NotEq => "!=",
1126            BinaryOp::StrictEq => "===",
1127            BinaryOp::StrictNotEq => "!==",
1128            BinaryOp::Lt => "<",
1129            BinaryOp::LtEq => "<=",
1130            BinaryOp::Gt => ">",
1131            BinaryOp::GtEq => ">=",
1132            BinaryOp::Shl => "<<",
1133            BinaryOp::Shr => ">>",
1134            BinaryOp::UShr => ">>>",
1135            BinaryOp::Add => "+",
1136            BinaryOp::Sub => "-",
1137            BinaryOp::Mul => "*",
1138            BinaryOp::Div => "/",
1139            BinaryOp::Mod => "%",
1140            BinaryOp::Pow => "**",
1141            BinaryOp::BitOr => "|",
1142            BinaryOp::BitXor => "^",
1143            BinaryOp::BitAnd => "&",
1144            BinaryOp::In => "in",
1145            BinaryOp::Instanceof => "instanceof",
1146        }
1147    }
1148
1149    /// Whether the operator is relational (`in`/`instanceof` included), which
1150    /// matters for the `no-in` restriction in `for` heads.
1151    pub fn is_relational(self) -> bool {
1152        matches!(
1153            self,
1154            BinaryOp::Lt
1155                | BinaryOp::LtEq
1156                | BinaryOp::Gt
1157                | BinaryOp::GtEq
1158                | BinaryOp::In
1159                | BinaryOp::Instanceof
1160        )
1161    }
1162}
1163
1164/// Short-circuiting operators.
1165#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1166pub enum LogicalOp {
1167    /// `&&`
1168    And,
1169    /// `||`
1170    Or,
1171    /// `??`
1172    Coalesce,
1173}
1174
1175impl LogicalOp {
1176    /// The operator text.
1177    pub fn as_str(self) -> &'static str {
1178        match self {
1179            LogicalOp::And => "&&",
1180            LogicalOp::Or => "||",
1181            LogicalOp::Coalesce => "??",
1182        }
1183    }
1184}
1185
1186/// Assignment operators.
1187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1188pub enum AssignOp {
1189    /// `=`
1190    Assign,
1191    /// `+=`
1192    Add,
1193    /// `-=`
1194    Sub,
1195    /// `*=`
1196    Mul,
1197    /// `/=`
1198    Div,
1199    /// `%=`
1200    Mod,
1201    /// `**=`
1202    Pow,
1203    /// `<<=`
1204    Shl,
1205    /// `>>=`
1206    Shr,
1207    /// `>>>=`
1208    UShr,
1209    /// `|=`
1210    BitOr,
1211    /// `^=`
1212    BitXor,
1213    /// `&=`
1214    BitAnd,
1215    /// `&&=`
1216    And,
1217    /// `||=`
1218    Or,
1219    /// `??=`
1220    Coalesce,
1221}
1222
1223impl AssignOp {
1224    /// The operator text.
1225    pub fn as_str(self) -> &'static str {
1226        match self {
1227            AssignOp::Assign => "=",
1228            AssignOp::Add => "+=",
1229            AssignOp::Sub => "-=",
1230            AssignOp::Mul => "*=",
1231            AssignOp::Div => "/=",
1232            AssignOp::Mod => "%=",
1233            AssignOp::Pow => "**=",
1234            AssignOp::Shl => "<<=",
1235            AssignOp::Shr => ">>=",
1236            AssignOp::UShr => ">>>=",
1237            AssignOp::BitOr => "|=",
1238            AssignOp::BitXor => "^=",
1239            AssignOp::BitAnd => "&=",
1240            AssignOp::And => "&&=",
1241            AssignOp::Or => "||=",
1242            AssignOp::Coalesce => "??=",
1243        }
1244    }
1245
1246    /// Whether this is a simple `=`.
1247    pub fn is_simple(self) -> bool {
1248        matches!(self, AssignOp::Assign)
1249    }
1250
1251    /// The binary operator a compound assignment implies.
1252    pub fn binary_op(self) -> Option<BinaryOp> {
1253        Some(match self {
1254            AssignOp::Assign => return None,
1255            AssignOp::Add => BinaryOp::Add,
1256            AssignOp::Sub => BinaryOp::Sub,
1257            AssignOp::Mul => BinaryOp::Mul,
1258            AssignOp::Div => BinaryOp::Div,
1259            AssignOp::Mod => BinaryOp::Mod,
1260            AssignOp::Pow => BinaryOp::Pow,
1261            AssignOp::Shl => BinaryOp::Shl,
1262            AssignOp::Shr => BinaryOp::Shr,
1263            AssignOp::UShr => BinaryOp::UShr,
1264            AssignOp::BitOr => BinaryOp::BitOr,
1265            AssignOp::BitXor => BinaryOp::BitXor,
1266            AssignOp::BitAnd => BinaryOp::BitAnd,
1267            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => return None,
1268        })
1269    }
1270
1271    /// The logical operator a short-circuiting assignment implies.
1272    pub fn logical_op(self) -> Option<LogicalOp> {
1273        match self {
1274            AssignOp::And => Some(LogicalOp::And),
1275            AssignOp::Or => Some(LogicalOp::Or),
1276            AssignOp::Coalesce => Some(LogicalOp::Coalesce),
1277            _ => None,
1278        }
1279    }
1280
1281    /// Map a punctuator to an assignment operator.
1282    pub fn from_punct(p: Punct) -> Option<AssignOp> {
1283        Some(match p {
1284            Punct::Eq => AssignOp::Assign,
1285            Punct::PlusEq => AssignOp::Add,
1286            Punct::MinusEq => AssignOp::Sub,
1287            Punct::StarEq => AssignOp::Mul,
1288            Punct::SlashEq => AssignOp::Div,
1289            Punct::PercentEq => AssignOp::Mod,
1290            Punct::StarStarEq => AssignOp::Pow,
1291            Punct::ShlEq => AssignOp::Shl,
1292            Punct::ShrEq => AssignOp::Shr,
1293            Punct::UShrEq => AssignOp::UShr,
1294            Punct::PipeEq => AssignOp::BitOr,
1295            Punct::CaretEq => AssignOp::BitXor,
1296            Punct::AmpEq => AssignOp::BitAnd,
1297            Punct::AmpAmpEq => AssignOp::And,
1298            Punct::PipePipeEq => AssignOp::Or,
1299            Punct::QuestionQuestionEq => AssignOp::Coalesce,
1300            _ => return None,
1301        })
1302    }
1303}
1304
1305// ---------------------------------------------------------------------------
1306// Modules
1307// ---------------------------------------------------------------------------
1308
1309/// The name on either side of a module binding, which may be a string.
1310#[derive(Debug, Clone, PartialEq, Eq)]
1311pub enum ModuleName {
1312    /// `foo`
1313    Ident(Ident),
1314    /// `"foo bar"`
1315    ///
1316    /// A `String`, unlike every other cooked string in this tree: a module specifier names
1317    /// a file, so it has to reach the loader as `&str`, and a path cannot contain a lone
1318    /// surrogate. The parser converts with `to_string_lossy` when it builds one, which is
1319    /// also what a filesystem would do with it.
1320    Str(String),
1321}
1322
1323impl ModuleName {
1324    /// The textual name.
1325    pub fn as_str(&self) -> &str {
1326        match self {
1327            ModuleName::Ident(id) => &id.name,
1328            ModuleName::Str(s) => s,
1329        }
1330    }
1331}
1332
1333/// `import …`
1334#[derive(Debug, Clone, PartialEq)]
1335pub struct ImportDecl {
1336    /// What is imported.
1337    pub specifiers: Vec<ImportSpecifier>,
1338    /// Module specifier string.
1339    pub source: String,
1340    /// `with { type: "json" }` attributes.
1341    pub attributes: Vec<ImportAttribute>,
1342    /// Source range.
1343    pub span: Span,
1344}
1345
1346/// One entry of an import clause.
1347#[derive(Debug, Clone, PartialEq)]
1348pub enum ImportSpecifier {
1349    /// `import d from "m"`
1350    Default(Ident),
1351    /// `import * as ns from "m"`
1352    Namespace(Ident),
1353    /// `import { a, b as c } from "m"`
1354    Named {
1355        /// Name in the exporting module.
1356        imported: ModuleName,
1357        /// Local binding.
1358        local: Ident,
1359    },
1360}
1361
1362/// `with { key: "value" }`
1363#[derive(Debug, Clone, PartialEq)]
1364pub struct ImportAttribute {
1365    /// Attribute key.
1366    pub key: String,
1367    /// Attribute value.
1368    pub value: String,
1369    /// Source range.
1370    pub span: Span,
1371}
1372
1373/// `export …`
1374#[derive(Debug, Clone, PartialEq)]
1375pub struct ExportDecl {
1376    /// What is exported.
1377    pub kind: ExportKind,
1378    /// Source range.
1379    pub span: Span,
1380}
1381
1382/// The variants of an export declaration.
1383#[derive(Debug, Clone, PartialEq)]
1384pub enum ExportKind {
1385    /// `export var/let/const/function/class …`
1386    Declaration(Box<Stmt>),
1387    /// `export default expr` / `export default function …` / `export default class …`
1388    Default(Box<Expr>),
1389    /// `export { a, b as c }` / `export { a } from "m"`
1390    Named {
1391        /// Exported bindings.
1392        specifiers: Vec<ExportSpecifier>,
1393        /// Re-export source.
1394        source: Option<String>,
1395        /// Import attributes for the `from` clause.
1396        attributes: Vec<ImportAttribute>,
1397    },
1398    /// `export * from "m"` / `export * as ns from "m"`
1399    All {
1400        /// Re-export source.
1401        source: String,
1402        /// `as ns`, when present.
1403        exported: Option<ModuleName>,
1404        /// Import attributes for the `from` clause.
1405        attributes: Vec<ImportAttribute>,
1406    },
1407}
1408
1409/// One entry of an `export { … }` clause.
1410#[derive(Debug, Clone, PartialEq)]
1411pub struct ExportSpecifier {
1412    /// Local name (or the name in the source module).
1413    pub local: ModuleName,
1414    /// Exported name.
1415    pub exported: ModuleName,
1416    /// Source range.
1417    pub span: Span,
1418}