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 ///
851 /// The third field is the phase. `import.defer(x)` has no options bag at all — its
852 /// grammar is `import.defer ( AssignmentExpression )` — so a non-`Evaluation` phase
853 /// always pairs with `None`.
854 ImportCall(Box<Expr>, Option<Box<Expr>>, ImportPhase),
855 /// `super()` — only valid in a derived constructor.
856 SuperCall(Vec<Expr>),
857 /// `super.x` / `super[x]` base (never standalone).
858 SuperProp,
859 /// `op expr`
860 Unary {
861 /// Operator.
862 op: UnaryOp,
863 /// Operand.
864 argument: Box<Expr>,
865 },
866 /// `++x`, `x--`
867 Update {
868 /// Operator.
869 op: UpdateOp,
870 /// Operand.
871 argument: Box<Expr>,
872 /// Whether the operator came before the operand.
873 prefix: bool,
874 },
875 /// `a + b`, `a instanceof b`, `a in b`, …
876 Binary {
877 /// Operator.
878 op: BinaryOp,
879 /// Left operand.
880 left: Box<Expr>,
881 /// Right operand.
882 right: Box<Expr>,
883 },
884 /// `a && b`, `a || b`, `a ?? b` (kept separate for mixing rules and
885 /// short-circuit code generation).
886 Logical {
887 /// Operator.
888 op: LogicalOp,
889 /// Left operand.
890 left: Box<Expr>,
891 /// Right operand.
892 right: Box<Expr>,
893 },
894 /// `a ? b : c`
895 Conditional {
896 /// Condition.
897 test: Box<Expr>,
898 /// Consequent.
899 cons: Box<Expr>,
900 /// Alternate.
901 alt: Box<Expr>,
902 },
903 /// `target op= value`
904 Assign {
905 /// Assignment operator.
906 op: AssignOp,
907 /// Assignment target (converted from the cover grammar).
908 target: Box<Pattern>,
909 /// Right-hand side.
910 value: Box<Expr>,
911 },
912 /// `(expr)` — kept as a node so that early errors can tell `(a ?? b) || c`
913 /// (legal) from `a ?? b || c` (SyntaxError), and `(a) = 1` from `(a, b) = 1`.
914 Paren(Box<Expr>),
915 /// `(a, b, c)`
916 Sequence(Vec<Expr>),
917 /// `yield expr` / `yield* expr`
918 Yield {
919 /// Operand; `None` for `yield;`.
920 argument: Option<Box<Expr>>,
921 /// Whether `yield*` was used.
922 delegate: bool,
923 },
924 /// `await expr`
925 Await(Box<Expr>),
926 /// `...expr` — only valid in call arguments, arrays and object literals.
927 Spread(Box<Expr>),
928 /// A member/call chain that contains at least one `?.`. Compiling the
929 /// wrapper short-circuits the whole spine when a link's base is nullish.
930 OptionalChain(Box<Expr>),
931 /// `#x in obj`
932 PrivateIn {
933 /// Private name.
934 name: Ident,
935 /// Tested object.
936 object: Box<Expr>,
937 },
938}
939
940/// One element of an array literal.
941#[derive(Debug, Clone, PartialEq)]
942pub enum ArrayElement {
943 /// An ordinary element.
944 Expr(Box<Expr>),
945 /// `...iterable`
946 Spread(Box<Expr>),
947}
948
949/// What an object-literal property does with its value.
950///
951/// Distinct from [`MethodKind`] on purpose: an object literal can never contain a
952/// `constructor`, and the compiler needs to tell `{a: 1}` from `{a() {}}` — the two
953/// compile to different instructions (`define_field` vs `define_method`), even though
954/// both hold a value on the stack.
955#[derive(Debug, Clone, Copy, PartialEq, Eq)]
956pub enum PropertyKind {
957 /// `key: value` or the `{key}` shorthand — stores a data property.
958 Value,
959 /// `m() {}` — defines a method.
960 Method,
961 /// `get m() {}` — the value is the getter.
962 Get,
963 /// `set m(v) {}` — the value is the setter.
964 Set,
965}
966
967/// One property of an object literal.
968#[derive(Debug, Clone, PartialEq)]
969pub enum ObjectProperty {
970 /// `key: value`, `key`, `get key() {}`, `[key]: value`, …
971 Property {
972 /// Property key.
973 key: PropName,
974 /// Value expression; for `get`/`set` it is the function.
975 value: Box<Expr>,
976 /// Whether this stores a value or defines an accessor/method.
977 kind: PropertyKind,
978 /// Whether the source used shorthand (`{a}` / `{a = 1}`).
979 shorthand: bool,
980 /// Source range.
981 span: Span,
982 },
983 /// `...spread`
984 Spread(Box<Expr>),
985}
986
987/// A template literal: `quasis.len() == expressions.len() + 1`.
988#[derive(Debug, Clone, PartialEq)]
989pub struct TemplateLiteral {
990 /// Literal chunks, in source order.
991 pub quasis: Vec<TemplateChunk>,
992 /// Substitution expressions, in source order.
993 pub expressions: Vec<Expr>,
994}
995
996/// One chunk of a [`TemplateLiteral`].
997#[derive(Debug, Clone, PartialEq, Eq)]
998pub struct TemplateChunk {
999 /// Escape-expanded text; `None` when the chunk has an invalid escape
1000 /// sequence (legal in tagged templates only, where it becomes `undefined`).
1001 ///
1002 /// A [`Wtf8`] because a template may hold an unpaired surrogate, just as a string
1003 /// literal may.
1004 pub cooked: Option<Wtf8>,
1005 /// Source text, verbatim.
1006 pub raw: String,
1007 /// Whether this chunk ends with the closing backtick.
1008 pub tail: bool,
1009}
1010
1011/// Property selector of a member expression.
1012#[derive(Debug, Clone, PartialEq)]
1013pub enum MemberProp {
1014 /// `.name`
1015 Ident(Ident),
1016 /// `[expr]`
1017 Computed(Box<Expr>),
1018 /// `.#name`
1019 Private(Ident),
1020}
1021
1022/// Unary operators.
1023#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1024pub enum UnaryOp {
1025 /// `-`
1026 Minus,
1027 /// `+`
1028 Plus,
1029 /// `!`
1030 Not,
1031 /// `~`
1032 BitNot,
1033 /// `typeof`
1034 Typeof,
1035 /// `void`
1036 Void,
1037 /// `delete`
1038 Delete,
1039}
1040
1041impl UnaryOp {
1042 /// The operator text.
1043 pub fn as_str(self) -> &'static str {
1044 match self {
1045 UnaryOp::Minus => "-",
1046 UnaryOp::Plus => "+",
1047 UnaryOp::Not => "!",
1048 UnaryOp::BitNot => "~",
1049 UnaryOp::Typeof => "typeof",
1050 UnaryOp::Void => "void",
1051 UnaryOp::Delete => "delete",
1052 }
1053 }
1054}
1055
1056/// `++`/`--`.
1057#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1058pub enum UpdateOp {
1059 /// `++`
1060 Increment,
1061 /// `--`
1062 Decrement,
1063}
1064
1065impl UpdateOp {
1066 /// The operator text.
1067 pub fn as_str(self) -> &'static str {
1068 match self {
1069 UpdateOp::Increment => "++",
1070 UpdateOp::Decrement => "--",
1071 }
1072 }
1073}
1074
1075/// Non-short-circuiting binary operators.
1076#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1077pub enum BinaryOp {
1078 /// `==`
1079 Eq,
1080 /// `!=`
1081 NotEq,
1082 /// `===`
1083 StrictEq,
1084 /// `!==`
1085 StrictNotEq,
1086 /// `<`
1087 Lt,
1088 /// `<=`
1089 LtEq,
1090 /// `>`
1091 Gt,
1092 /// `>=`
1093 GtEq,
1094 /// `<<`
1095 Shl,
1096 /// `>>`
1097 Shr,
1098 /// `>>>`
1099 UShr,
1100 /// `+`
1101 Add,
1102 /// `-`
1103 Sub,
1104 /// `*`
1105 Mul,
1106 /// `/`
1107 Div,
1108 /// `%`
1109 Mod,
1110 /// `**`
1111 Pow,
1112 /// `|`
1113 BitOr,
1114 /// `^`
1115 BitXor,
1116 /// `&`
1117 BitAnd,
1118 /// `in`
1119 In,
1120 /// `instanceof`
1121 Instanceof,
1122}
1123
1124impl BinaryOp {
1125 /// The operator text.
1126 pub fn as_str(self) -> &'static str {
1127 match self {
1128 BinaryOp::Eq => "==",
1129 BinaryOp::NotEq => "!=",
1130 BinaryOp::StrictEq => "===",
1131 BinaryOp::StrictNotEq => "!==",
1132 BinaryOp::Lt => "<",
1133 BinaryOp::LtEq => "<=",
1134 BinaryOp::Gt => ">",
1135 BinaryOp::GtEq => ">=",
1136 BinaryOp::Shl => "<<",
1137 BinaryOp::Shr => ">>",
1138 BinaryOp::UShr => ">>>",
1139 BinaryOp::Add => "+",
1140 BinaryOp::Sub => "-",
1141 BinaryOp::Mul => "*",
1142 BinaryOp::Div => "/",
1143 BinaryOp::Mod => "%",
1144 BinaryOp::Pow => "**",
1145 BinaryOp::BitOr => "|",
1146 BinaryOp::BitXor => "^",
1147 BinaryOp::BitAnd => "&",
1148 BinaryOp::In => "in",
1149 BinaryOp::Instanceof => "instanceof",
1150 }
1151 }
1152
1153 /// Whether the operator is relational (`in`/`instanceof` included), which
1154 /// matters for the `no-in` restriction in `for` heads.
1155 pub fn is_relational(self) -> bool {
1156 matches!(
1157 self,
1158 BinaryOp::Lt
1159 | BinaryOp::LtEq
1160 | BinaryOp::Gt
1161 | BinaryOp::GtEq
1162 | BinaryOp::In
1163 | BinaryOp::Instanceof
1164 )
1165 }
1166}
1167
1168/// Short-circuiting operators.
1169#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1170pub enum LogicalOp {
1171 /// `&&`
1172 And,
1173 /// `||`
1174 Or,
1175 /// `??`
1176 Coalesce,
1177}
1178
1179impl LogicalOp {
1180 /// The operator text.
1181 pub fn as_str(self) -> &'static str {
1182 match self {
1183 LogicalOp::And => "&&",
1184 LogicalOp::Or => "||",
1185 LogicalOp::Coalesce => "??",
1186 }
1187 }
1188}
1189
1190/// Assignment operators.
1191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1192pub enum AssignOp {
1193 /// `=`
1194 Assign,
1195 /// `+=`
1196 Add,
1197 /// `-=`
1198 Sub,
1199 /// `*=`
1200 Mul,
1201 /// `/=`
1202 Div,
1203 /// `%=`
1204 Mod,
1205 /// `**=`
1206 Pow,
1207 /// `<<=`
1208 Shl,
1209 /// `>>=`
1210 Shr,
1211 /// `>>>=`
1212 UShr,
1213 /// `|=`
1214 BitOr,
1215 /// `^=`
1216 BitXor,
1217 /// `&=`
1218 BitAnd,
1219 /// `&&=`
1220 And,
1221 /// `||=`
1222 Or,
1223 /// `??=`
1224 Coalesce,
1225}
1226
1227impl AssignOp {
1228 /// The operator text.
1229 pub fn as_str(self) -> &'static str {
1230 match self {
1231 AssignOp::Assign => "=",
1232 AssignOp::Add => "+=",
1233 AssignOp::Sub => "-=",
1234 AssignOp::Mul => "*=",
1235 AssignOp::Div => "/=",
1236 AssignOp::Mod => "%=",
1237 AssignOp::Pow => "**=",
1238 AssignOp::Shl => "<<=",
1239 AssignOp::Shr => ">>=",
1240 AssignOp::UShr => ">>>=",
1241 AssignOp::BitOr => "|=",
1242 AssignOp::BitXor => "^=",
1243 AssignOp::BitAnd => "&=",
1244 AssignOp::And => "&&=",
1245 AssignOp::Or => "||=",
1246 AssignOp::Coalesce => "??=",
1247 }
1248 }
1249
1250 /// Whether this is a simple `=`.
1251 pub fn is_simple(self) -> bool {
1252 matches!(self, AssignOp::Assign)
1253 }
1254
1255 /// The binary operator a compound assignment implies.
1256 pub fn binary_op(self) -> Option<BinaryOp> {
1257 Some(match self {
1258 AssignOp::Assign => return None,
1259 AssignOp::Add => BinaryOp::Add,
1260 AssignOp::Sub => BinaryOp::Sub,
1261 AssignOp::Mul => BinaryOp::Mul,
1262 AssignOp::Div => BinaryOp::Div,
1263 AssignOp::Mod => BinaryOp::Mod,
1264 AssignOp::Pow => BinaryOp::Pow,
1265 AssignOp::Shl => BinaryOp::Shl,
1266 AssignOp::Shr => BinaryOp::Shr,
1267 AssignOp::UShr => BinaryOp::UShr,
1268 AssignOp::BitOr => BinaryOp::BitOr,
1269 AssignOp::BitXor => BinaryOp::BitXor,
1270 AssignOp::BitAnd => BinaryOp::BitAnd,
1271 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => return None,
1272 })
1273 }
1274
1275 /// The logical operator a short-circuiting assignment implies.
1276 pub fn logical_op(self) -> Option<LogicalOp> {
1277 match self {
1278 AssignOp::And => Some(LogicalOp::And),
1279 AssignOp::Or => Some(LogicalOp::Or),
1280 AssignOp::Coalesce => Some(LogicalOp::Coalesce),
1281 _ => None,
1282 }
1283 }
1284
1285 /// Map a punctuator to an assignment operator.
1286 pub fn from_punct(p: Punct) -> Option<AssignOp> {
1287 Some(match p {
1288 Punct::Eq => AssignOp::Assign,
1289 Punct::PlusEq => AssignOp::Add,
1290 Punct::MinusEq => AssignOp::Sub,
1291 Punct::StarEq => AssignOp::Mul,
1292 Punct::SlashEq => AssignOp::Div,
1293 Punct::PercentEq => AssignOp::Mod,
1294 Punct::StarStarEq => AssignOp::Pow,
1295 Punct::ShlEq => AssignOp::Shl,
1296 Punct::ShrEq => AssignOp::Shr,
1297 Punct::UShrEq => AssignOp::UShr,
1298 Punct::PipeEq => AssignOp::BitOr,
1299 Punct::CaretEq => AssignOp::BitXor,
1300 Punct::AmpEq => AssignOp::BitAnd,
1301 Punct::AmpAmpEq => AssignOp::And,
1302 Punct::PipePipeEq => AssignOp::Or,
1303 Punct::QuestionQuestionEq => AssignOp::Coalesce,
1304 _ => return None,
1305 })
1306 }
1307}
1308
1309// ---------------------------------------------------------------------------
1310// Modules
1311// ---------------------------------------------------------------------------
1312
1313/// The name on either side of a module binding, which may be a string.
1314#[derive(Debug, Clone, PartialEq, Eq)]
1315pub enum ModuleName {
1316 /// `foo`
1317 Ident(Ident),
1318 /// `"foo bar"`
1319 ///
1320 /// A `String`, unlike every other cooked string in this tree: a module specifier names
1321 /// a file, so it has to reach the loader as `&str`, and a path cannot contain a lone
1322 /// surrogate. The parser converts with `to_string_lossy` when it builds one, which is
1323 /// also what a filesystem would do with it.
1324 Str(String),
1325}
1326
1327impl ModuleName {
1328 /// The textual name.
1329 pub fn as_str(&self) -> &str {
1330 match self {
1331 ModuleName::Ident(id) => &id.name,
1332 ModuleName::Str(s) => s,
1333 }
1334 }
1335}
1336
1337/// `import …`
1338#[derive(Debug, Clone, PartialEq)]
1339pub struct ImportDecl {
1340 /// Which phase of the module the clause names.
1341 pub phase: ImportPhase,
1342 /// What is imported.
1343 pub specifiers: Vec<ImportSpecifier>,
1344 /// Module specifier string.
1345 pub source: String,
1346 /// `with { type: "json" }` attributes.
1347 pub attributes: Vec<ImportAttribute>,
1348 /// Source range.
1349 pub span: Span,
1350}
1351
1352/// The phase a module request asks for.
1353///
1354/// This is the source-phase-imports proposal's `[[Phase]]`. A plain `import` asks for the
1355/// *evaluation* phase, which is the only one ECMA-262 itself defines; the other two come
1356/// from proposals that hang off the same grammar:
1357///
1358/// * `import defer * as ns from "m"` — a namespace whose module is not evaluated until
1359/// something reads through it (the import-defer proposal);
1360/// * `import source x from "m"` — the module *source object* rather than its namespace
1361/// (source-phase-imports).
1362///
1363/// The phase belongs to the request rather than to the binding, because two clauses naming
1364/// one specifier at different phases are two requests: §16.2.1.5 de-duplicates
1365/// `[[RequestedModules]]` on `[[Specifier]]` **and** `[[Phase]]`.
1366#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1367pub enum ImportPhase {
1368 /// `import …` / `import(…)` — evaluate the module and hand back its namespace.
1369 #[default]
1370 Evaluation,
1371 /// `import defer …` / `import.defer(…)` — evaluate on first use.
1372 Defer,
1373 /// `import source …` / `import.source(…)` — hand back the source text.
1374 Source,
1375}
1376
1377impl ImportPhase {
1378 /// Whether this is the ordinary, spec-defined phase.
1379 pub fn is_evaluation(self) -> bool {
1380 self == ImportPhase::Evaluation
1381 }
1382}
1383
1384/// One entry of an import clause.
1385#[derive(Debug, Clone, PartialEq)]
1386pub enum ImportSpecifier {
1387 /// `import d from "m"`
1388 Default(Ident),
1389 /// `import * as ns from "m"`
1390 Namespace(Ident),
1391 /// `import { a, b as c } from "m"`
1392 Named {
1393 /// Name in the exporting module.
1394 imported: ModuleName,
1395 /// Local binding.
1396 local: Ident,
1397 },
1398}
1399
1400/// `with { key: "value" }`
1401#[derive(Debug, Clone, PartialEq)]
1402pub struct ImportAttribute {
1403 /// Attribute key.
1404 pub key: String,
1405 /// Attribute value.
1406 pub value: String,
1407 /// Source range.
1408 pub span: Span,
1409}
1410
1411/// `export …`
1412#[derive(Debug, Clone, PartialEq)]
1413pub struct ExportDecl {
1414 /// What is exported.
1415 pub kind: ExportKind,
1416 /// Source range.
1417 pub span: Span,
1418}
1419
1420/// The variants of an export declaration.
1421#[derive(Debug, Clone, PartialEq)]
1422pub enum ExportKind {
1423 /// `export var/let/const/function/class …`
1424 Declaration(Box<Stmt>),
1425 /// `export default expr` / `export default function …` / `export default class …`
1426 Default(Box<Expr>),
1427 /// `export { a, b as c }` / `export { a } from "m"`
1428 Named {
1429 /// Exported bindings.
1430 specifiers: Vec<ExportSpecifier>,
1431 /// Re-export source.
1432 source: Option<String>,
1433 /// Import attributes for the `from` clause.
1434 attributes: Vec<ImportAttribute>,
1435 },
1436 /// `export * from "m"` / `export * as ns from "m"`
1437 All {
1438 /// Re-export source.
1439 source: String,
1440 /// `as ns`, when present.
1441 exported: Option<ModuleName>,
1442 /// Import attributes for the `from` clause.
1443 attributes: Vec<ImportAttribute>,
1444 },
1445}
1446
1447/// One entry of an `export { … }` clause.
1448#[derive(Debug, Clone, PartialEq)]
1449pub struct ExportSpecifier {
1450 /// Local name (or the name in the source module).
1451 pub local: ModuleName,
1452 /// Exported name.
1453 pub exported: ModuleName,
1454 /// Source range.
1455 pub span: Span,
1456}