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 /// Source range.
344 pub span: Span,
345 /// Range of the parameter list, for error messages and `length`.
346 pub params_span: Span,
347}
348
349/// The body of a [`Function`].
350#[derive(Debug, Clone, PartialEq)]
351pub enum FunctionBody {
352 /// `{ … }`
353 Block(Vec<Stmt>),
354 /// An arrow's expression body (no braces).
355 Expr(Box<Expr>),
356}
357
358impl FunctionBody {
359 /// Statements of a block body, if this is one.
360 pub fn statements(&self) -> Option<&[Stmt]> {
361 match self {
362 FunctionBody::Block(body) => Some(body),
363 FunctionBody::Expr(_) => None,
364 }
365 }
366}
367
368/// A class body.
369#[derive(Debug, Clone, PartialEq)]
370pub struct Class {
371 /// Class name: required for declarations, optional for expressions.
372 pub name: Option<Ident>,
373 /// `extends` clause.
374 pub super_class: Option<Box<Expr>>,
375 /// Members, in source order.
376 pub elements: Vec<ClassElement>,
377 /// Source range.
378 pub span: Span,
379 /// The closing `}` of the body.
380 ///
381 /// A class that writes no constructor still gets one, and the reference creates that
382 /// synthetic function *at* the closing brace: `js_parse_class_default_ctor` runs with
383 /// the `}` as its current token and hands `s->token.ptr` to `js_new_function_def`. The
384 /// position is the function's own `source_pos`, which is the first entry of its
385 /// line table — so `class B extends BigInt {}` constructed as `new B(1)` reports its
386 /// frame at the `}`, not at `class`. `span.end` cannot stand in: it is one *past* the
387 /// brace, and the brace may be the last character of a line.
388 pub body_end: Position,
389}
390
391impl Class {
392 /// Whether the class body itself defines `name`, which an anonymous class then keeps.
393 ///
394 /// `class { static name(){} }` has an own `name` property, so assigning one from the
395 /// binding would either fail or be shadowed — `NamedEvaluation` checks for it and
396 /// leaves the class alone.
397 pub fn has_own_name(&self) -> bool {
398 self.elements.iter().any(|element| match element {
399 ClassElement::Method { key, is_static, .. }
400 | ClassElement::Field { key, is_static, .. } => {
401 *is_static
402 && matches!(key.static_name(), Some(PropKeyRef::Str(name)) if name.as_str() == Some("name"))
403 }
404 ClassElement::StaticBlock { .. } => false,
405 })
406 }
407}
408
409/// The binding a computed field key is stored in.
410///
411/// `js_atom_concat_num(ctx, JS_ATOM_computed_field + is_static, n)` produces
412/// `computed_field0`/`computed_field_static0`; the dump prints them as `<computed_field>0` and
413/// `<computed_field_static>0`, which is the reference's own bracket convention for a hidden
414/// name.
415pub fn computed_field_binding(index: usize, is_static: bool) -> String {
416 if is_static {
417 format!("<computed_field_static>{index}")
418 } else {
419 format!("<computed_field>{index}")
420 }
421}
422
423/// One member of a class body.
424#[derive(Debug, Clone, PartialEq)]
425pub enum ClassElement {
426 /// A method (`constructor`, ordinary, `get`, `set`, generator or async).
427 Method {
428 /// Property key.
429 key: PropName,
430 /// `static`
431 is_static: bool,
432 /// Which kind of method this is.
433 kind: MethodKind,
434 /// The method itself.
435 func: Box<Function>,
436 /// Source range.
437 span: Span,
438 },
439 /// A field (`x = 1`, `#x`, `static x`).
440 Field {
441 /// Property key.
442 key: PropName,
443 /// `static`
444 is_static: bool,
445 /// Initialiser expression.
446 value: Option<Box<Expr>>,
447 /// Source range.
448 span: Span,
449 },
450 /// `static { … }`
451 StaticBlock {
452 /// Block body.
453 body: Vec<Stmt>,
454 /// Position of the opening `{`, which is where the reference puts the function it
455 /// compiles the body into — the seed for the block's line table.
456 body_start: Position,
457 /// Source range.
458 span: Span,
459 },
460}
461
462/// Which kind of method a class member or object literal property defines.
463#[derive(Debug, Clone, Copy, PartialEq, Eq)]
464pub enum MethodKind {
465 /// `constructor`
466 Constructor,
467 /// An ordinary method.
468 Method,
469 /// `get name()`
470 Get,
471 /// `set name(v)`
472 Set,
473}
474
475/// A property key.
476#[derive(Debug, Clone, PartialEq)]
477pub enum PropName {
478 /// A bare identifier, string or numeric key. The variant records which
479 /// spelling was used, because `{ 1e2: x }` needs the numeric value while
480 /// `{ "1e2": x }` needs the string.
481 Literal(PropKey),
482 /// `[expr]`
483 Computed(Box<Expr>),
484 /// `#name` (classes only).
485 Private(Ident),
486}
487
488impl PropName {
489 /// Static name of the key, when it is not computed.
490 pub fn static_name(&self) -> Option<PropKeyRef<'_>> {
491 match self {
492 PropName::Literal(k) => Some(k.as_ref()),
493 PropName::Private(id) => Some(PropKeyRef::Private(&id.name)),
494 PropName::Computed(_) => None,
495 }
496 }
497}
498
499/// A literal property key.
500#[derive(Debug, Clone, PartialEq)]
501pub enum PropKey {
502 /// `foo` or `"foo"` — identical once the value is interned.
503 ///
504 /// A [`Wtf8`]: the quoted form can hold a surrogate the identifier form cannot, so
505 /// the wider type is the one that has to hold both.
506 Str(Wtf8),
507 /// `1`, `1.5`, `0x10` — the numeric value matters for array indexing.
508 Num(f64),
509}
510
511impl PropKey {
512 /// Borrow as [`PropKeyRef`].
513 pub fn as_ref(&self) -> PropKeyRef<'_> {
514 match self {
515 PropKey::Str(s) => PropKeyRef::Str(s),
516 PropKey::Num(n) => PropKeyRef::Num(*n),
517 }
518 }
519}
520
521/// Borrowed view of a [`PropKey`], used by the compiler.
522#[derive(Debug, Clone, Copy, PartialEq)]
523pub enum PropKeyRef<'a> {
524 /// A string key.
525 Str(&'a Wtf8),
526 /// A numeric key.
527 Num(f64),
528 /// A private name.
529 Private(&'a str),
530}
531
532// ---------------------------------------------------------------------------
533// Patterns
534// ---------------------------------------------------------------------------
535
536/// A binding pattern or assignment target.
537#[derive(Debug, Clone, PartialEq)]
538pub struct Pattern {
539 /// Pattern payload.
540 pub kind: PatternKind,
541 /// Source range.
542 pub span: Span,
543}
544
545impl Pattern {
546 /// Build a pattern node.
547 pub fn new(kind: PatternKind, span: Span) -> Pattern {
548 Pattern { kind, span }
549 }
550
551 /// Collect every name bound by this pattern, in source order.
552 pub fn bound_names(&self, out: &mut Vec<Ident>) {
553 match &self.kind {
554 PatternKind::Ident(id) => out.push(id.clone()),
555 PatternKind::Array { elements, rest, .. }
556 | PatternKind::Object {
557 properties: elements,
558 rest,
559 ..
560 } => {
561 for element in elements.iter().flatten() {
562 match element {
563 PatternElement::Pattern(p) => p.bound_names(out),
564 PatternElement::Property { value, .. } => value.bound_names(out),
565 }
566 }
567 if let Some(rest) = rest {
568 match &**rest {
569 RestElement::Pattern(p) => p.bound_names(out),
570 RestElement::Member(m) => m.bound_names(out),
571 }
572 }
573 }
574 PatternKind::Assign { target, .. } => target.bound_names(out),
575 PatternKind::Rest(target) => target.bound_names(out),
576 PatternKind::Invalid(_) => {}
577 PatternKind::Member(m) => m.bound_names(out),
578 }
579 }
580}
581
582/// Pattern payloads.
583#[derive(Debug, Clone, PartialEq)]
584pub enum PatternKind {
585 /// A binding identifier.
586 Ident(Ident),
587 /// `[a, , b, ...rest]`
588 Array {
589 /// Element patterns; `None` for an elision (`,,`).
590 elements: Vec<Option<PatternElement>>,
591 /// Trailing rest element.
592 rest: Option<Box<RestElement>>,
593 },
594 /// `{ a, b: c, [k]: d, ...rest }`
595 Object {
596 /// Properties, in source order.
597 properties: Vec<Option<PatternElement>>,
598 /// Trailing rest element.
599 rest: Option<Box<RestElement>>,
600 },
601 /// `target = default`
602 Assign {
603 /// Pattern being defaulted.
604 target: Box<Pattern>,
605 /// Default value expression.
606 default: Box<Expr>,
607 },
608 /// `obj.prop` / `obj[k]` — only valid as an assignment target, never as a
609 /// binding pattern.
610 Member(Box<MemberPattern>),
611 /// `...target` — a rest element of a parameter list or pattern.
612 Rest(Box<Pattern>),
613 /// An assignment target that is not assignable (`a() = 1`). QuickJS rejects
614 /// this at run time rather than at parse time, so the compiler has to raise
615 /// the error while evaluating the expression.
616 Invalid(Box<Expr>),
617}
618
619/// An element of an array or object pattern.
620#[derive(Debug, Clone, PartialEq)]
621pub enum PatternElement {
622 /// A nested pattern (array element, or an object property's value).
623 Pattern(Pattern),
624 /// An object property with an explicit key.
625 Property {
626 /// Property key.
627 key: PropName,
628 /// Bound pattern.
629 value: Pattern,
630 /// Whether the source used shorthand (`{a}` versus `{a: a}`).
631 shorthand: bool,
632 /// Source range.
633 span: Span,
634 },
635}
636
637/// `...` in a pattern.
638#[derive(Debug, Clone, PartialEq)]
639pub enum RestElement {
640 /// `...rest` where `rest` is a binding/assignment pattern.
641 Pattern(Pattern),
642 /// `...[a, b]` style member target inside an assignment pattern.
643 Member(Box<MemberPattern>),
644}
645
646/// A member expression used as an assignment target.
647#[derive(Debug, Clone, PartialEq)]
648pub struct MemberPattern {
649 /// Object being accessed.
650 pub object: Box<Expr>,
651 /// Property selector.
652 pub property: MemberProp,
653 /// Source range.
654 pub span: Span,
655 /// Where the selector punctuator (`.` or `[`) sits, carried over from the
656 /// expression this pattern came from.
657 ///
658 /// A store is blamed on that token, not on the `=` and not on the base object, so
659 /// the compiler needs the position after the expression has been turned into a
660 /// pattern.
661 pub op_pos: Option<Position>,
662}
663
664impl MemberPattern {
665 /// Member targets never bind names; provided so patterns can be walked
666 /// uniformly.
667 pub fn bound_names(&self, _out: &mut Vec<Ident>) {}
668}
669
670// ---------------------------------------------------------------------------
671// Expressions
672// ---------------------------------------------------------------------------
673
674/// An expression.
675#[derive(Debug, Clone, PartialEq)]
676pub struct Expr {
677 /// Expression payload.
678 pub kind: ExprKind,
679 /// Source range.
680 pub span: Span,
681 /// Where the operator or punctuator that produced this node sits.
682 ///
683 /// Stack traces report the position of the token that failed, not the start of
684 /// the enclosing expression: `1 + null[0]` blames the `[`, and `o.foo = 1` blames
685 /// the `.`. `span.start` cannot stand in for it — the base expression starts
686 /// earlier — so the parser records the token here for the node kinds that emit an
687 /// instruction at an operator, and the compiler puts it in the position table.
688 pub op_pos: Option<Position>,
689}
690
691impl Expr {
692 /// Build an expression node.
693 pub fn new(kind: ExprKind, span: Span) -> Expr {
694 Expr {
695 kind,
696 span,
697 op_pos: None,
698 }
699 }
700
701 /// Build an expression node whose failing instruction sits at `pos`.
702 pub fn at_operator(kind: ExprKind, span: Span, pos: Position) -> Expr {
703 Expr {
704 kind,
705 span,
706 op_pos: Some(pos),
707 }
708 }
709
710 /// Strip any `( … )` wrappers, which carry no runtime meaning.
711 pub fn unparen(&self) -> &Expr {
712 let mut expr = self;
713 while let ExprKind::Paren(inner) = &expr.kind {
714 expr = inner;
715 }
716 expr
717 }
718
719 /// Whether this expression is an anonymous function definition, which takes
720 /// its name from the binding it is assigned to (`var f = function(){}`).
721 ///
722 /// Parentheses are looked through: `[f = (function(){})] = []` still names the
723 /// function `f`. A sequence expression does **not** — `(0, function(){})` is an
724 /// anonymous function used as a value, and `NamedEvaluation` only reaches a form
725 /// that *is* a function definition.
726 pub fn is_anonymous_function_definition(&self) -> bool {
727 match &self.unparen().kind {
728 ExprKind::Function(f) => f.name.is_none() && !f.is_arrow,
729 // An arrow is anonymous by construction — it has no name of its own to
730 // write — and still takes one from the binding: `var f = () => {}` leaves
731 // `f.name === "f"`, which is what a stack frame prints.
732 ExprKind::Arrow(_) => true,
733 // A class that already has an own `name` — `class { static name(){} }` — keeps
734 // it: `NamedEvaluation` only sets the name when the class has none.
735 ExprKind::Class(c) => c.name.is_none() && !c.has_own_name(),
736 _ => false,
737 }
738 }
739}
740
741/// Expression payloads.
742#[derive(Debug, Clone, PartialEq)]
743pub enum ExprKind {
744 /// An identifier reference (not resolved to a binding yet).
745 Ident(Ident),
746 /// `null`
747 Null,
748 /// `true` / `false`
749 Bool(bool),
750 /// `1.5`
751 Number(f64),
752 /// `1n`
753 BigInt {
754 /// Digits without prefix or separators.
755 digits: String,
756 /// 2, 8, 10 or 16.
757 radix: u32,
758 },
759 /// `"text"`
760 ///
761 /// A [`Wtf8`] because a literal may hold an unpaired surrogate, which `String` cannot.
762 String(Wtf8),
763 /// `/pattern/flags`
764 RegExp {
765 /// Pattern source.
766 pattern: String,
767 /// Flag letters.
768 flags: String,
769 },
770 /// `this`
771 This,
772 /// `[a, b, ...c]`
773 Array {
774 /// Elements; `None` for an elision.
775 elements: Vec<Option<ArrayElement>>,
776 },
777 /// `{ a, b: c, ...d }`
778 Object(Vec<ObjectProperty>),
779 /// `function name() {}`
780 Function(Box<Function>),
781 /// `(params) => body`
782 Arrow(Box<Function>),
783 /// `class { }`
784 Class(Box<Class>),
785 /// `` `a${b}c` ``
786 Template(Box<TemplateLiteral>),
787 /// `` tag`a${b}c` ``
788 TaggedTemplate {
789 /// Tag function.
790 tag: Box<Expr>,
791 /// Template parts.
792 quasi: Box<TemplateLiteral>,
793 },
794 /// `a.b`, `a[b]`, `a?.b`, `super.x`
795 Member {
796 /// Base object.
797 object: Box<Expr>,
798 /// Selector.
799 property: MemberProp,
800 /// Whether `?.` was used.
801 optional: bool,
802 },
803 /// `f(args)`
804 Call {
805 /// Callee.
806 callee: Box<Expr>,
807 /// Arguments.
808 arguments: Vec<Expr>,
809 /// Whether `?.()` was used.
810 optional: bool,
811 },
812 /// `new C(args)` / `new C`
813 New {
814 /// Constructor.
815 callee: Box<Expr>,
816 /// Arguments; `None` for `new C` without a list.
817 arguments: Option<Vec<Expr>>,
818 },
819 /// `new.target`
820 NewTarget,
821 /// `import.meta`
822 ImportMeta,
823 /// `import(specifier)`
824 ImportCall(Box<Expr>),
825 /// `super()` — only valid in a derived constructor.
826 SuperCall(Vec<Expr>),
827 /// `super.x` / `super[x]` base (never standalone).
828 SuperProp,
829 /// `op expr`
830 Unary {
831 /// Operator.
832 op: UnaryOp,
833 /// Operand.
834 argument: Box<Expr>,
835 },
836 /// `++x`, `x--`
837 Update {
838 /// Operator.
839 op: UpdateOp,
840 /// Operand.
841 argument: Box<Expr>,
842 /// Whether the operator came before the operand.
843 prefix: bool,
844 },
845 /// `a + b`, `a instanceof b`, `a in b`, …
846 Binary {
847 /// Operator.
848 op: BinaryOp,
849 /// Left operand.
850 left: Box<Expr>,
851 /// Right operand.
852 right: Box<Expr>,
853 },
854 /// `a && b`, `a || b`, `a ?? b` (kept separate for mixing rules and
855 /// short-circuit code generation).
856 Logical {
857 /// Operator.
858 op: LogicalOp,
859 /// Left operand.
860 left: Box<Expr>,
861 /// Right operand.
862 right: Box<Expr>,
863 },
864 /// `a ? b : c`
865 Conditional {
866 /// Condition.
867 test: Box<Expr>,
868 /// Consequent.
869 cons: Box<Expr>,
870 /// Alternate.
871 alt: Box<Expr>,
872 },
873 /// `target op= value`
874 Assign {
875 /// Assignment operator.
876 op: AssignOp,
877 /// Assignment target (converted from the cover grammar).
878 target: Box<Pattern>,
879 /// Right-hand side.
880 value: Box<Expr>,
881 },
882 /// `(expr)` — kept as a node so that early errors can tell `(a ?? b) || c`
883 /// (legal) from `a ?? b || c` (SyntaxError), and `(a) = 1` from `(a, b) = 1`.
884 Paren(Box<Expr>),
885 /// `(a, b, c)`
886 Sequence(Vec<Expr>),
887 /// `yield expr` / `yield* expr`
888 Yield {
889 /// Operand; `None` for `yield;`.
890 argument: Option<Box<Expr>>,
891 /// Whether `yield*` was used.
892 delegate: bool,
893 },
894 /// `await expr`
895 Await(Box<Expr>),
896 /// `...expr` — only valid in call arguments, arrays and object literals.
897 Spread(Box<Expr>),
898 /// A member/call chain that contains at least one `?.`. Compiling the
899 /// wrapper short-circuits the whole spine when a link's base is nullish.
900 OptionalChain(Box<Expr>),
901 /// `#x in obj`
902 PrivateIn {
903 /// Private name.
904 name: Ident,
905 /// Tested object.
906 object: Box<Expr>,
907 },
908}
909
910/// One element of an array literal.
911#[derive(Debug, Clone, PartialEq)]
912pub enum ArrayElement {
913 /// An ordinary element.
914 Expr(Box<Expr>),
915 /// `...iterable`
916 Spread(Box<Expr>),
917}
918
919/// What an object-literal property does with its value.
920///
921/// Distinct from [`MethodKind`] on purpose: an object literal can never contain a
922/// `constructor`, and the compiler needs to tell `{a: 1}` from `{a() {}}` — the two
923/// compile to different instructions (`define_field` vs `define_method`), even though
924/// both hold a value on the stack.
925#[derive(Debug, Clone, Copy, PartialEq, Eq)]
926pub enum PropertyKind {
927 /// `key: value` or the `{key}` shorthand — stores a data property.
928 Value,
929 /// `m() {}` — defines a method.
930 Method,
931 /// `get m() {}` — the value is the getter.
932 Get,
933 /// `set m(v) {}` — the value is the setter.
934 Set,
935}
936
937/// One property of an object literal.
938#[derive(Debug, Clone, PartialEq)]
939pub enum ObjectProperty {
940 /// `key: value`, `key`, `get key() {}`, `[key]: value`, …
941 Property {
942 /// Property key.
943 key: PropName,
944 /// Value expression; for `get`/`set` it is the function.
945 value: Box<Expr>,
946 /// Whether this stores a value or defines an accessor/method.
947 kind: PropertyKind,
948 /// Whether the source used shorthand (`{a}` / `{a = 1}`).
949 shorthand: bool,
950 /// Source range.
951 span: Span,
952 },
953 /// `...spread`
954 Spread(Box<Expr>),
955}
956
957/// A template literal: `quasis.len() == expressions.len() + 1`.
958#[derive(Debug, Clone, PartialEq)]
959pub struct TemplateLiteral {
960 /// Literal chunks, in source order.
961 pub quasis: Vec<TemplateChunk>,
962 /// Substitution expressions, in source order.
963 pub expressions: Vec<Expr>,
964}
965
966/// One chunk of a [`TemplateLiteral`].
967#[derive(Debug, Clone, PartialEq, Eq)]
968pub struct TemplateChunk {
969 /// Escape-expanded text; `None` when the chunk has an invalid escape
970 /// sequence (legal in tagged templates only, where it becomes `undefined`).
971 ///
972 /// A [`Wtf8`] because a template may hold an unpaired surrogate, just as a string
973 /// literal may.
974 pub cooked: Option<Wtf8>,
975 /// Source text, verbatim.
976 pub raw: String,
977 /// Whether this chunk ends with the closing backtick.
978 pub tail: bool,
979}
980
981/// Property selector of a member expression.
982#[derive(Debug, Clone, PartialEq)]
983pub enum MemberProp {
984 /// `.name`
985 Ident(Ident),
986 /// `[expr]`
987 Computed(Box<Expr>),
988 /// `.#name`
989 Private(Ident),
990}
991
992/// Unary operators.
993#[derive(Debug, Clone, Copy, PartialEq, Eq)]
994pub enum UnaryOp {
995 /// `-`
996 Minus,
997 /// `+`
998 Plus,
999 /// `!`
1000 Not,
1001 /// `~`
1002 BitNot,
1003 /// `typeof`
1004 Typeof,
1005 /// `void`
1006 Void,
1007 /// `delete`
1008 Delete,
1009}
1010
1011impl UnaryOp {
1012 /// The operator text.
1013 pub fn as_str(self) -> &'static str {
1014 match self {
1015 UnaryOp::Minus => "-",
1016 UnaryOp::Plus => "+",
1017 UnaryOp::Not => "!",
1018 UnaryOp::BitNot => "~",
1019 UnaryOp::Typeof => "typeof",
1020 UnaryOp::Void => "void",
1021 UnaryOp::Delete => "delete",
1022 }
1023 }
1024}
1025
1026/// `++`/`--`.
1027#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1028pub enum UpdateOp {
1029 /// `++`
1030 Increment,
1031 /// `--`
1032 Decrement,
1033}
1034
1035impl UpdateOp {
1036 /// The operator text.
1037 pub fn as_str(self) -> &'static str {
1038 match self {
1039 UpdateOp::Increment => "++",
1040 UpdateOp::Decrement => "--",
1041 }
1042 }
1043}
1044
1045/// Non-short-circuiting binary operators.
1046#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1047pub enum BinaryOp {
1048 /// `==`
1049 Eq,
1050 /// `!=`
1051 NotEq,
1052 /// `===`
1053 StrictEq,
1054 /// `!==`
1055 StrictNotEq,
1056 /// `<`
1057 Lt,
1058 /// `<=`
1059 LtEq,
1060 /// `>`
1061 Gt,
1062 /// `>=`
1063 GtEq,
1064 /// `<<`
1065 Shl,
1066 /// `>>`
1067 Shr,
1068 /// `>>>`
1069 UShr,
1070 /// `+`
1071 Add,
1072 /// `-`
1073 Sub,
1074 /// `*`
1075 Mul,
1076 /// `/`
1077 Div,
1078 /// `%`
1079 Mod,
1080 /// `**`
1081 Pow,
1082 /// `|`
1083 BitOr,
1084 /// `^`
1085 BitXor,
1086 /// `&`
1087 BitAnd,
1088 /// `in`
1089 In,
1090 /// `instanceof`
1091 Instanceof,
1092}
1093
1094impl BinaryOp {
1095 /// The operator text.
1096 pub fn as_str(self) -> &'static str {
1097 match self {
1098 BinaryOp::Eq => "==",
1099 BinaryOp::NotEq => "!=",
1100 BinaryOp::StrictEq => "===",
1101 BinaryOp::StrictNotEq => "!==",
1102 BinaryOp::Lt => "<",
1103 BinaryOp::LtEq => "<=",
1104 BinaryOp::Gt => ">",
1105 BinaryOp::GtEq => ">=",
1106 BinaryOp::Shl => "<<",
1107 BinaryOp::Shr => ">>",
1108 BinaryOp::UShr => ">>>",
1109 BinaryOp::Add => "+",
1110 BinaryOp::Sub => "-",
1111 BinaryOp::Mul => "*",
1112 BinaryOp::Div => "/",
1113 BinaryOp::Mod => "%",
1114 BinaryOp::Pow => "**",
1115 BinaryOp::BitOr => "|",
1116 BinaryOp::BitXor => "^",
1117 BinaryOp::BitAnd => "&",
1118 BinaryOp::In => "in",
1119 BinaryOp::Instanceof => "instanceof",
1120 }
1121 }
1122
1123 /// Whether the operator is relational (`in`/`instanceof` included), which
1124 /// matters for the `no-in` restriction in `for` heads.
1125 pub fn is_relational(self) -> bool {
1126 matches!(
1127 self,
1128 BinaryOp::Lt
1129 | BinaryOp::LtEq
1130 | BinaryOp::Gt
1131 | BinaryOp::GtEq
1132 | BinaryOp::In
1133 | BinaryOp::Instanceof
1134 )
1135 }
1136}
1137
1138/// Short-circuiting operators.
1139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1140pub enum LogicalOp {
1141 /// `&&`
1142 And,
1143 /// `||`
1144 Or,
1145 /// `??`
1146 Coalesce,
1147}
1148
1149impl LogicalOp {
1150 /// The operator text.
1151 pub fn as_str(self) -> &'static str {
1152 match self {
1153 LogicalOp::And => "&&",
1154 LogicalOp::Or => "||",
1155 LogicalOp::Coalesce => "??",
1156 }
1157 }
1158}
1159
1160/// Assignment operators.
1161#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1162pub enum AssignOp {
1163 /// `=`
1164 Assign,
1165 /// `+=`
1166 Add,
1167 /// `-=`
1168 Sub,
1169 /// `*=`
1170 Mul,
1171 /// `/=`
1172 Div,
1173 /// `%=`
1174 Mod,
1175 /// `**=`
1176 Pow,
1177 /// `<<=`
1178 Shl,
1179 /// `>>=`
1180 Shr,
1181 /// `>>>=`
1182 UShr,
1183 /// `|=`
1184 BitOr,
1185 /// `^=`
1186 BitXor,
1187 /// `&=`
1188 BitAnd,
1189 /// `&&=`
1190 And,
1191 /// `||=`
1192 Or,
1193 /// `??=`
1194 Coalesce,
1195}
1196
1197impl AssignOp {
1198 /// The operator text.
1199 pub fn as_str(self) -> &'static str {
1200 match self {
1201 AssignOp::Assign => "=",
1202 AssignOp::Add => "+=",
1203 AssignOp::Sub => "-=",
1204 AssignOp::Mul => "*=",
1205 AssignOp::Div => "/=",
1206 AssignOp::Mod => "%=",
1207 AssignOp::Pow => "**=",
1208 AssignOp::Shl => "<<=",
1209 AssignOp::Shr => ">>=",
1210 AssignOp::UShr => ">>>=",
1211 AssignOp::BitOr => "|=",
1212 AssignOp::BitXor => "^=",
1213 AssignOp::BitAnd => "&=",
1214 AssignOp::And => "&&=",
1215 AssignOp::Or => "||=",
1216 AssignOp::Coalesce => "??=",
1217 }
1218 }
1219
1220 /// Whether this is a simple `=`.
1221 pub fn is_simple(self) -> bool {
1222 matches!(self, AssignOp::Assign)
1223 }
1224
1225 /// The binary operator a compound assignment implies.
1226 pub fn binary_op(self) -> Option<BinaryOp> {
1227 Some(match self {
1228 AssignOp::Assign => return None,
1229 AssignOp::Add => BinaryOp::Add,
1230 AssignOp::Sub => BinaryOp::Sub,
1231 AssignOp::Mul => BinaryOp::Mul,
1232 AssignOp::Div => BinaryOp::Div,
1233 AssignOp::Mod => BinaryOp::Mod,
1234 AssignOp::Pow => BinaryOp::Pow,
1235 AssignOp::Shl => BinaryOp::Shl,
1236 AssignOp::Shr => BinaryOp::Shr,
1237 AssignOp::UShr => BinaryOp::UShr,
1238 AssignOp::BitOr => BinaryOp::BitOr,
1239 AssignOp::BitXor => BinaryOp::BitXor,
1240 AssignOp::BitAnd => BinaryOp::BitAnd,
1241 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => return None,
1242 })
1243 }
1244
1245 /// The logical operator a short-circuiting assignment implies.
1246 pub fn logical_op(self) -> Option<LogicalOp> {
1247 match self {
1248 AssignOp::And => Some(LogicalOp::And),
1249 AssignOp::Or => Some(LogicalOp::Or),
1250 AssignOp::Coalesce => Some(LogicalOp::Coalesce),
1251 _ => None,
1252 }
1253 }
1254
1255 /// Map a punctuator to an assignment operator.
1256 pub fn from_punct(p: Punct) -> Option<AssignOp> {
1257 Some(match p {
1258 Punct::Eq => AssignOp::Assign,
1259 Punct::PlusEq => AssignOp::Add,
1260 Punct::MinusEq => AssignOp::Sub,
1261 Punct::StarEq => AssignOp::Mul,
1262 Punct::SlashEq => AssignOp::Div,
1263 Punct::PercentEq => AssignOp::Mod,
1264 Punct::StarStarEq => AssignOp::Pow,
1265 Punct::ShlEq => AssignOp::Shl,
1266 Punct::ShrEq => AssignOp::Shr,
1267 Punct::UShrEq => AssignOp::UShr,
1268 Punct::PipeEq => AssignOp::BitOr,
1269 Punct::CaretEq => AssignOp::BitXor,
1270 Punct::AmpEq => AssignOp::BitAnd,
1271 Punct::AmpAmpEq => AssignOp::And,
1272 Punct::PipePipeEq => AssignOp::Or,
1273 Punct::QuestionQuestionEq => AssignOp::Coalesce,
1274 _ => return None,
1275 })
1276 }
1277}
1278
1279// ---------------------------------------------------------------------------
1280// Modules
1281// ---------------------------------------------------------------------------
1282
1283/// The name on either side of a module binding, which may be a string.
1284#[derive(Debug, Clone, PartialEq, Eq)]
1285pub enum ModuleName {
1286 /// `foo`
1287 Ident(Ident),
1288 /// `"foo bar"`
1289 ///
1290 /// A `String`, unlike every other cooked string in this tree: a module specifier names
1291 /// a file, so it has to reach the loader as `&str`, and a path cannot contain a lone
1292 /// surrogate. The parser converts with `to_string_lossy` when it builds one, which is
1293 /// also what a filesystem would do with it.
1294 Str(String),
1295}
1296
1297impl ModuleName {
1298 /// The textual name.
1299 pub fn as_str(&self) -> &str {
1300 match self {
1301 ModuleName::Ident(id) => &id.name,
1302 ModuleName::Str(s) => s,
1303 }
1304 }
1305}
1306
1307/// `import …`
1308#[derive(Debug, Clone, PartialEq)]
1309pub struct ImportDecl {
1310 /// What is imported.
1311 pub specifiers: Vec<ImportSpecifier>,
1312 /// Module specifier string.
1313 pub source: String,
1314 /// `with { type: "json" }` attributes.
1315 pub attributes: Vec<ImportAttribute>,
1316 /// Source range.
1317 pub span: Span,
1318}
1319
1320/// One entry of an import clause.
1321#[derive(Debug, Clone, PartialEq)]
1322pub enum ImportSpecifier {
1323 /// `import d from "m"`
1324 Default(Ident),
1325 /// `import * as ns from "m"`
1326 Namespace(Ident),
1327 /// `import { a, b as c } from "m"`
1328 Named {
1329 /// Name in the exporting module.
1330 imported: ModuleName,
1331 /// Local binding.
1332 local: Ident,
1333 },
1334}
1335
1336/// `with { key: "value" }`
1337#[derive(Debug, Clone, PartialEq)]
1338pub struct ImportAttribute {
1339 /// Attribute key.
1340 pub key: String,
1341 /// Attribute value.
1342 pub value: String,
1343 /// Source range.
1344 pub span: Span,
1345}
1346
1347/// `export …`
1348#[derive(Debug, Clone, PartialEq)]
1349pub struct ExportDecl {
1350 /// What is exported.
1351 pub kind: ExportKind,
1352 /// Source range.
1353 pub span: Span,
1354}
1355
1356/// The variants of an export declaration.
1357#[derive(Debug, Clone, PartialEq)]
1358pub enum ExportKind {
1359 /// `export var/let/const/function/class …`
1360 Declaration(Box<Stmt>),
1361 /// `export default expr` / `export default function …` / `export default class …`
1362 Default(Box<Expr>),
1363 /// `export { a, b as c }` / `export { a } from "m"`
1364 Named {
1365 /// Exported bindings.
1366 specifiers: Vec<ExportSpecifier>,
1367 /// Re-export source.
1368 source: Option<String>,
1369 /// Import attributes for the `from` clause.
1370 attributes: Vec<ImportAttribute>,
1371 },
1372 /// `export * from "m"` / `export * as ns from "m"`
1373 All {
1374 /// Re-export source.
1375 source: String,
1376 /// `as ns`, when present.
1377 exported: Option<ModuleName>,
1378 /// Import attributes for the `from` clause.
1379 attributes: Vec<ImportAttribute>,
1380 },
1381}
1382
1383/// One entry of an `export { … }` clause.
1384#[derive(Debug, Clone, PartialEq)]
1385pub struct ExportSpecifier {
1386 /// Local name (or the name in the source module).
1387 pub local: ModuleName,
1388 /// Exported name.
1389 pub exported: ModuleName,
1390 /// Source range.
1391 pub span: Span,
1392}