js_compile/compiler.rs
1//! The bytecode compiler.
2//!
3//! Compilation is a single walk over the AST that emits *symbolic* instructions
4//! (jump targets are label ids, variable references are names), followed by a
5//! resolution pass that turns them into final bytecode. Splitting it this way
6//! keeps the emitter readable: nothing has to know slot indices or byte offsets
7//! while it is still discovering them.
8//!
9//! Variable resolution follows the reference implementation's model:
10//!
11//! * every function has a flat table of arguments and locals;
12//! * block scopes form a chain through [`VarDef::scope_next`], which is what makes
13//! `let`/`const` bindings visible only inside their block and lets the runtime
14//! put them back into the temporal dead zone on entry;
15//! * a name that is not in the current function is looked up in the enclosing
16//! ones; if found, the variable is marked captured and reached through a
17//! closure reference;
18//! * a name found nowhere is a global, reached through a closure entry as well.
19//!
20//! Emission order and instruction choice deliberately mirror `quickjs.c`: the
21//! differential test compares disassembly with the reference opcode by opcode, so
22//! an unnecessary `dup` or a differently chosen short form shows up immediately.
23
24use crate::bytecode::LineCol;
25use crate::bytecode::{
26 ANONYMOUS_BINDING, Atom, ClosureType, ClosureVar, Constant, EvalPrivate, EvalPrivateKind,
27 EvalSite, EvalVisible, ExportEntry, Function as CompiledFunction, FunctionKind, ImportEntry,
28 ModuleMeta, ModuleRequest, VarDef, VarKind,
29};
30use crate::disasm;
31use crate::opcode::Opcode;
32use js_parse::Position;
33use js_parse::Span;
34use js_parse::SyntaxError;
35use js_parse::Wtf8;
36use js_parse::ast::{self, *};
37
38/// A label id, local to the function being compiled.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub struct Label(u32);
41
42/// The name of the hidden local that carries a function's `[[HomeObject]]` for `super`.
43///
44/// The reference calls the variable `home_object` and prints it as `"<home_object>"`, which
45/// is why the brackets are part of the name; nothing a program writes can collide with it.
46const HOME_OBJECT: &str = "<home_object>";
47
48/// The local holding the function `super()` constructs from.
49///
50/// The reference's `JS_ATOM_this_active_func`. Unlike `<home_object>` this one is printed
51/// with its dots, because that is the atom's text: its dump shows `1: var this.active_func`.
52const ACTIVE_FUNC: &str = "this.active_func";
53
54/// The local holding `new.target`, likewise spelled the way the reference's dump shows it.
55const NEW_TARGET: &str = "new.target";
56
57/// Stand-in for a constant-pool index that is only known later in the instruction stream.
58///
59/// One user: the class constructor's `fclosure`, whose slot the reference assigns after the
60/// members have taken theirs. `u32::MAX` is not a reachable pool index — a class with four
61/// billion members is not a thing — and the compiler patches it before resolution runs, so a
62/// missed patch is a panic-free compiler error rather than a wrong jump.
63const CTOR_INDEX_PLACEHOLDER: u32 = u32::MAX;
64
65/// One step of a class's initialisation, in source order.
66///
67/// A static block is not a member the class keeps — it is a run of statements that executes
68/// at the point the class definition reaches it — so it belongs *inside* the initialiser
69/// function rather than alongside the fields as a separate pass. Merging the two is what
70/// makes `static a = 1; static {}` and `static {}; static a = 1` order-sensitive in the
71/// same way the reference is.
72enum StaticInitItem<'a> {
73 /// `static x = value`, or `x = value` for the instance half.
74 Field(FieldKey<'a>, Option<&'a Expr>),
75 /// `static { … }`
76 Block {
77 body: &'a [Stmt],
78 /// Position of the `{`, which is where the reference puts the function.
79 body_start: Position,
80 },
81}
82
83/// How one field names its property.
84///
85/// A computed key is *not* re-evaluated per instance: the reference evaluates it once at
86/// class definition and stores it in a `<computed_field>N` binding, because the key of a field
87/// is fixed when the class is created. Keeping the expression here instead made
88/// `class C { [k] = 1 }` re-read `k` on every `new`, which is a different program when `k`
89/// changes — and worse, the operand order was wrong, so `class C { ["a"] = 1 }` produced
90/// `{1: "a"}`.
91enum FieldKey<'a> {
92 /// `x`, `"x"`, `0` — the property name is static text.
93 Literal(&'a PropKey),
94 /// `#x`: the class-scope binding that holds the private symbol.
95 Private(String),
96 /// `[expr]`: the class-scope binding that holds the evaluated key.
97 Computed(String),
98}
99
100/// The `var_block` sentinel for a binding that lives at function scope.
101///
102/// It has to be a value a *real* block key can never take. Block keys are source
103/// offsets, so `0` is a perfectly ordinary key — the first block statement of a file
104/// gets it — and using `0` as the sentinel made `{ let y = 2 }` at offset zero look
105/// like a function-scoped `var`, which is how a top-level block's `let` leaked out of
106/// its block. The body block already uses `u64::MAX` to stay clear of offsets, so the
107/// sentinel takes the slot below it.
108const FUNCTION_SCOPE: u64 = u64::MAX - 3;
109
110/// The `var_block` sentinel for a binding of the parameter list.
111///
112/// A function whose parameter list contains a default expression gets *two* variable
113/// environments: one for the parameters and one for the body, so a `var` in the body
114/// that shares a name with a parameter is a different binding. The parameter bindings
115/// therefore need a scope key of their own: reachable while the defaults are
116/// evaluated, invisible to the body, and never merged with a body `var` of the same
117/// name.
118///
119/// Without this, `function f(a = 1, p = () => a) { var a = 2 }` made `p()` return 2:
120/// the closure and the body shared one slot, when only the parameters were in scope
121/// when it was created.
122const PARAM_SCOPE: u64 = u64::MAX - 4;
123
124/// The name of the hidden local a `using` declaration caches its dispose method in.
125///
126/// It has to be a name no source can produce, because a script may declare anything: the
127/// angle brackets keep it out of the identifier grammar, exactly like `<ret>`.
128fn using_method_name(name: &str) -> String {
129 format!("<using.method {name}>")
130}
131
132/// The `blocks` parent sentinel for "this block has no enclosing block".
133///
134/// Same reasoning as [`FUNCTION_SCOPE`]: `0` is a legal block key, and when it was
135/// also the terminator the chain walk from the script body reached the file's
136/// offset-zero block and treated it as an *enclosing* block — so that block's `let`
137/// leaked into the body scope.
138const NO_PARENT: u64 = u64::MAX - 2;
139
140/// The block key for a script body. Distinct from both sentinels and unreachable from
141/// any source offset.
142const SCRIPT_BODY: u64 = u64::MAX - 1;
143
144/// An operand of a symbolic instruction.
145#[derive(Debug, Clone, PartialEq)]
146enum Op {
147 /// An immediate integer.
148 Int(i32),
149 /// A jump target.
150 Label(Label),
151 /// A constant pool index.
152 Const(u32),
153 /// An atom, before interning.
154 Atom(Atom),
155 /// An interned atom, as an index into [`Function::atoms`].
156 AtomId(u32),
157 /// A resolved slot.
158 Slot(Slot),
159}
160
161/// Where a resolved variable lives.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163enum Slot {
164 Arg(u32),
165 Loc(u32),
166 VarRef(u32),
167 /// A global, by closure-var index.
168 Global(u32),
169 /// A global *declared* in this script. The reference keeps these bindings in
170 /// reference cells so that the script and any closure share one variable, so
171 /// a store goes through `put_var_ref` while a read uses `get_var`.
172 GlobalDecl(u32),
173}
174
175/// What a symbolic variable access does, which decides the final opcode.
176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177enum VarAction {
178 /// Read the value.
179 Get,
180 /// Read the value, yielding `undefined` for an undeclared global.
181 GetUndef,
182 /// Write, leaving nothing on the stack.
183 Put,
184 /// Write and initialise, leaving the value on the stack.
185 PutInit,
186 /// Write, leaving the value on the stack.
187 Set,
188 /// Initialise a binding that may only be initialised once, such as a derived
189 /// constructor's `this`.
190 PutInitChecked,
191 /// Initialise, leaving the value on the stack and without the `const` check.
192 ///
193 /// A class's own scope binding is a `const` that has to be initialised in the middle
194 /// of the definition — after the constructor exists but before the static fields run
195 /// — and the value has to survive for the outer store to use.
196 SetInit,
197 /// Write a binding that lives in a reference cell.
198 PutRef,
199}
200
201#[derive(Debug, Clone)]
202enum Insn {
203 /// A fully determined instruction.
204 Fixed { op: Opcode, operands: Vec<Op> },
205 /// A variable access, resolved in the second pass.
206 ///
207 /// `block` is the lexical block the access appears in, which is what makes
208 /// shadowing work: two bindings can share a name, and the one that wins is
209 /// whichever scope encloses the access.
210 Var {
211 action: VarAction,
212 name: String,
213 block: u64,
214 /// Whether the access was written in the parameter list; see
215 /// [`FnState::in_params`].
216 in_params: bool,
217 },
218 /// Close a binding *if* it turned out to be captured.
219 ///
220 /// Whether a `for (let i ...)` loop variable needs a fresh per-iteration cell is
221 /// only known once the body has been compiled — a closure created there is the
222 /// thing that makes it necessary. The reference emits `close_loc` exactly in that
223 /// case and nothing otherwise, so the decision is deferred to [`resolve`] instead
224 /// of emitted blind.
225 CloseCaptured { name: String, block: u64 },
226 /// `delete name`, which can only answer `false` once the binding is known.
227 ///
228 /// It is not a `Var` action because `delete_var` carries an *atom*: the runtime
229 /// looks the name up on the global object, which is what distinguishes an implicit
230 /// global (configurable, deletable) from a declared one (a binding, always `false`).
231 DeleteVar { name: String },
232 /// An instruction that dead-code elimination removed. It keeps its slot so
233 /// that label indices stay valid, and resolves to no bytecode.
234 Dead,
235}
236
237/// Where `break` and `continue` jump to.
238///
239/// Targets are stacked as the compiler enters loops and labelled statements, so a
240/// bare `break` needs no analysis: it is simply the innermost target. A labelled
241/// one searches outward by name.
242#[derive(Debug, Clone)]
243struct JumpTarget {
244 /// The labels attached to this target. `l: for(;;)` gives one name; a bare
245 /// loop gives none; `a: b: for(;;)` gives two, because both labels name the
246 /// same statement and `break a` must reach the same place as `break b`.
247 names: Vec<String>,
248 /// Where `break` lands. `None` for a construct `break` may only leave, not
249 /// target — a `try`, whose entry exists purely to unwind.
250 break_label: Option<Label>,
251 /// Where `continue` lands. `None` for anything that is not a loop.
252 continue_label: Option<Label>,
253 /// Stack slots to discard when control leaves this construct by a jump.
254 ///
255 /// Both `switch` and `try` leave something on the value stack for the duration
256 /// of the construct — the discriminant, or the `catch` offset — and a jump out
257 /// has to take it with it. A loop leaves nothing.
258 drop_count: u32,
259 /// The finalizer to run when control leaves this construct.
260 ///
261 /// Set on a `try` even when it has no `finally`: the label is always emitted and
262 /// the empty-subroutine removal cleans up afterwards, so the code that unwinds
263 /// does not have to know whether a finalizer exists.
264 finally_label: Option<Label>,
265 /// Whether this is a labelled non-loop statement, which an unlabelled `break`
266 /// does not reach.
267 is_regular_stmt: bool,
268 /// Whether leaving this construct has to close an iterator.
269 ///
270 /// A `for`/`of` loop keeps an iterator on the value stack, and leaving early has
271 /// to run its `return` method. `for`/`in` keeps only an enumeration object, which
272 /// is dropped rather than closed.
273 has_iterator: bool,
274 /// Whether that iterator speaks the *async* protocol.
275 ///
276 /// An async close has to `await` the inner `return`, so it is an inline instruction
277 /// sequence rather than one opcode — the reference's `emit_iterator_close`.
278 is_async_iterator: bool,
279}
280
281/// Whether a named property read should be `get_field2` rather than `dup; get_field`.
282///
283/// Both leave `source value` on the stack, so this is purely which spelling the reference
284/// picked, and it picked it by whether it had to build a *reference* for the target:
285///
286/// * a target that is itself a pattern starts by boxing the value, so the copy is what it
287/// consumes — `get_field2` (and a default does not change that: `{a: {b} = {}}` still
288/// destructures);
289/// * a `let`/`const` binding needs no reference, so the reference takes the short form;
290/// * a `var`, and any assignment target, go through `dup; get_field`, because the
291/// reference builds a reference for them — which is what `with` needs.
292fn reads_with_get_field2(decl: Option<VarDeclKind>, value: &Pattern) -> bool {
293 nests_a_pattern(value) || matches!(decl, Some(VarDeclKind::Let) | Some(VarDeclKind::Const))
294}
295
296/// Whether binding this pattern starts by boxing the value it was handed.
297fn nests_a_pattern(pattern: &Pattern) -> bool {
298 match &pattern.kind {
299 PatternKind::Array { .. } | PatternKind::Object { .. } => true,
300 PatternKind::Assign { target, .. } => nests_a_pattern(target),
301 _ => false,
302 }
303}
304
305/// `copy_data_properties` flags for an object-literal spread.
306///
307/// The byte packs three fields: the low bits are the stack offset of the source,
308/// the next three the offset of the exclusion list, and bit 2 asks for symbol keys
309/// as well as string keys. A spread passes a literal `null` exclusion list right
310/// below the source, so that field stays zero and only the source offset and the
311/// symbol bit are set — hence `{...v}` copies symbols, which the flag name says.
312const COPY_ALL_PROPERTIES: i32 = 2 | (1 << 2);
313
314/// The expression a `...` introduces.
315///
316/// The parser marks the spread in two places — the element/property variant and an
317/// [`ExprKind::Spread`] wrapper around the argument — so the wrapper has to be
318/// stepped through before the argument can be compiled.
319fn spread_argument(spread: &Expr) -> &Expr {
320 match &spread.kind {
321 ExprKind::Spread(inner) => inner,
322 _ => spread,
323 }
324}
325
326/// The flag byte `define_method` takes.
327///
328/// The low two bits pick value/getter/setter; bit 2 marks the property
329/// enumerable, which every object-literal method is.
330/// What kind of class constructor a function is being compiled as.
331///
332/// A constructor is not an ordinary method: a base one materialises `this` and refuses
333/// to run without `new`, and a derived one starts with `this` in the dead zone until
334/// `super()` produces it.
335#[derive(Debug, Clone, Copy, PartialEq, Eq)]
336enum CtorKind {
337 /// Not a class constructor.
338 None,
339 /// A constructor of a class without `extends`.
340 Base,
341 /// A constructor of a class with `extends`.
342 Derived,
343}
344
345/// The flag byte `define_method` takes for a class member.
346///
347/// The low two bits pick value/getter/setter; bit 2 marks the property enumerable, which
348/// a class method is *not* — that is the whole difference from an object-literal method,
349/// and the reason `Object.keys(C.prototype)` stays empty.
350fn class_method_flags(kind: MethodKind) -> i32 {
351 match kind {
352 MethodKind::Constructor | MethodKind::Method => 0,
353 MethodKind::Get => 1,
354 MethodKind::Set => 2,
355 }
356}
357
358fn define_method_flags(kind: PropertyKind) -> i32 {
359 let base = match kind {
360 PropertyKind::Value | PropertyKind::Method => 0,
361 PropertyKind::Get => 1,
362 PropertyKind::Set => 2,
363 };
364 base | 4
365}
366
367/// Convert a numeric property key to the text an atom would be made from.
368///
369/// Only the range where Rust and JavaScript agree on the spelling is accepted.
370/// Both print the shortest representation that round-trips, so plain decimal
371/// digits match; they diverge at the extremes, where JavaScript switches to an
372/// exponent (`1e-7`, `1e+21`) and Rust does not. Rather than emit an atom that
373/// differs from the reference, those keys are rejected.
374fn numeric_key_text(value: f64, span: Span) -> Result<String, SyntaxError> {
375 if !value.is_finite() {
376 return Err(SyntaxError::new(
377 "a non-finite numeric property key is not supported by the compiler yet",
378 span,
379 ));
380 }
381 if value == value.trunc() && value.abs() < 1e21 {
382 return Ok(format!("{}", value as i64));
383 }
384 if value.abs() >= 1e-6 && value.abs() < 1e21 {
385 return Ok(format!("{value}"));
386 }
387 Err(SyntaxError::new(
388 "a numeric property key outside [1e-6, 1e21) is not supported by the compiler yet",
389 span,
390 ))
391}
392
393/// Collect the operands of a same-operator logical run, in source order.
394///
395/// Recurses down the left spine only: `((a || b) || c)` contributes `a`, `b`, then
396/// the caller appends `c`. A node with a different operator is one operand.
397fn collect_same_operator<'a>(op: LogicalOp, expr: &'a Expr, out: &mut Vec<&'a Expr>) {
398 if let ExprKind::Logical {
399 op: inner_op,
400 left,
401 right,
402 } = &expr.kind
403 && *inner_op == op
404 {
405 collect_same_operator(op, left, out);
406 out.push(right);
407 return;
408 }
409 out.push(expr);
410}
411
412/// The jump a logical assignment or `??` takes when the value is kept.
413///
414/// `||` and `&&` branch on truthiness, so the same opcode serves both the operator
415/// and `??` once [`Compiler::emit_logical_test`] has pushed a boolean. `??` keeps
416/// the value when it is *not* null-ish, so it is the `if_false` side.
417fn logical_jump(op: AssignOp) -> Opcode {
418 match op {
419 AssignOp::Or => Opcode::IfTrue,
420 AssignOp::And | AssignOp::Coalesce => Opcode::IfFalse,
421 _ => Opcode::IfFalse,
422 }
423}
424
425/// Whether a loop enumerates keys or values.
426#[derive(Debug, Clone, Copy, PartialEq, Eq)]
427enum ForLoopKind {
428 /// `for (x in o)` — the keys of an object.
429 In,
430 /// `for (x of o)` — the values of an iterable.
431 Of,
432 /// `for await (x of o)` — the values of an async iterable, or of a sync one.
433 AwaitOf,
434}
435
436/// Which part of a `try` statement a block key refers to.
437#[derive(Debug, Clone, Copy)]
438enum TryPart {
439 /// The guarded block.
440 Block = 0,
441 /// The handler body, excluding the catch parameter.
442 Catch = 1,
443 /// The finalizer block.
444 Finally = 2,
445 /// The catch parameter's own scope.
446 Param = 3,
447}
448
449/// A lexical scope, identified while hoisting and numbered at the end.
450///
451/// Scope identity is needed in two passes that must agree: declarations are
452/// hoisted in source order (so slots come out in source order, as in the
453/// reference), but a binding belongs to the block it was written in, which is only
454/// entered later. Blocks are therefore keyed by the source position of their
455/// opening brace, which is stable across both walks.
456#[derive(Debug, Clone, Copy)]
457struct Block {
458 /// Source position of the block.
459 key: u64,
460 /// The block this one is nested in; `0` for the function scope.
461 parent: u64,
462}
463
464/// One function under construction.
465struct FnState {
466 /// The function's own source range, used to record its text for
467 /// `Function.prototype.toString`.
468 span: Option<(usize, usize)>,
469 name: String,
470 kind: FunctionKind,
471 strict: bool,
472 args: Vec<VarDef>,
473 vars: Vec<VarDef>,
474 closure_vars: Vec<ClosureVar>,
475 cpool: Vec<Constant>,
476 atoms: Vec<Atom>,
477 /// Every lexical scope, in creation order.
478 blocks: Vec<Block>,
479 /// The block currently being parsed or compiled.
480 current_block: u64,
481 /// The block a *nested* function was created in, so a capture made from here can be
482 /// resolved against the enclosing function's lexical scopes rather than against a
483 /// flat name table. Without it, `function f(){ class S{} }` capturing `S` found the
484 /// function's own `let S` instead of the class body's `const S`.
485 created_in_block: u64,
486 /// The block each local was declared in, parallel to `vars`. `0` means the
487 /// function scope, where `var` bindings live.
488 var_block: Vec<u64>,
489 /// Set when the expression just compiled left no value on the stack.
490 ///
491 /// Only a store can do that: `put_field` consumes the object and the value, so
492 /// an assignment whose result is unused emits nothing extra. The expression
493 /// statement then has nothing to drop.
494 no_value: bool,
495 /// Whether a label was placed since the last instruction was emitted.
496 ///
497 /// The `put`/`get` fold is only valid when the two are adjacent in the final
498 /// stream; a label in between means a jump can land on the read, so the store has
499 /// to keep consuming its value. A flag is enough and avoids having to reason about
500 /// which index a label recorded.
501 label_since_insn: bool,
502 /// Whether the value of the expression being compiled is thrown away.
503 ///
504 /// Only an expression *statement* discards its value, and only the outermost
505 /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
506 /// still has to produce a value. Consumed by [`Compiler::assign`], which is
507 /// the one construct whose bytecode depends on it.
508 discard_value: bool,
509 /// The block that holds the function body.
510 body_block: u64,
511 /// Head of each scope's binding chain, indexed by level. Filled in by
512 /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
513 block_heads: Vec<i32>,
514 /// Enclosing `break`/`continue` targets, innermost last.
515 jump_targets: Vec<JumpTarget>,
516 insns: Vec<Insn>,
517 labels: Vec<Option<usize>>,
518 /// Captured locals, which need a reference cell.
519 var_ref_count: u32,
520 line: u32,
521 column: u32,
522 /// Whether this is a script body. A script's top-level declarations create
523 /// global properties rather than locals, which is why they show up as
524 /// closure variables with `[global_decl]`.
525 is_script: bool,
526 /// Whether this is a module body.
527 ///
528 /// A module body is a script in every respect that matters here — no `arguments`,
529 /// no `this` of its own — but its top-level declarations are *module*-scoped
530 /// instead of global, which is what this flag changes.
531 is_module: bool,
532 /// Whether the function is an arrow, which never gets its own `arguments`.
533 is_arrow: bool,
534 /// The name a *named function expression* binds inside its own body.
535 /// How many parameters count towards `.length`.
536 defined_args: u32,
537 /// Parameters that are not a plain name, with the argument slot each came from.
538 param_prologue: Vec<(usize, Pattern)>,
539 /// What kind of class constructor this function is, if any.
540 ctor_kind: CtorKind,
541 /// Whether the class has instance fields, so the constructor has to run their
542 /// initialiser before it returns.
543 /// What the nested function about to be compiled should be told about its class.
544 class_ctor_pending: Option<CtorKind>,
545 /// Whether this function needs the hidden `this` local, because an arrow inside it
546 /// refers to `this`.
547 ///
548 /// An arrow has no `this` of its own, so the reference materialises the enclosing
549 /// function's receiver into a local and lets the arrow capture it as an ordinary
550 /// closure variable. Declaring the local is not enough on its own: the store that
551 /// fills it has to be prepended to the body, which is what this flag arranges.
552 needs_this_local: bool,
553 /// The same, for `arguments`.
554 needs_arguments_local: bool,
555 /// The same, for `new.target`.
556 needs_new_target_local: bool,
557 /// Whether the body already opens by filling a `this` local, which
558 /// [`Compiler::begin_this_local`] does for a constructor and a field initialiser.
559 has_this_prologue: bool,
560 /// The same, for `<home_object>`: the object `super` resolves against.
561 ///
562 /// An arrow and a static block have no home object of their own — only the method or
563 /// initialiser they were written in does — so `super.x` inside one is a read of the
564 /// enclosing function's `[[HomeObject]]`. The value is materialised into a local there
565 /// by `special_object 4`, the same way `this` is.
566 needs_home_object_local: bool,
567 /// Whether this function has an `arguments` binding of its own.
568 ///
569 /// False for a class field initialiser and a static block: §15.7 puts them outside any
570 /// function, so `arguments` does not exist there and `eval('arguments')` inside one is a
571 /// `SyntaxError` rather than the caller's arguments object. The parser already enforces
572 /// that for written code; this carries the same fact to the `eval` call site, which has
573 /// to compile the eval'd source under the caller's restriction.
574 no_arguments_binding: bool,
575 /// The same, for `this.active_func`: the function `super()` constructs from.
576 ///
577 /// An arrow has no `super` of its own, so it reads the enclosing function's — and that
578 /// is a *lexical* relationship, not a stack one. The reference keeps `this_active_func`
579 /// as a local of the enclosing function; an arrow that escaped the constructor
580 /// (`iter.return = () => super()`) then finds it in its closure even with the
581 /// constructor nowhere on the call stack.
582 needs_active_func_local: bool,
583 /// Hidden locals of the `with` blocks currently open, innermost last.
584 with_names: Vec<String>,
585 /// Set while a with-guard is being emitted, so the guard's own accesses are not
586 /// wrapped in another guard.
587 emitting_with_guard: bool,
588 self_name: Option<String>,
589 /// Where the function body starts, in source order; see [`Function::body_start`].
590 body_start: (u32, u32),
591 /// Whether the body contains a *direct* `eval(...)` call.
592 ///
593 /// A direct eval sees every binding of the function that called it, including ones
594 /// no other code mentions. It also hands those bindings to any closure it creates,
595 /// which can outlive the function. Both need the bindings to live in cells, so this
596 /// flag makes the function treat all of them as captured.
597 has_direct_eval: bool,
598 /// Whether the parameter list contains a default expression, which is what gives
599 /// the function a second variable environment (see [`PARAM_SCOPE`]).
600 has_parameter_expressions: bool,
601 /// `IsSimpleParameterList`: every parameter is a plain binding identifier.
602 simple_parameter_list: bool,
603 /// Whether the instructions being emitted belong to the parameter list.
604 ///
605 /// References made here must not see the body's `var`s: the body has not run yet,
606 /// and the reference's own model keeps the two scopes apart.
607 in_params: bool,
608 /// Whether an arrow created in this function's parameter list needs the parameter
609 /// scope's `arguments` binding.
610 needs_param_arguments: bool,
611 /// Whether this function was *created* inside a parameter list.
612 ///
613 /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
614 /// arrow too. The name reference is the arrow's, but the scope it must not see
615 /// belongs to the function the arrow was born in.
616 created_in_params: bool,
617 /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
618 ///
619 /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
620 /// final while the body is still being compiled: a named function expression declares
621 /// its own name binding *after* the body, and that binding is exactly what
622 /// `eval("myfunc = 1")` has to find.
623 eval_sites: Vec<EvalSite>,
624 /// Direct `eval` call sites seen so far: where, and the block that was current.
625 pending_eval_sites: Vec<(Span, u64, bool, Vec<EvalPrivate>, bool)>,
626 /// Whether this body contains `await`.
627 ///
628 /// For a *module* this decides whether its body is an async function: top-level
629 /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
630 /// to survive to the compiled function rather than being a local of the compiler.
631 has_await: bool,
632 /// The module tables, when this body is a module.
633 ///
634 /// Only the top-level state ever has one: `export` and `import` are top-level
635 /// statements, so nothing nested can add to these tables.
636 module: Option<ModuleMeta>,
637 /// Whether the self-name prologue (`special_object 2` then the store) has been
638 /// emitted for this function.
639 ///
640 /// A *nested* function's lookup declares the binding early (see
641 /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
642 /// prologue is still needed — the binding existing is not the same as it being
643 /// initialised.
644 self_name_initialized: bool,
645 /// Whether the code emitted so far leaves the program's result on the stack.
646 /// The reference tracks this for the hidden `<ret>` local of an eval script.
647 leaves_value: bool,
648 /// Statement nesting depth, used to tell top-level statements apart.
649 stmt_depth: u32,
650 /// Function declarations waiting to be instantiated at scope entry, as
651 /// (target slot, constant pool index). The reference emits these from
652 /// `instantiate_hoisted_definitions` rather than at the statement, because a
653 /// declaration is visible before it is reached.
654 hoisted: Vec<(u64, HoistTarget, u32)>,
655 /// Function declarations whose bodies are compiled only once the enclosing scope
656 /// has finished hoisting, as (owning block, declaration).
657 ///
658 /// Compiling a body at the declaration makes the result depend on source order: in
659 /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
660 /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
661 /// names first and the bodies second is what removes that dependence.
662 deferred_funcs: Vec<(u64, Box<ast::Function>)>,
663 /// The source position of the node being compiled. Every instruction emitted
664 /// takes it, which is how the position table that feeds stack traces is built.
665 cur_pos: Option<Position>,
666 /// One position per entry in `insns`, index-aligned.
667 insn_pos: Vec<Option<Position>>,
668}
669
670/// Where a hoisted function declaration is stored.
671#[derive(Debug, Clone)]
672enum HoistTarget {
673 Arg(u32),
674 Loc(u32),
675 /// A global, which the resolver looks up by name.
676 Global(String),
677}
678
679impl FnState {
680 /// Whether this function suspends: a generator or an async function.
681 ///
682 /// A suspending function's `return` is a `return_async` and its body starts with an
683 /// `initial_yield`, so almost every statement that touches control flow asks this.
684 fn is_suspending(&self) -> bool {
685 self.kind.is_generator() || self.kind.is_async()
686 }
687
688 fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
689 FnState {
690 span: None,
691 name: name.into(),
692 kind,
693 strict: false,
694 args: Vec::new(),
695 vars: Vec::new(),
696 closure_vars: Vec::new(),
697 cpool: Vec::new(),
698 atoms: Vec::new(),
699 blocks: Vec::new(),
700 current_block: 0,
701 created_in_block: NO_PARENT,
702 var_block: Vec::new(),
703 no_value: false,
704 label_since_insn: false,
705 discard_value: false,
706 body_block: 0,
707 block_heads: Vec::new(),
708 jump_targets: Vec::new(),
709 insns: Vec::new(),
710 labels: Vec::new(),
711 var_ref_count: 0,
712 line: 1,
713 column: 1,
714 is_script: false,
715 is_module: false,
716 is_arrow: false,
717 defined_args: 0,
718 param_prologue: Vec::new(),
719 ctor_kind: CtorKind::None,
720 class_ctor_pending: None,
721 needs_this_local: false,
722 needs_arguments_local: false,
723 needs_new_target_local: false,
724 has_this_prologue: false,
725 needs_home_object_local: false,
726 no_arguments_binding: false,
727 needs_active_func_local: false,
728 with_names: Vec::new(),
729 emitting_with_guard: false,
730 self_name: None,
731 has_direct_eval: false,
732 body_start: (0, 0),
733 has_parameter_expressions: false,
734 simple_parameter_list: true,
735 in_params: false,
736 needs_param_arguments: false,
737 created_in_params: false,
738 eval_sites: Vec::new(),
739 pending_eval_sites: Vec::new(),
740 has_await: false,
741 module: None,
742 self_name_initialized: false,
743 leaves_value: false,
744 stmt_depth: 0,
745 hoisted: Vec::new(),
746 deferred_funcs: Vec::new(),
747 cur_pos: None,
748 insn_pos: Vec::new(),
749 }
750 }
751
752 /// The scope a declaration lands in: a script's top-level declarations are
753 /// globals, everything else gets a slot.
754 /// Whether a binding declared *now* becomes a property of the global object.
755 ///
756 /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
757 /// The `var` case is decided by the keyword rather than by the cursor position:
758 /// `var` is function-scoped, so a `var i` in a `for` head is still the same
759 /// binding as a `var i` in the body, even though the head has its own block.
760 fn declares_globally(&self, def: &VarDef) -> bool {
761 // A module's top-level declarations are *module*-scoped: they live in the module
762 // record, never on the global object. Two modules can both declare `var x`
763 // without seeing each other, which is the whole point.
764 if self.is_module {
765 return false;
766 }
767 self.is_script && (!def.is_lexical || self.current_block == self.body_block)
768 }
769}
770
771/// The compiler's entry point.
772pub struct Compiler {
773 /// The text being compiled, kept so each function can record its own slice for
774 /// `Function.prototype.toString`.
775 source: Option<String>,
776 module: bool,
777 /// Whether the program itself is the body of an `async` function.
778 ///
779 /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
780 /// completion value is wrapped so a returned promise is not adopted.
781 async_body: bool,
782 /// Enclosing functions, outermost first. The last entry is the current one.
783 stack: Vec<FnState>,
784 /// The private names visible at this point, innermost class body last.
785 ///
786 /// A stack rather than a field of `FnState` because a private name is *lexically* scoped
787 /// to the class body: a method, an arrow inside it and a class nested inside that arrow
788 /// all resolve against the same entries, and the parser accepts exactly that set
789 /// (`self.private` in `parser.rs`). `FnState` is per-function, so it would lose the outer
790 /// class's names the moment a method started.
791 private_scopes: Vec<std::collections::HashMap<String, PrivateUse>>,
792 /// Whether the expression [`Compiler::expr`] is about to compile is the one its
793 /// statement asked to discard.
794 ///
795 /// `FnState::discard_value` says "the statement's value is thrown away", which is only
796 /// ever true of the statement's own expression — an assignment nested inside it, as in
797 /// `f(x = 1)`, has a value that is very much used. Clearing the flag on the way in and
798 /// keeping the answer here is what tells the two apart; without it the nested store
799 /// consumed its value, `call` took the callee as its argument, and `f(x = 1)` inside a
800 /// function threw `undefined is not a function`.
801 discard_root: bool,
802}
803
804/// How a use site of a private name compiles.
805///
806/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
807/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
808/// of a setter-only accessor pair.
809#[derive(Clone, Copy, PartialEq, Eq)]
810enum PrivateKind {
811 /// `#x = 1`: an own property keyed by the symbol in the binding.
812 Field,
813 /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
814 Method,
815 /// `get #a() {}`: the binding holds the getter, and a read calls it.
816 Getter,
817 /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
818 /// the same `TypeError` as reading an uninitialised `const`.
819 Setter,
820}
821
822/// What the compiler knows about one `#name` where it is used.
823#[derive(Clone)]
824struct PrivateUse {
825 kind: PrivateKind,
826 /// `#a<set>` when the class defines a setter for this name.
827 ///
828 /// A second binding, not a second field of the first: the reference stores the setter
829 /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
830 setter: Option<String>,
831}
832
833/// The class-scope bindings one class body needs, in declaration order.
834#[derive(Default)]
835struct ClassPlan {
836 /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
837 /// at class entry, in member order.
838 bindings: Vec<String>,
839 /// The private names, for the use sites inside the body.
840 uses: std::collections::HashMap<String, PrivateUse>,
841 /// Computed field keys, by element index, so the emission pass does not have to redo the
842 /// per-half counter that names them.
843 computed: std::collections::HashMap<usize, String>,
844 /// Whether the instance initialiser has to add the brand to `this`.
845 instance_brand: bool,
846 /// Whether the constructor itself has to carry the brand.
847 static_brand: bool,
848}
849
850impl ClassPlan {
851 /// Walk a class body once and decide every class-scope binding it needs.
852 ///
853 /// Order is the reference's: a member's binding is created when the member is parsed, so
854 /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
855 /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
856 /// the disassembly stops matching even when every instruction is right.
857 fn build(class: &Class) -> ClassPlan {
858 let mut plan = ClassPlan::default();
859 let mut instance_keys = 0usize;
860 let mut static_keys = 0usize;
861 for (index, element) in class.elements.iter().enumerate() {
862 match element {
863 ClassElement::Method {
864 key: PropName::Private(ident),
865 kind,
866 is_static,
867 ..
868 } => {
869 let name = format!("#{}", ident.name);
870 let first = !plan.uses.contains_key(&name);
871 if first {
872 plan.bindings.push(name.clone());
873 plan.uses.insert(
874 name.clone(),
875 PrivateUse {
876 kind: match kind {
877 MethodKind::Get => PrivateKind::Getter,
878 MethodKind::Set => PrivateKind::Setter,
879 _ => PrivateKind::Method,
880 },
881 setter: None,
882 },
883 );
884 }
885 match kind {
886 MethodKind::Set => {
887 let binding = format!("{name}<set>");
888 plan.bindings.push(binding.clone());
889 if let Some(use_) = plan.uses.get_mut(&name) {
890 use_.setter = Some(binding);
891 }
892 }
893 // A getter is what makes the name readable, so a pair that started
894 // as a setter becomes readable once the getter arrives.
895 MethodKind::Get => {
896 if let Some(use_) = plan.uses.get_mut(&name) {
897 use_.kind = PrivateKind::Getter;
898 }
899 }
900 _ => {}
901 }
902 if *is_static {
903 plan.static_brand = true;
904 } else {
905 plan.instance_brand = true;
906 }
907 }
908 ClassElement::Method {
909 key: PropName::Computed(_),
910 ..
911 } => {}
912 ClassElement::Method { .. } => {}
913 ClassElement::Field {
914 key: PropName::Private(ident),
915 ..
916 } => {
917 let name = format!("#{}", ident.name);
918 if !plan.uses.contains_key(&name) {
919 plan.bindings.push(name.clone());
920 plan.uses.insert(
921 name,
922 PrivateUse {
923 kind: PrivateKind::Field,
924 setter: None,
925 },
926 );
927 }
928 }
929 ClassElement::Field {
930 key: PropName::Computed(_),
931 is_static,
932 ..
933 } => {
934 let index_in_half = if *is_static {
935 static_keys += 1;
936 static_keys - 1
937 } else {
938 instance_keys += 1;
939 instance_keys - 1
940 };
941 let binding = computed_field_binding(index_in_half, *is_static);
942 plan.bindings.push(binding.clone());
943 plan.computed.insert(index, binding);
944 }
945 ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
946 }
947 }
948 plan
949 }
950
951 /// How a private name used inside the body compiles, or `None` if no enclosing class
952 /// declares it.
953 fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
954 compiler
955 .private_scopes
956 .iter()
957 .rev()
958 .find_map(|scope| scope.get(name))
959 }
960}
961
962impl Compiler {
963 /// The exact source text of a function, for `Function.prototype.toString`.
964 ///
965 /// §20.2.3.5 requires the *original* text: a function must stringify back to what
966 /// was written, comments and odd spacing included. Slicing the recorded span out of
967 /// the whole source is the only way to get that — rebuilding it from the AST would
968 /// normalise the text, and answering `[native code]` for a script function (which is
969 /// what this engine used to do) makes the result useless for feature detection and
970 /// for libraries that read their own source.
971 ///
972 /// Top-level bodies have no single expression span, so their `source` stays `None`
973 /// and `toString` falls back to the calling convention the spec allows.
974 fn function_source(
975 &self,
976 span: Option<(usize, usize)>,
977 line: u32,
978 column: u32,
979 ) -> Option<String> {
980 let source = self.source.as_ref()?;
981 let span = span?;
982 let bytes = source.as_bytes();
983 let start = span.0;
984 let end = span.1;
985 if start >= bytes.len() || end > bytes.len() || start >= end {
986 let _ = (line, column);
987 return None;
988 }
989 Some(source.get(start..end)?.to_string())
990 }
991}
992
993/// Compile a script.
994pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
995 Compiler::new(false).compile(program)
996}
997
998/// Compile a script, keeping its text so `Function.prototype.toString` can answer with
999/// the original source.
1000///
1001/// The separate entry point rather than a parameter on [`compile_script`] because the
1002/// tests and the disassembler compile from an AST they built themselves and have no
1003/// source to give; they keep the `None` behaviour they already relied on.
1004pub fn compile_script_with_source(
1005 program: &Program,
1006 source: &str,
1007) -> Result<CompiledFunction, SyntaxError> {
1008 let mut compiler = Compiler::new(false);
1009 compiler.source = Some(source.to_string());
1010 compiler.compile(program)
1011}
1012
1013/// [`compile_script_with_source`] for a module.
1014pub fn compile_module_with_source(
1015 program: &Program,
1016 source: &str,
1017) -> Result<CompiledFunction, SyntaxError> {
1018 let mut compiler = Compiler::new(true);
1019 compiler.source = Some(source.to_string());
1020 compiler.compile(program)
1021}
1022
1023/// Compile a script whose top level is the body of an `async` function.
1024/// The body is an ordinary script in every other way — it still reports a completion value
1025/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
1026/// it answers a promise instead of a value. The wrapper is what keeps that promise from
1027/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
1028/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
1029/// documents.
1030pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1031 Compiler::for_suspensible_script().compile(program)
1032}
1033
1034/// Compile a module.
1035pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1036 Compiler::new(true).compile(program)
1037}
1038
1039/// Compile a direct `eval` body that inherits private names from its caller.
1040///
1041/// `class C { #m = 44; f() { return eval("this.#m") } }` is legal — private names are
1042/// lexically scoped and the eval runs inside the caller's scope — but the names live in the
1043/// *call site's* compilation unit, so they have to be handed over. Seeding them as the
1044/// outermost private scope is what lets the eval resolve `#m` to the caller's binding: the
1045/// read compiles as an ordinary name lookup of `#m`, which at run time finds the caller's
1046/// slot through the same `eval`-scope machinery every other inherited name uses.
1047///
1048/// `suspensible` selects the `{async: true}` form (`std.evalScript(s, {async: true})`), whose
1049/// body may `await`.
1050pub fn compile_eval_with_private(
1051 program: &Program,
1052 private: &[EvalPrivate],
1053 suspensible: bool,
1054) -> Result<CompiledFunction, SyntaxError> {
1055 let mut compiler = if suspensible {
1056 Compiler::for_suspensible_script()
1057 } else {
1058 Compiler::new(false)
1059 };
1060 if !private.is_empty() {
1061 let scope: std::collections::HashMap<String, PrivateUse> = private
1062 .iter()
1063 .map(|entry| {
1064 (
1065 entry.name.clone(),
1066 PrivateUse {
1067 kind: match entry.kind {
1068 EvalPrivateKind::Field => PrivateKind::Field,
1069 EvalPrivateKind::Method => PrivateKind::Method,
1070 EvalPrivateKind::Getter => PrivateKind::Getter,
1071 EvalPrivateKind::Setter => PrivateKind::Setter,
1072 },
1073 setter: entry.setter.clone(),
1074 },
1075 )
1076 })
1077 .collect();
1078 compiler.private_scopes.push(scope);
1079 }
1080 compiler.compile(program)
1081}
1082
1083impl Compiler {
1084 /// Create a compiler.
1085 pub fn new(module: bool) -> Compiler {
1086 Compiler {
1087 source: None,
1088 module,
1089 async_body: false,
1090 stack: Vec::new(),
1091 private_scopes: Vec::new(),
1092 discard_root: false,
1093 }
1094 }
1095
1096 /// Create a compiler for a script whose top level is an `async` function body.
1097 fn for_suspensible_script() -> Compiler {
1098 Compiler {
1099 source: None,
1100 module: false,
1101 async_body: true,
1102 stack: Vec::new(),
1103 private_scopes: Vec::new(),
1104 discard_root: false,
1105 }
1106 }
1107
1108 /// Compile a whole program into its top-level function.
1109 pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
1110 let mut state = FnState::new("<eval>", FunctionKind::Normal);
1111 // A module body is *not* a script: it has no completion value, so no hidden
1112 // `<ret>` local and no `put_loc0` before each statement. What it shares with one
1113 // is having no `arguments` of its own and no receiver — see `is_module`.
1114 state.is_script = !self.module;
1115 state.is_module = self.module;
1116 if self.module {
1117 state.module = Some(ModuleMeta::default());
1118 }
1119 state.strict = program.strict || self.module;
1120 state.line = program.span.start.line;
1121 state.column = program.span.start.column;
1122 // Locals are numbered in declaration order; `<ret>` is always slot 0.
1123 //
1124 // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
1125 // slot that only appears in one of the two arrays shifts every later
1126 // binding's block and silently loses the temporal-dead-zone marking for
1127 // the script's own blocks. A function frame has no `<ret>`, which is why
1128 // the misalignment only showed up at the top level.
1129 if !self.module {
1130 state.vars.push(VarDef::var("<ret>"));
1131 state.var_block.push(FUNCTION_SCOPE);
1132 }
1133 self.stack.push(state);
1134 // The body is its own scope, keyed by the position of the program.
1135 // The script body needs a key no statement can produce. Statement keys are
1136 // source offsets, and the program's own start offset is `0` — which is also
1137 // the offset of the first statement, so a top-level `{ let x }` or
1138 // `for (let i …)` used to share the body's block and lose its scope.
1139 let body_key = SCRIPT_BODY;
1140 self.push_block(body_key, NO_PARENT);
1141 self.state().body_block = body_key;
1142 // A module body opens with a re-entry guard. The host evaluates a module exactly
1143 // once, so the guard never fires in practice — but the reference emits it, and a
1144 // module function called a second time (through `eval` of its own source, say)
1145 // must not run its body again.
1146 let module_guard = self.module.then(|| self.new_label());
1147 if let Some(body) = module_guard {
1148 // The guard wraps the *hoisting* too: a second evaluation of the same module
1149 // body must not even re-create its function declarations.
1150 self.emit(Opcode::PushThis, &[]);
1151 self.emit_jump(Opcode::IfFalse, body, &[]);
1152 }
1153 self.hoist(&program.body, body_key)?;
1154 // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
1155 // come before the guard's `return_undef`: the reference's jump target sits past
1156 // both, and a second evaluation therefore re-creates nothing.
1157 self.emit_scope_enter(body_key);
1158 if let Some(body) = module_guard {
1159 self.emit(Opcode::ReturnUndef, &[]);
1160 self.place_label(body);
1161 }
1162 // Through `stmts` rather than the loop, so a `using` region at the top level of an
1163 // eval'd body or a module gets its disposal epilogue like any other block.
1164 self.stmts(&program.body)?;
1165 if self.module {
1166 // A module has no completion value; its body simply ends.
1167 self.emit(Opcode::Undefined, &[]);
1168 self.emit(Opcode::ReturnAsync, &[]);
1169 // Top-level `await` makes the body an async function, so the host runs it as
1170 // a coroutine and waits. Without this the `await` opcode would suspend in a
1171 // body that nothing knows how to resume — which is what "a generator body ran
1172 // as an ordinary call" was reporting.
1173 if self.cur().has_await {
1174 self.state().kind = FunctionKind::Async;
1175 }
1176 } else if self.async_body {
1177 // An async body reports its completion value the same way, but through an
1178 // object: the function answers a promise, and resolving that promise *with*
1179 // the completion value would adopt a promise completion instead of reporting
1180 // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
1181 // resolve to `{value: <promise>}` rather than to `7`.
1182 //
1183 // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
1184 // value in an object so that promises can be safely returned").
1185 self.emit(Opcode::Object, &[]);
1186 self.emit(Opcode::Dup, &[]);
1187 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1188 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
1189 self.emit(Opcode::Return, &[]);
1190 self.state().kind = FunctionKind::Async;
1191 } else {
1192 // The program's value is whatever the last expression statement stored in
1193 // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
1194 // case into a single `set_loc0`.
1195 self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1196 self.emit(Opcode::Return, &[]);
1197 }
1198 Ok(self.finish_current())
1199 }
1200
1201 // -- emitting ----------------------------------------------------------
1202
1203 fn state(&mut self) -> &mut FnState {
1204 self.stack.last_mut().expect("a function is being compiled")
1205 }
1206
1207 fn cur(&self) -> &FnState {
1208 self.stack.last().expect("a function is being compiled")
1209 }
1210
1211 fn emit(&mut self, op: Opcode, operands: &[Op]) {
1212 self.state().label_since_insn = false;
1213 let pos = self.cur().cur_pos;
1214 self.state().insns.push(Insn::Fixed {
1215 op,
1216 operands: operands.to_vec(),
1217 });
1218 self.state().insn_pos.push(pos);
1219 }
1220
1221 /// Reset the script's hidden return value to `undefined`.
1222 ///
1223 /// Called at the start of every statement that does not itself produce the
1224 /// program's value, which is how the reference keeps `if`/loop results from
1225 /// leaking into an eval result.
1226 fn reset_value(&mut self) {
1227 if !self.cur().is_script {
1228 return;
1229 }
1230 self.emit(Opcode::Undefined, &[]);
1231 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1232 self.state().leaves_value = false;
1233 }
1234
1235 /// Whether `name` is a local or argument slot rather than a global.
1236 fn is_slot(&self, name: &str) -> bool {
1237 self.cur().vars.iter().any(|v| v.name == name)
1238 || self.cur().args.iter().any(|a| a.name == name)
1239 }
1240
1241 /// `with (object) body`
1242 ///
1243 /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
1244 /// what makes the object reachable from a closure created inside the block, and it
1245 /// is also what lets an `eval` find it: the runtime collects the active `With`
1246 /// locals of every frame and resolves names against them before the realm.
1247 ///
1248 /// Inside the block every name reference is spelled as "look in the with objects
1249 /// first", innermost outwards, and falls through to the ordinary access. The test is
1250 /// `in`, which is `HasProperty` — the same question the spec's Object Environment
1251 /// Record asks.
1252 fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
1253 let name = self.next_with_name();
1254 // The object expression is evaluated *outside* the scope it introduces, so no
1255 // wrapper may be emitted for the names it mentions.
1256 let saved = std::mem::take(&mut self.state().with_names);
1257 self.expr(object)?;
1258 self.state().with_names = saved;
1259 self.emit(Opcode::ToObject, &[]);
1260 self.declare_hidden_local(&name, VarKind::With);
1261 // Pushed before the store so the store itself is not guarded by an *outer*
1262 // `with` — the object being stored is the new one, not something to look up.
1263 self.state().with_names.push(name.clone());
1264 self.emit_var(VarAction::Put, &name);
1265 let result = self.stmt(body);
1266 self.state().with_names.pop();
1267 result
1268 }
1269
1270 /// A hidden-local name for one `with` block, distinct from every enclosing one.
1271 fn next_with_name(&self) -> String {
1272 let depth = self.cur().with_names.len();
1273 if depth == 0 {
1274 "<with>".to_string()
1275 } else {
1276 format!("<with{depth}>")
1277 }
1278 }
1279
1280 /// Declare a hidden local that must stay a *local* even in a script.
1281 ///
1282 /// A script's `var` is a property of the global object, but the `with` object is not
1283 /// part of the source program's name space at all — it only exists for the compiler
1284 /// and the runtime — so it goes straight into the frame's slot list.
1285 fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
1286 let state = self.state();
1287 if state.vars.iter().any(|v| v.name == name) {
1288 return;
1289 }
1290 state.var_block.push(FUNCTION_SCOPE);
1291 state.vars.push(VarDef {
1292 kind,
1293 ..VarDef::var(name)
1294 });
1295 }
1296
1297 /// Emit a name access, guarded by every active `with` object.
1298 ///
1299 /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
1300 /// the read itself; the outer guards and the plain access are what the `if_false`
1301 /// jumps to, so the innermost object wins.
1302 fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
1303 let names = self.cur().with_names.clone();
1304 let done = self.new_label();
1305 let mut starts = Vec::new();
1306 // Innermost object first: the last `with` opened is the one that shadows the
1307 // others, so its guard has to be the first chance to satisfy the name.
1308 for with_name in names.iter().rev() {
1309 let next = self.new_label();
1310 // `in` takes the key then the object.
1311 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1312 self.emit_var(VarAction::Get, with_name);
1313 self.emit(Opcode::In, &[]);
1314 self.emit_jump(Opcode::IfFalse, next, &[]);
1315 starts.push(next);
1316 match action {
1317 // A store keeps the value under the receiver, which is where
1318 // `put_field` expects it.
1319 VarAction::Put | VarAction::PutInit => {
1320 self.emit_var(VarAction::Get, with_name);
1321 self.emit(Opcode::Swap, &[]);
1322 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(name))]);
1323 }
1324 _ => {
1325 self.emit_var(VarAction::Get, with_name);
1326 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1327 self.emit(Opcode::GetArrayEl, &[]);
1328 }
1329 }
1330 self.emit_jump(Opcode::Goto, done, &[]);
1331 self.place_label(next);
1332 }
1333 self.emit_var(action, name);
1334 self.place_label(done);
1335 }
1336
1337 fn emit_var(&mut self, action: VarAction, name: &str) {
1338 // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
1339 // stores and keeps the value in one instruction. The reference does this
1340 // in a post-pass; folding it at emit time keeps instruction indices
1341 // stable, which matters because labels are recorded as indices.
1342 //
1343 // Only slots have a `set_` form: a global is stored with `put_var` and
1344 // read with `get_var`, and the reference does not fold those.
1345 //
1346 // A label between the two cancels the fold. `set_x v` leaves the value on
1347 // the stack, which is only equivalent when the read immediately follows the
1348 // store; when a jump target sits in between, the store must *consume* the
1349 // value and the read must fetch it afresh. A loop head is exactly that
1350 // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
1351 // condition re-reads it — and folding across the label would make the
1352 // condition compare whatever the previous iteration left on the stack.
1353 if action == VarAction::Get {
1354 let is_slot = self.is_slot(name);
1355 let at_label = std::mem::take(&mut self.state().label_since_insn);
1356 //
1357 // `arguments` is excluded because the reference treats it as a special
1358 // binding: it is initialised once and read many times, and folding its
1359 // initialisation into a `set_` would leave the object on the stack where
1360 // the reference leaves nothing.
1361 if is_slot
1362 && name != "arguments"
1363 && !at_label
1364 && let Some(Insn::Var {
1365 action: previous,
1366 name: previous_name,
1367 ..
1368 }) = self.state().insns.last_mut()
1369 && *previous == VarAction::Put
1370 && previous_name == name
1371 {
1372 *previous = VarAction::Set;
1373 return;
1374 }
1375 }
1376 // Inside a `with`, every name lookup consults the with objects first. The
1377 // hidden `<with…>` locals themselves are exempt, or the guard would recurse.
1378 let guarded = !self.cur().with_names.is_empty()
1379 && !self.cur().with_names.iter().any(|hidden| hidden == name)
1380 && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1381 && !self.state().emitting_with_guard;
1382 if guarded {
1383 self.state().emitting_with_guard = true;
1384 self.emit_with_guarded(action, name);
1385 self.state().emitting_with_guard = false;
1386 return;
1387 }
1388 let block = self.cur().current_block;
1389 self.state().label_since_insn = false;
1390 let pos = self.cur().cur_pos;
1391 let in_params = self.cur().in_params;
1392 self.state().insns.push(Insn::Var {
1393 action,
1394 name: name.to_string(),
1395 block,
1396 in_params,
1397 });
1398 self.state().insn_pos.push(pos);
1399 }
1400
1401 fn new_label(&mut self) -> Label {
1402 let state = self.state();
1403 state.labels.push(None);
1404 Label(state.labels.len() as u32 - 1)
1405 }
1406
1407 fn place_label(&mut self, label: Label) {
1408 let index = self.cur().insns.len();
1409 self.state().label_since_insn = true;
1410 self.state().labels[label.0 as usize] = Some(index);
1411 }
1412
1413 fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1414 let mut operands = vec![Op::Label(label)];
1415 operands.extend_from_slice(extra);
1416 self.emit(op, &operands);
1417 }
1418
1419 // -- scopes ------------------------------------------------------------
1420
1421 /// Start a new lexical scope inside `parent`.
1422 fn push_block(&mut self, key: u64, parent: u64) {
1423 let state = self.state();
1424 if !state.blocks.iter().any(|b| b.key == key) {
1425 state.blocks.push(Block { key, parent });
1426 }
1427 state.current_block = key;
1428 }
1429
1430 /// Emit the code that runs when a lexical scope is entered.
1431 ///
1432 /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1433 /// so entering its block marks it uninitialised. Hoisted function
1434 /// declarations are created here instead, which is why a call before the
1435 /// declaration still works.
1436 ///
1437 /// The order is not obvious: bindings are emitted in *reverse* declaration
1438 /// order, because the reference walks its scope chain, which is built by
1439 /// prepending.
1440 fn emit_scope_enter(&mut self, block: u64) {
1441 // Only *this* scope's hoisted declarations are consumed here; the rest stay in the
1442 // list for the scope that owns them. `std::mem::take` used to empty the whole list,
1443 // so entering an outer scope threw away every nested block's function
1444 // declarations: `function h(){ { function k(){} } return k; }` answered
1445 // `undefined`, and `{ function g(){} }` was `undefined` even *inside* the block.
1446 // That is one Annex B rule the engine otherwise implements (a sloppy-mode function
1447 // in a block is also a `var` of the enclosing function), and it is what makes the
1448 // `for (const ctor of ctors) { function f(){} … }` shape in test262 work.
1449 let mut hoisted = std::mem::take(&mut self.state().hoisted);
1450 let mut rest = Vec::with_capacity(hoisted.len());
1451 let mut mine: Vec<(HoistTarget, u32)> = Vec::new();
1452 for (owner, target, pool_index) in hoisted.drain(..) {
1453 if owner == block {
1454 mine.push((target, pool_index));
1455 } else {
1456 rest.push((owner, target, pool_index));
1457 }
1458 }
1459 self.state().hoisted = rest;
1460 mine.sort_by_key(|(target, _)| match target {
1461 HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1462 HoistTarget::Global(_) => u32::MAX,
1463 });
1464 for (target, pool_index) in mine {
1465 self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1466 match target {
1467 HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1468 HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1469 HoistTarget::Global(name) => {
1470 // A global binding lives in a reference cell, so the store
1471 // goes through `put_var_ref` while reads use `get_var`.
1472 let block = self.cur().current_block;
1473 let pos = self.cur().cur_pos;
1474 let in_params = self.cur().in_params;
1475 self.state().insns.push(Insn::Var {
1476 action: VarAction::PutRef,
1477 name,
1478 block,
1479 in_params,
1480 });
1481 self.state().insn_pos.push(pos);
1482 }
1483 }
1484 }
1485 for index in self.block_vars_reversed(block) {
1486 self.emit(
1487 Opcode::SetLocUninitialized,
1488 &[Op::Slot(Slot::Loc(index as u32))],
1489 );
1490 }
1491 }
1492
1493 /// Emit the code that runs when a lexical scope is exited.
1494 ///
1495 /// A captured binding has to be closed: detaching its reference cell freezes
1496 /// the value the binding had when the block ended, which is what a closure
1497 /// created inside the block must keep seeing.
1498 fn emit_scope_leave(&mut self, block: u64) {
1499 for index in self.block_vars_reversed(block) {
1500 if self.cur().vars[index].is_captured {
1501 self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1502 }
1503 }
1504 }
1505
1506 /// Locals declared in `block`, in reverse declaration order.
1507 fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1508 let state = self.cur();
1509 let mut out: Vec<usize> = (0..state.vars.len())
1510 .filter(|index| {
1511 state.var_block.get(*index).copied() == Some(block)
1512 && state.vars[*index].is_lexical
1513 // A derived constructor's `this` is lexical but is not initialised by
1514 // entering the scope: `check_ctor` proves it, so its dead-zone marker
1515 // was emitted with the constructor's own prologue.
1516 && state.vars[*index].name != "this"
1517 })
1518 .collect();
1519 out.reverse();
1520 out
1521 }
1522
1523 /// Declare a local, even at the top level of a script.
1524 ///
1525 /// A `catch` parameter is always a local: the reference puts it in the
1526 /// function's own variable list (`1: catch e`), never in the global object,
1527 /// because it only exists while the handler runs.
1528 fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1529 let state = self.state();
1530 let index = state.vars.len() as u32;
1531 // A `catch` parameter belongs to a scope even though it is not lexical: the
1532 // runtime instantiates it per handler entry, but it never sits in the
1533 // temporal dead zone.
1534 let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1535 state.current_block
1536 } else {
1537 0
1538 };
1539 state.var_block.push(block);
1540 state.vars.push(def);
1541 index
1542 }
1543
1544 fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1545 if self.cur().is_module
1546 && self.cur().current_block == self.cur().body_block
1547 && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1548 {
1549 // Only the body's own block: a `let` inside a module-level `{}` is still an
1550 // ordinary local of that block, not a module variable.
1551 //
1552 // A `using` binding is excluded on purpose, and the reference excludes it in
1553 // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1554 // "'using' variables are currently not exported in modules"): a module-level
1555 // `using` is an ordinary *local* of the module body function, not a module
1556 // cell. Two things follow, and both are what the reference does — `export {a}`
1557 // of a `using` binding is "exported variable 'a' does not exist", and
1558 // disposal works, because the disposal epilogue addresses locals by slot.
1559 //
1560 // The hidden dispose-method variable is excluded for a stronger reason: it is
1561 // *always* a local (`add_scope_var` in the reference), and it must sit
1562 // immediately after its value so `using_dispose` can find it at `slot + 1`.
1563 return self.declare_module(name, &def);
1564 }
1565 if self.cur().declares_globally(&def) {
1566 self.declare_global(name, &def);
1567 return 0;
1568 }
1569 let state = self.state();
1570 let index = state.vars.len() as u32;
1571 let block = if def.is_lexical {
1572 state.current_block
1573 } else {
1574 0
1575 };
1576 state.var_block.push(block);
1577 state.vars.push(def);
1578 index
1579 }
1580
1581 /// Declare a `using` binding and its cached dispose method, returning both slots.
1582 ///
1583 /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1584 /// `(value, value + 1)` — the reference does the same and documents the constraint.
1585 fn declare_using(&mut self, name: &str) -> (u32, u32) {
1586 let mut def = VarDef::lexical(name);
1587 def.kind = VarKind::Using;
1588 let value = self.declare(name, def);
1589 let mut method = VarDef::lexical(using_method_name(name));
1590 method.kind = VarKind::UsingMethod;
1591 let method_slot = self.declare(&using_method_name(name), method);
1592 (value, method_slot)
1593 }
1594
1595 /// The slot a `using` binding's dispose method lives in.
1596 fn using_method_slot(&self, name: &str) -> Option<u32> {
1597 let hidden = using_method_name(name);
1598 self.cur()
1599 .vars
1600 .iter()
1601 .position(|var| var.name == hidden)
1602 .map(|index| index as u32)
1603 }
1604
1605 // -- statements --------------------------------------------------------
1606
1607 fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1608 self.stmt_labelled(stmt, &[])
1609 }
1610
1611 /// Compile a statement that a chain of labels names.
1612 ///
1613 /// Only a loop consumes `labels`; every other statement ignores them (the
1614 /// parser has already rejected a label on a statement that cannot use it).
1615 fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1616 // Only a *top-level* expression statement supplies the program's value.
1617 let saved = self.cur().leaves_value;
1618 self.state().leaves_value =
1619 matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1620 self.state().stmt_depth += 1;
1621 let result = self.stmt_inner(stmt, labels);
1622 self.state().stmt_depth -= 1;
1623 // A nested statement never contributes the program's value, so the flag
1624 // the wrapper set above is what survives.
1625 let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1626 self.state().leaves_value = produced;
1627 let _ = saved;
1628 result
1629 }
1630
1631 fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1632 match &stmt.kind {
1633 StmtKind::Empty | StmtKind::Debugger => {}
1634 StmtKind::Expr(expr) => {
1635 // The statement's first token is a position the reference records: an
1636 // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1637 // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1638 // is why an error from a construct with no position of its own (`[...it]`
1639 // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1640 let saved = self.cur().cur_pos;
1641 self.state().cur_pos = Some(expr.span.start);
1642 // An expression statement's value is thrown away — except in a
1643 // script, where it becomes the program's result. `assign` reads this
1644 // and clears it, so a nested assignment still produces a value.
1645 self.state().discard_value = !self.cur().is_script;
1646 let result = self.expr(expr);
1647 self.state().discard_value = false;
1648 result?;
1649 if std::mem::take(&mut self.state().no_value) {
1650 // A store whose value was discarded left nothing to drop.
1651 } else if self.cur().is_script {
1652 // The program's value lands in the hidden `<ret>` local.
1653 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1654 } else {
1655 self.emit(Opcode::Drop, &[]);
1656 }
1657 // Restored last: the trailing `drop` is part of the statement, and in the
1658 // reference it simply inherits whatever the expression last recorded.
1659 self.state().cur_pos = saved;
1660 }
1661 StmtKind::Block(body) => {
1662 // The block's declarations were hoisted with its enclosing
1663 // statement list, so there is nothing left to declare here.
1664 let key = stmt.span.start.offset as u64;
1665 let parent = self.cur().current_block;
1666 self.push_block(key, parent);
1667 self.emit_scope_enter(key);
1668 // A block is where a `using` region lives, so its statements have to go
1669 // through `stmts`: that is what emits the disposal epilogue.
1670 self.stmts(body)?;
1671 self.emit_scope_leave(key);
1672 self.state().current_block = parent;
1673 }
1674 StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1675 // A function declaration was already instantiated when its scope was
1676 // entered, so the statement itself emits nothing.
1677 StmtKind::FuncDecl(_) => {}
1678 StmtKind::If { test, cons, alt } => {
1679 self.reset_value();
1680 let else_label = self.new_label();
1681 let end_label = self.new_label();
1682 self.expr(test)?;
1683 self.emit_jump(Opcode::IfFalse, else_label, &[]);
1684 self.stmt(cons)?;
1685 if alt.is_some() {
1686 self.emit_jump(Opcode::Goto, end_label, &[]);
1687 }
1688 self.place_label(else_label);
1689 if let Some(alt) = alt {
1690 self.stmt(alt)?;
1691 self.place_label(end_label);
1692 }
1693 }
1694 StmtKind::While { test, body } => {
1695 self.reset_value();
1696 let top = self.new_label();
1697 let end = self.new_label();
1698 self.place_label(top);
1699 self.expr(test)?;
1700 // The condition's false branch and `break` share one target,
1701 // which is why a `while` loop needs only one end label.
1702 self.emit_jump(Opcode::IfFalse, end, &[]);
1703 self.loop_body(body, labels, top, end)?;
1704 self.emit_jump(Opcode::Goto, top, &[]);
1705 self.place_label(end);
1706 }
1707 StmtKind::DoWhile { body, test } => {
1708 self.reset_value();
1709 let top = self.new_label();
1710 let cont = self.new_label();
1711 let end = self.new_label();
1712 self.place_label(top);
1713 // `continue` in a `do…while` runs the test, so it lands on `cont`
1714 // rather than on the loop head.
1715 self.loop_body(body, labels, cont, end)?;
1716 self.place_label(cont);
1717 self.expr(test)?;
1718 self.emit_jump(Opcode::IfTrue, top, &[]);
1719 self.place_label(end);
1720 }
1721 StmtKind::For {
1722 init,
1723 test,
1724 update,
1725 body,
1726 } => {
1727 self.reset_value();
1728 let for_key = stmt.span.start.offset as u64;
1729 let for_parent = self.cur().current_block;
1730 self.push_block(for_key, for_parent);
1731 self.emit_scope_enter(for_key);
1732 if let Some(init) = init {
1733 match init {
1734 ForInit::VarDecl(decl) => {
1735 self.var_decl(decl)?;
1736 }
1737 ForInit::Expr(expr) => {
1738 // The head's value is discarded. Saying so lets an
1739 // assignment store with `put` instead of `dup`+`put`, which
1740 // is what the reference emits — and the difference matters:
1741 // a `dup`/`drop` pair around the store gives the peephole a
1742 // chance to fold the store into the *condition's* read.
1743 self.state().discard_value = true;
1744 let result = self.expr(expr);
1745 self.state().discard_value = false;
1746 result?;
1747 if !std::mem::take(&mut self.state().no_value) {
1748 self.emit(Opcode::Drop, &[]);
1749 }
1750 }
1751 }
1752 }
1753 // A `let`/`const` in the head gets a *fresh binding per iteration*,
1754 // so a closure made in the body captures that iteration's value
1755 // instead of sharing one. The reference expresses this with
1756 // `close_loc`, which swaps in a new reference cell holding the
1757 // current value; the three points below are the ones it uses — after
1758 // the initialiser, before the update, and after the loop.
1759 let loop_bindings = match init {
1760 Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
1761 let mut names: Vec<String> = Vec::new();
1762 for declarator in &decl.declarators {
1763 let mut idents = Vec::new();
1764 declarator.target.bound_names(&mut idents);
1765 names.extend(idents.into_iter().map(|ident| ident.name));
1766 }
1767 names
1768 }
1769 _ => Vec::new(),
1770 };
1771 // The reference also closes right after the initialiser, so the first
1772 // iteration's closures get their own cell rather than sharing the one
1773 // the initialiser wrote into.
1774 for name in &loop_bindings {
1775 let pos = self.cur().cur_pos;
1776 self.state().insns.push(Insn::CloseCaptured {
1777 name: name.clone(),
1778 block: for_key,
1779 });
1780 self.state().insn_pos.push(pos);
1781 }
1782 let top = self.new_label();
1783 let cont = self.new_label();
1784 let end = self.new_label();
1785 self.place_label(top);
1786 if let Some(test) = test {
1787 self.expr(test)?;
1788 self.emit_jump(Opcode::IfFalse, end, &[]);
1789 }
1790 // `continue` runs the update expression first, so it lands on
1791 // `cont`, which sits just before the update.
1792 self.loop_body(body, labels, cont, end)?;
1793 self.place_label(cont);
1794 // Each iteration ends with a fresh cell, so the closures the body just
1795 // created keep the cell they captured and the update writes to a new
1796 // one. Without this every closure in the loop shares one binding.
1797 let binding_block = for_key;
1798 for name in &loop_bindings {
1799 let pos = self.cur().cur_pos;
1800 self.state().insns.push(Insn::CloseCaptured {
1801 name: name.clone(),
1802 block: binding_block,
1803 });
1804 self.state().insn_pos.push(pos);
1805 }
1806 if let Some(update) = update {
1807 self.state().discard_value = true;
1808 let result = self.expr(update);
1809 self.state().discard_value = false;
1810 result?;
1811 if !std::mem::take(&mut self.state().no_value) {
1812 self.emit(Opcode::Drop, &[]);
1813 }
1814 }
1815 self.emit_jump(Opcode::Goto, top, &[]);
1816 self.place_label(end);
1817 self.emit_scope_leave(for_key);
1818 self.state().current_block = for_parent;
1819 }
1820 StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1821 StmtKind::Throw(expr) => {
1822 self.expr(expr)?;
1823 self.emit(Opcode::Throw, &[]);
1824 }
1825 StmtKind::Break(_) | StmtKind::Continue(_) => {
1826 // Labels and loops are wired up in a later milestone; a bare
1827 // break/continue jumps to the innermost enclosing target, which
1828 // the loop helpers register.
1829 self.control_transfer(stmt)?;
1830 }
1831 StmtKind::Labeled { label, body } => {
1832 self.labeled(label, body, stmt)?;
1833 }
1834 StmtKind::Switch {
1835 discriminant,
1836 cases,
1837 } => {
1838 self.switch(discriminant, cases, stmt)?;
1839 }
1840 StmtKind::Try {
1841 block,
1842 handler,
1843 finalizer,
1844 } => {
1845 self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
1846 }
1847 StmtKind::ForIn { left, right, body } => {
1848 self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
1849 }
1850 StmtKind::ForOf {
1851 left,
1852 right,
1853 body,
1854 is_await,
1855 } => {
1856 let kind = if *is_await {
1857 ForLoopKind::AwaitOf
1858 } else {
1859 ForLoopKind::Of
1860 };
1861 self.for_in_of(stmt, left, right, body, kind, labels)?;
1862 }
1863 StmtKind::With { object, body } => self.with_stmt(object, body)?,
1864 StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
1865 // `import` emits nothing: hoisting already bound its names, and the host
1866 // fills their cells before the body runs.
1867 StmtKind::Import(_) => {}
1868 StmtKind::Export(decl) => self.export_stmt(decl)?,
1869 }
1870 Ok(())
1871 }
1872
1873 /// Compile `return`, running every enclosing finalizer on the way out.
1874 ///
1875 /// `nip_catch` is what makes this possible: it discards everything on the stack
1876 /// down to and including the `catch` offset while keeping the return value on
1877 /// top, so the frame the finalizer sees has the same shape as on the normal
1878 /// path.
1879 fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
1880 let mut has_value = value.is_some();
1881 if let Some(expr) = value {
1882 // `return f(x)` is a tail call *only* when nothing has to happen to the
1883 // value afterwards. A `finally` or an open iterator in scope forces the
1884 // normal path, because the cleanup has to run after the call returns —
1885 // which is exactly what a tail call refuses to do.
1886 let plain = self
1887 .cur()
1888 .jump_targets
1889 .iter()
1890 .all(|target| target.finally_label.is_none() && !target.has_iterator);
1891 if plain && self.expr_if_tail_call(expr)? {
1892 // A tail call never reaches `expr`, so the direct-eval bookkeeping has to
1893 // happen here as well.
1894 self.note_direct_eval(expr);
1895 return Ok(());
1896 }
1897 self.expr(expr)?;
1898 }
1899 // `return v` in an *async generator* awaits `v` before anything else happens —
1900 // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
1901 // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
1902 // exactly that reason ("the await must be done before handling the finally in case
1903 // it raises an exception").
1904 if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
1905 self.emit(Opcode::Await, &[]);
1906 self.state().has_await = true;
1907 }
1908 has_value = self.emit_unwind_for_return(has_value);
1909 // A generator or async function does not return to its caller: it either
1910 // finishes, and the value becomes `{value, done: true}`, or it suspends.
1911 // `return_async` is the "finished" half, and it reads the value off the stack
1912 // rather than carrying it, which is what the resume machinery expects.
1913 if self.cur().is_suspending() {
1914 if !has_value {
1915 self.emit(Opcode::Undefined, &[]);
1916 }
1917 self.emit(Opcode::ReturnAsync, &[]);
1918 return Ok(());
1919 }
1920 if has_value {
1921 self.emit(Opcode::Return, &[]);
1922 } else {
1923 self.emit(Opcode::ReturnUndef, &[]);
1924 }
1925 Ok(())
1926 }
1927
1928 /// Close an iterator: the reference's `emit_iterator_close`.
1929 ///
1930 /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
1931 /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
1932 /// sequence, and three details in it are load-bearing:
1933 ///
1934 /// * the iterator object is compared against `undefined` first, because a loop that
1935 /// ran to completion clears that slot rather than closing an exhausted iterator;
1936 /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
1937 /// * `preserve_completion` keeps whatever was underneath (the return value of the
1938 /// function being left), which is why one branch ends on `nip` and the other on `drop`.
1939 fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
1940 if !is_async {
1941 if preserve_completion {
1942 self.emit(Opcode::Rot3r, &[]);
1943 self.emit(Opcode::Undefined, &[]);
1944 }
1945 self.emit(Opcode::IteratorClose, &[]);
1946 return;
1947 }
1948 if preserve_completion {
1949 // `iter next completion -> completion iter`
1950 self.emit(Opcode::Nip, &[]);
1951 self.emit(Opcode::Swap, &[]);
1952 } else {
1953 // `iter next catch_offset -> iter`
1954 self.emit(Opcode::Drop, &[]);
1955 self.emit(Opcode::Drop, &[]);
1956 }
1957 let done = self.new_label();
1958 let no_return = self.new_label();
1959 self.emit(Opcode::Dup, &[]);
1960 self.emit(Opcode::IsUndefined, &[]);
1961 self.emit_jump(Opcode::IfTrue, done, &[]);
1962 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
1963 self.emit(Opcode::Dup, &[]);
1964 self.emit(Opcode::IsUndefinedOrNull, &[]);
1965 self.emit_jump(Opcode::IfTrue, no_return, &[]);
1966 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
1967 self.emit(Opcode::Await, &[]);
1968 self.state().has_await = true;
1969 self.emit_jump(Opcode::Goto, done, &[]);
1970 self.place_label(no_return);
1971 self.emit(Opcode::Drop, &[]);
1972 self.place_label(done);
1973 self.emit(Opcode::Drop, &[]);
1974 }
1975
1976 /// Emit the finalizer/iterator cleanup for leaving the current position with a
1977 /// return, and report whether a value is now on the stack for it to carry.
1978 ///
1979 /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
1980 /// enclosing `finally` at once, and the two used to be separate — the `yield` path
1981 /// simply emitted `return_async`, so `it.return()` ended the generator without ever
1982 /// running `finally` blocks the body was sitting inside.
1983 fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
1984 let targets = self.cur().jump_targets.clone();
1985 for target in targets.iter().rev() {
1986 if target.finally_label.is_none() && !target.has_iterator {
1987 continue;
1988 }
1989 if !has_value {
1990 // The cleanup expects a value to pass through; with nothing to
1991 // return, `undefined` stands in.
1992 self.emit(Opcode::Undefined, &[]);
1993 has_value = true;
1994 }
1995 self.emit(Opcode::NipCatch, &[]);
1996 if target.has_iterator {
1997 // Rewind to the loop's own slots and hand the close a dummy catch offset:
1998 // the loop is being abandoned, so there is nothing left to catch.
1999 self.emit_iterator_close(target.is_async_iterator, true);
2000 } else if let Some(finally) = target.finally_label {
2001 self.emit_jump(Opcode::Gosub, finally, &[]);
2002 }
2003 }
2004 has_value
2005 }
2006
2007 /// Compile a statement list, stopping at the first statement that cannot
2008 /// fall through.
2009 fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2010 for (index, stmt) in body.iter().enumerate() {
2011 // A `using` declaration is not just a binding: everything after it, to the end
2012 // of the list, runs inside its disposal region. Compiling the rest of the list
2013 // recursively is what gives nested regions their innermost-first order.
2014 if Self::using_declaration(stmt).is_some() {
2015 return self.using_region(stmt, &body[index + 1..]);
2016 }
2017 self.stmt(stmt)?;
2018 if Self::terminates(stmt) {
2019 break;
2020 }
2021 }
2022 Ok(())
2023 }
2024
2025 /// The declaration a `using` statement carries, if it is one.
2026 fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
2027 match &stmt.kind {
2028 StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
2029 _ => None,
2030 }
2031 }
2032
2033 /// Compile `decl` and then the rest of its block, disposing when the block ends.
2034 ///
2035 /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
2036 /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
2037 /// exception — and this engine already funnels all of those through `catch` plus
2038 /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
2039 /// `return` and `break` dispose without knowing anything about `using`.
2040 ///
2041 /// ```text
2042 /// <declaration> value -> x, method -> x+1
2043 /// catch CATCH <- an exception in the rest lands here
2044 /// REST:
2045 /// <the rest of the block>
2046 /// drop <- the catch offset, on the fall-through path
2047 /// undefined; gosub DISPOSE; drop
2048 /// goto END
2049 /// CATCH:
2050 /// using_dispose x <- merges the failure into the pending exception
2051 /// throw
2052 /// DISPOSE:
2053 /// using_dispose_init
2054 /// using_dispose x
2055 /// using_dispose_end <- rethrows if a dispose failed
2056 /// ret
2057 /// END:
2058 /// ```
2059 fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
2060 let Some(decl) = Self::using_declaration(stmt) else {
2061 unreachable!("using_region is only called for a using declaration");
2062 };
2063 // `using` binds exactly one name and has no pattern form, which the parser
2064 // enforces; the region still has to know *which* slot to dispose.
2065 let name = decl
2066 .declarators
2067 .first()
2068 .and_then(|declarator| match &declarator.target.kind {
2069 PatternKind::Ident(ident) => Some(ident.name.clone()),
2070 _ => None,
2071 });
2072 self.stmt(stmt)?;
2073 let Some(name) = name else {
2074 // Unreachable for a well-formed `using`, but a bare `using` with no declarator
2075 // must not make the compiler panic.
2076 return self.stmts(rest);
2077 };
2078 let Some(value_slot) = self.using_value_slot(&name) else {
2079 // Declared globally, which the parser rules out for a script; a module's
2080 // top level is a scope, and there the disposal stays a known gap.
2081 return self.stmts(rest);
2082 };
2083 // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
2084 // exit path already disposed.
2085 let live = !rest.last().is_some_and(Self::terminates);
2086 self.using_region_around(value_slot, live, |compiler| compiler.stmts(rest))
2087 }
2088
2089 /// The slot a `using` binding's value lives in.
2090 fn using_value_slot(&self, name: &str) -> Option<u32> {
2091 self.cur()
2092 .vars
2093 .iter()
2094 .position(|var| var.name == name && var.kind == VarKind::Using)
2095 .map(|index| index as u32)
2096 }
2097
2098 /// Wrap `inside` in a disposal region for the resource in `value_slot`.
2099 ///
2100 /// Shared between a `using` statement — which owns the rest of its block — and a
2101 /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
2102 /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
2103 /// the end, `return`, `break`, `continue`, and an exception — and this engine already
2104 /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
2105 /// target with a `finally_label` is what makes `return` and `break` dispose without
2106 /// knowing anything about `using`.
2107 ///
2108 /// ```text
2109 /// catch CATCH <- an exception inside lands here
2110 /// <inside>
2111 /// drop <- the catch offset, on the fall-through path
2112 /// undefined; gosub DISPOSE; drop
2113 /// goto END
2114 /// CATCH:
2115 /// using_dispose slot <- merges the failure into the pending exception
2116 /// throw
2117 /// DISPOSE:
2118 /// using_dispose_init
2119 /// using_dispose slot
2120 /// using_dispose_end <- rethrows if a dispose failed
2121 /// ret
2122 /// END:
2123 /// ```
2124 fn using_region_around(
2125 &mut self,
2126 value_slot: u32,
2127 live: bool,
2128 inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
2129 ) -> Result<(), SyntaxError> {
2130 let catch_label = self.new_label();
2131 let end_label = self.new_label();
2132 let dispose_label = self.new_label();
2133
2134 self.emit_jump(Opcode::Catch, catch_label, &[]);
2135 self.push_jump_target(JumpTarget {
2136 names: Vec::new(),
2137 break_label: None,
2138 continue_label: None,
2139 // The catch offset is the one thing on the stack that leaving has to remove.
2140 drop_count: 1,
2141 finally_label: Some(dispose_label),
2142 is_regular_stmt: false,
2143 has_iterator: false,
2144 is_async_iterator: false,
2145 });
2146 inside(self)?;
2147 self.pop_jump_target();
2148
2149 if live {
2150 self.emit(Opcode::Drop, &[]);
2151 self.emit(Opcode::Undefined, &[]);
2152 self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2153 self.emit(Opcode::Drop, &[]);
2154 self.emit_jump(Opcode::Goto, end_label, &[]);
2155 }
2156
2157 // An exception unwinds to here with the thrown value on the stack, which is exactly
2158 // the shape `using_dispose` expects as its error state.
2159 self.place_label(catch_label);
2160 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2161 self.emit(Opcode::Throw, &[]);
2162
2163 self.place_label(dispose_label);
2164 // Inside the subroutine the return value and the `gosub` return address are both
2165 // live, and neither an outer finalizer nor another region may run before this one
2166 // has finished.
2167 self.push_jump_target(JumpTarget {
2168 names: Vec::new(),
2169 break_label: None,
2170 continue_label: None,
2171 drop_count: 2,
2172 finally_label: None,
2173 is_regular_stmt: false,
2174 has_iterator: false,
2175 is_async_iterator: false,
2176 });
2177 self.emit(Opcode::UsingDisposeInit, &[]);
2178 self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2179 self.emit(Opcode::UsingDisposeEnd, &[]);
2180 self.pop_jump_target();
2181 self.emit(Opcode::Ret, &[]);
2182 self.place_label(end_label);
2183 Ok(())
2184 }
2185
2186 /// Declare every name a statement list introduces, before compiling any of
2187 /// it, so a reference that appears textually before a declaration still
2188 /// resolves.
2189 ///
2190 /// Declarations are walked in source order because that is the order the
2191 /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2192 /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2193 /// declarations hoist out to the function scope; lexical names belong to the
2194 /// block they were written in, which `block` records.
2195 fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2196 let saved = self.cur().current_block;
2197 self.state().current_block = block;
2198 let result = self.hoist_list(body);
2199 // Only now is every binding of this scope known, so the deferred function
2200 // bodies can be compiled against the finished list. Compiled at its own
2201 // declaration instead, a body that names a `var` written further down would
2202 // have resolved that name as a global.
2203 if result.is_ok() {
2204 let deferred = std::mem::take(&mut self.state().deferred_funcs);
2205 let mut outcome = Ok(());
2206 for (owner, func) in deferred {
2207 let previous = self.cur().current_block;
2208 self.state().current_block = owner;
2209 outcome = self.func_decl(&func);
2210 self.state().current_block = previous;
2211 if outcome.is_err() {
2212 break;
2213 }
2214 }
2215 self.state().current_block = saved;
2216 return outcome;
2217 }
2218 // `current_block` is restored by the caller for a block statement, since
2219 // it needs it set while compiling; only clean up on the hoist path.
2220 self.state().current_block = saved;
2221 result
2222 }
2223
2224 fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2225 for stmt in body {
2226 self.hoist_stmt(stmt)?;
2227 }
2228 Ok(())
2229 }
2230
2231 /// Whether a statement always transfers control away, making everything after
2232 /// it in the same list unreachable.
2233 ///
2234 /// The reference drops such statements in `skip_dead_code`, so `return 1;
2235 /// let x = 2;` compiles to the same bytecode as `return 1;`.
2236 fn terminates(stmt: &Stmt) -> bool {
2237 matches!(
2238 stmt.kind,
2239 StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2240 )
2241 }
2242
2243 fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2244 match &stmt.kind {
2245 StmtKind::VarDecl(decl) => {
2246 for declarator in &decl.declarators {
2247 let mut names = Vec::new();
2248 declarator.target.bound_names(&mut names);
2249 for name in names {
2250 let text = name.name.clone();
2251 if decl.kind == VarDeclKind::Var {
2252 let def = VarDef::var(text.clone());
2253 self.declare_var(&text, def);
2254 } else if decl.kind.is_using() {
2255 // Two adjacent slots: the resource, then the dispose method
2256 // snapshotted at declaration. `using_dispose` reads them as a
2257 // pair `(slot, slot + 1)`, so nothing may be declared between
2258 // them — which is why both are declared here, in one step,
2259 // rather than the method being added at emission time.
2260 self.declare_using(&text);
2261 } else {
2262 let def = if decl.kind == VarDeclKind::Const {
2263 VarDef::constant(text.clone())
2264 } else {
2265 VarDef::lexical(text.clone())
2266 };
2267 self.declare(&text, def);
2268 }
2269 }
2270 }
2271 }
2272 StmtKind::FuncDecl(func) => {
2273 if let Some(name) = &func.name {
2274 // A function declaration is a `var` binding that happens to
2275 // hold a function, not a lexical one.
2276 let def = VarDef::var(name.name.clone());
2277 self.declare_var(&name.name.clone(), def);
2278 }
2279 // The function object is created when the scope is entered, so it
2280 // exists before the declaration is reached. Its body is compiled
2281 // *after* this scope's hoisting finishes, so a name it uses resolves
2282 // even when the `var` that declares it comes later in the source.
2283 let owner = self.cur().current_block;
2284 self.state().deferred_funcs.push((owner, func.clone()));
2285 }
2286 StmtKind::ClassDecl(class) => {
2287 if let Some(name) = &class.name {
2288 self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2289 }
2290 }
2291 // A module's imports are bound before any of its code runs, and its exports
2292 // declare the very bindings they export — so both hoist the declarations
2293 // their `StmtKind` arm will later emit code for.
2294 StmtKind::Import(decl) => self.hoist_import(decl)?,
2295 StmtKind::Export(decl) => self.hoist_export(decl)?,
2296 StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2297 StmtKind::If { cons, alt, .. } => {
2298 self.hoist_stmt(cons)?;
2299 if let Some(alt) = alt {
2300 self.hoist_stmt(alt)?;
2301 }
2302 }
2303 StmtKind::While { body, .. }
2304 | StmtKind::DoWhile { body, .. }
2305 | StmtKind::Labeled { body, .. }
2306 | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2307 StmtKind::For { init, body, .. } => {
2308 // A `for` head gets its own scope even when it declares nothing,
2309 // because `let` in the head is scoped to the loop.
2310 let key = stmt.span.start.offset as u64;
2311 let parent = self.cur().current_block;
2312 self.push_block(key, parent);
2313 if let Some(init) = init
2314 && let ForInit::VarDecl(decl) = init
2315 {
2316 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2317 }
2318 self.hoist_stmt(body)?;
2319 self.state().current_block = parent;
2320 }
2321 StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
2322 let key = stmt.span.start.offset as u64;
2323 let parent = self.cur().current_block;
2324 self.push_block(key, parent);
2325 if let ForHead::VarDecl(decl) = left {
2326 self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2327 }
2328 self.hoist_stmt(body)?;
2329 self.state().current_block = parent;
2330 }
2331 StmtKind::Try {
2332 block,
2333 handler,
2334 finalizer,
2335 } => {
2336 self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2337 let try_parent = self.cur().current_block;
2338 if let Some(handler) = handler {
2339 // The catch parameter belongs to the function scope, not to a
2340 // block: it is a `catch` binding rather than a `let`, so it is
2341 // never in the temporal dead zone and `emit_scope_enter` must
2342 // not mark it uninitialised. It still has to be declared before
2343 // the handler body is hoisted, so it takes the slot the
2344 // reference gives it (bindings are numbered in source order).
2345 if let Some(pattern) = &handler.param {
2346 // The parameter gets its own scope, so entering the handler
2347 // does not have to re-declare it. It is not lexical, so it
2348 // is never marked uninitialised.
2349 let key = Self::try_block_key(stmt, TryPart::Param);
2350 let parent = self.cur().current_block;
2351 self.push_block(key, parent);
2352 // A destructuring parameter binds several names, one slot each,
2353 // in the order they are written. The reference declares those as
2354 // `let`s rather than as one `catch` binding — its dump prints
2355 // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2356 // so the kind follows the shape of the parameter.
2357 //
2358 // Neither form is in the dead zone: the stores run as the handler
2359 // is entered, so both use the unchecked `put_loc`.
2360 let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2361 let mut names = Vec::new();
2362 pattern.bound_names(&mut names);
2363 for name in names {
2364 let def = VarDef {
2365 name: name.name.clone(),
2366 is_const: false,
2367 is_lexical: destructures,
2368 kind: if destructures {
2369 crate::bytecode::VarKind::LexicalCatch
2370 } else {
2371 crate::bytecode::VarKind::Catch
2372 },
2373 is_captured: false,
2374 scope_level: 0,
2375 scope_next: None,
2376 };
2377 self.declare_local(&name.name.clone(), def);
2378 }
2379 // The handler body nests inside the parameter's scope, so the
2380 // body's bindings chain on to the parameter (the reference
2381 // prints `let y [next:1]`, pointing at `e`).
2382 self.state().current_block = key;
2383 }
2384 self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2385 // Back to the block the `try` itself lives in, so the finalizer
2386 // is a sibling of the handler rather than nested in it.
2387 self.state().current_block = try_parent;
2388 }
2389 if let Some(finalizer) = finalizer {
2390 self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2391 }
2392 }
2393 StmtKind::Switch { cases, .. } => {
2394 let key = stmt.span.start.offset as u64;
2395 let parent = self.cur().current_block;
2396 self.push_block(key, parent);
2397 for case in cases {
2398 self.hoist_list(&case.body)?;
2399 }
2400 self.state().current_block = parent;
2401 }
2402 _ => {}
2403 }
2404 Ok(())
2405 }
2406
2407 /// Hoist a nested statement list, which is its own lexical scope.
2408 fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2409 let parent = self.cur().current_block;
2410 self.push_block(key, parent);
2411 self.hoist_list(body)?;
2412 self.state().current_block = parent;
2413 Ok(())
2414 }
2415
2416 /// A block key for one part of a `try` statement.
2417 ///
2418 /// The three parts are three separate scopes, so they cannot share the key a
2419 /// statement's own offset would give them: the try block, the handler body and
2420 /// the finalizer would then look like one scope, and their `let` bindings would
2421 /// be marked uninitialised only on entering the first of them.
2422 fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2423 (stmt.span.start.offset as u64) * 4 + part as u64
2424 }
2425
2426 /// Declare a `var`: it lives in the function's own scope, not the block's.
2427 fn declare_var(&mut self, name: &str, def: VarDef) {
2428 if self.cur().is_module {
2429 self.declare_module(name, &def);
2430 return;
2431 }
2432 if self.cur().declares_globally(&def) {
2433 self.declare_global(name, &def);
2434 return;
2435 }
2436 let state = self.state();
2437 // A binding of the *parameter* scope does not count: the body's `var` of the
2438 // same name is a different binding and needs a slot of its own.
2439 if state.vars.iter().enumerate().any(|(index, v)| {
2440 v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
2441 }) {
2442 return;
2443 }
2444 // A `var` belongs to the function scope, never to the enclosing block.
2445 state.var_block.push(FUNCTION_SCOPE);
2446 state.vars.push(def);
2447 }
2448
2449 /// Declare `name` as a binding of the parameter scope, returning its slot.
2450 fn declare_param_var(&mut self, name: &str) -> u32 {
2451 declare_param_var_at(self.state(), name)
2452 }
2453
2454 /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2455 ///
2456 /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2457 /// so each points at the one declared before it and the oldest ends the chain with
2458 /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2459 /// runtime walks when it instantiates them.
2460 fn declare_param_binding(&mut self, name: &str) -> u32 {
2461 let state = self.state();
2462 let previous = state
2463 .vars
2464 .iter()
2465 .enumerate()
2466 .rev()
2467 .find(|(index, var)| {
2468 state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2469 })
2470 .map(|(index, _)| index as i32);
2471 let index = state.vars.len() as u32;
2472 state.var_block.push(PARAM_SCOPE);
2473 let mut def = VarDef::lexical(name);
2474 // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2475 // the function's, and its bindings are initialised one by one rather than all at
2476 // once — which is exactly what the dead zone needs.
2477 def.scope_level = 1;
2478 def.scope_next = Some(previous.unwrap_or(-2));
2479 state.vars.push(def);
2480 index
2481 }
2482
2483 /// The slot of a parameter-list binding, if the list has one by that name.
2484 fn param_binding_slot(&self, name: &str) -> Option<u32> {
2485 let state = self.cur();
2486 state
2487 .vars
2488 .iter()
2489 .enumerate()
2490 .position(|(index, var)| {
2491 var.name == name
2492 && var.is_lexical
2493 && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2494 })
2495 .map(|index| index as u32)
2496 }
2497
2498 /// Every parameter-list binding, in declaration order.
2499 fn param_binding_names(&self) -> Vec<String> {
2500 let state = self.cur();
2501 state
2502 .vars
2503 .iter()
2504 .enumerate()
2505 .filter(|(index, var)| {
2506 var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2507 })
2508 .map(|(_, var)| var.name.clone())
2509 .collect()
2510 }
2511
2512 /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2513 fn body_var_slot(&self, name: &str) -> Option<u32> {
2514 let state = self.cur();
2515 state
2516 .vars
2517 .iter()
2518 .enumerate()
2519 .find(|(index, var)| {
2520 var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2521 })
2522 .map(|(index, _)| index as u32)
2523 }
2524
2525 /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2526 /// one.
2527 ///
2528 /// With parameter expressions the reference creates two: an unmapped one in the
2529 /// argument scope, for the defaults and anything they close over, and the body's own.
2530 /// They are separate bindings, which is what makes
2531 /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2532 /// report 1 from `p` and 2 from the body.
2533 fn provide_param_arguments(&mut self) {
2534 if !self.cur().has_parameter_expressions {
2535 return;
2536 }
2537 let mentioned = self.cur().needs_param_arguments
2538 || self
2539 .cur()
2540 .insns
2541 .iter()
2542 .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2543 if !mentioned {
2544 return;
2545 }
2546 let slot = self.declare_param_var("arguments");
2547 let magic = if self.cur().strict || !self.cur().simple_parameter_list {
2548 0
2549 } else {
2550 1
2551 };
2552 self.prepend_initialiser_to(
2553 slot,
2554 Insn::Fixed {
2555 op: Opcode::SpecialObject,
2556 operands: vec![Op::Int(magic)],
2557 },
2558 );
2559 }
2560
2561 /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2562 fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2563 let current = self.stack.len() - 1;
2564 let init = [
2565 producer,
2566 Insn::Fixed {
2567 op: Opcode::PutLoc,
2568 operands: vec![Op::Slot(Slot::Loc(slot))],
2569 },
2570 ];
2571 let inserted = init.len();
2572 for (index, instruction) in init.into_iter().enumerate() {
2573 self.stack[current].insns.insert(index, instruction);
2574 }
2575 for placed in self.stack[current].labels.iter_mut().flatten() {
2576 *placed += inserted;
2577 }
2578 self.state().label_since_insn = false;
2579 }
2580
2581 /// Give the function an `arguments` binding if its body mentions one.
2582 ///
2583 /// The check runs on the *instruction* stream rather than the AST: by this point
2584 /// every reference has become an `Insn::Var`, so scanning is exact and needs no
2585 /// AST walker. Declaring lazily matters for more than tidiness — always declaring
2586 /// would renumber every later local slot and stop the bytecode matching the
2587 /// reference, which only adds the binding when the body uses it.
2588 ///
2589 /// `arguments` is a local, initialised at the top of the body by
2590 /// `special_object`; that is the reference's shape, so the disassembly agrees.
2591 fn provide_arguments(&mut self) {
2592 let current = self.stack.len() - 1;
2593 if self.stack[current].is_script || self.stack[current].is_module {
2594 // A module has no `arguments` binding; referring to it is a ReferenceError,
2595 // which is exactly what an unbound name produces.
2596 return;
2597 }
2598 // An arrow has no `arguments` of its own: the binding belongs to the enclosing
2599 // function, which is why `() => arguments` sees the caller's arguments.
2600 if self.stack[current].is_arrow {
2601 if self.mentions("arguments") {
2602 self.ensure_enclosing_arguments();
2603 }
2604 return;
2605 }
2606 // Only a *body* mention needs the body's binding: the parameter list has one of
2607 // its own (see [`Compiler::provide_param_arguments`]).
2608 //
2609 // `delete arguments` counts too: it compiles to `DeleteVar`, which is not a
2610 // `Var`, so without this the body got no binding at all — the name resolved to
2611 // the global object and `delete` answered `true` for a binding that cannot be
2612 // deleted. The reference answers `false`.
2613 let mentioned = self.cur().insns.iter().any(|insn| match insn {
2614 Insn::Var {
2615 name, in_params, ..
2616 } => name == "arguments" && !*in_params,
2617 Insn::DeleteVar { name } => name == "arguments",
2618 _ => false,
2619 });
2620 // A mention that resolves to the body's *own* lexical `arguments` is not a request
2621 // for the implicit one — `function f(p = 1) { let arguments; }` shadows it, and the
2622 // implicit binding is not created at all. Providing it anyway was worse than useless:
2623 // its prologue store resolved past the shadowing `let` and landed on the **global**,
2624 // so `function f(p = eval("var arguments")) { let arguments; }` defined
2625 // `globalThis.arguments` as a side effect (`globalThis.arguments unchanged` in
2626 // test262's `fn-body-cntns-arguments-lex-bind` family).
2627 //
2628 // Lexical only. `var arguments = 1` in the body is a different thing entirely: the
2629 // var *is* the binding, and the implicit arguments object is initialised into it at
2630 // entry, which is why `function f(){ return typeof arguments; var arguments = 1 }`
2631 // answers `"object"` (`S13_A15_T4`). Suppressing the prologue for those two made
2632 // `typeof arguments` `"undefined"`.
2633 if self
2634 .cur()
2635 .vars
2636 .iter()
2637 .any(|var| var.name == "arguments" && var.needs_check())
2638 {
2639 return;
2640 }
2641 if !mentioned && !self.cur().needs_arguments_local {
2642 return;
2643 }
2644 // The request may have come only from a parameter-list arrow, in which case the
2645 // parameter scope's binding already answers for it and the body needs none.
2646 if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
2647 return;
2648 }
2649 // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`.
2650 //
2651 // With parameter expressions the list and the body are separate environments, so
2652 // an assignment to a parameter cannot be reflected into `arguments` at all — the
2653 // arguments object is unmapped whatever the mode, which is why the reference emits
2654 // `special_object 0` here even in sloppy code.
2655 // A non-simple parameter list (`[a]`, `...rest`, `a = 1`) makes the arguments
2656 // object unmapped whatever the mode — §10.4.4 keys the decision on
2657 // `IsSimpleParameterList`, not on strictness alone.
2658 let magic = if self.stack[current].strict || !self.stack[current].simple_parameter_list {
2659 0
2660 } else {
2661 1
2662 };
2663 // A mapped `arguments` shares storage with the parameters: `arguments[0] = 2`
2664 // has to be visible as `a`, and assigning `a` has to be visible as `arguments[0]`.
2665 // The only storage both sides can see is a reference cell, so every parameter the
2666 // object maps gets one — even a parameter no closure captured. Without this the
2667 // slot holds a plain copy and the mapping has nothing to write through.
2668 if magic == 1 {
2669 for arg in &mut self.stack[current].args {
2670 arg.is_captured = true;
2671 }
2672 }
2673 self.prepend_binding("arguments", magic);
2674 }
2675
2676 /// Whether a *body* instruction refers to `arguments`.
2677 fn body_mentions_arguments(&self) -> bool {
2678 self.cur()
2679 .insns
2680 .iter()
2681 .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
2682 }
2683
2684 /// Whether the function body's instruction stream refers to `name`.
2685 fn mentions(&self, name: &str) -> bool {
2686 let current = self.stack.len() - 1;
2687 // A binding of the parameter scope does not answer for the body: the body's own
2688 // `arguments` (or self-name) still has to be provided for it.
2689 if self.stack[current]
2690 .vars
2691 .iter()
2692 .enumerate()
2693 .any(|(index, v)| {
2694 v.name == name
2695 && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
2696 })
2697 {
2698 return false;
2699 }
2700 self.stack[current]
2701 .insns
2702 .iter()
2703 .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
2704 }
2705
2706 /// Bind the name a named function expression uses to refer to itself.
2707 ///
2708 /// The value is `special_object 2`, the function currently running, so the binding
2709 /// is the closure itself and not a copy. It is a local of this function, which is
2710 /// what keeps `g` out of the enclosing scope.
2711 /// Give the function a local `this`, for an arrow inside it to capture.
2712 fn provide_this_local(&mut self) {
2713 let current = self.stack.len() - 1;
2714 if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
2715 return;
2716 }
2717 if !self.stack[current]
2718 .vars
2719 .iter()
2720 .any(|var| var.name == "this")
2721 {
2722 self.declare_hidden_local("this", VarKind::Normal);
2723 }
2724 self.prepend_initialiser(
2725 "this",
2726 Insn::Fixed {
2727 op: Opcode::PushThis,
2728 operands: vec![],
2729 },
2730 );
2731 }
2732
2733 /// Give the function a local `<home_object>`, for an arrow or a static block inside it
2734 /// to read through `super`.
2735 fn provide_home_object_local(&mut self) {
2736 let current = self.stack.len() - 1;
2737 if !self.stack[current].needs_home_object_local {
2738 return;
2739 }
2740 if !self.stack[current]
2741 .vars
2742 .iter()
2743 .any(|var| var.name == HOME_OBJECT)
2744 {
2745 self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
2746 }
2747 self.prepend_initialiser(
2748 HOME_OBJECT,
2749 Insn::Fixed {
2750 op: Opcode::SpecialObject,
2751 operands: vec![Op::Int(4)],
2752 },
2753 );
2754 }
2755
2756 fn provide_self_name(&mut self) {
2757 let current = self.stack.len() - 1;
2758 let Some(name) = self.stack[current].self_name.clone() else {
2759 return;
2760 };
2761 if self.stack[current].self_name_initialized {
2762 return;
2763 }
2764 // Either the body refers to the name, or a nested function already forced the
2765 // binding into existence while being resolved. A direct `eval` can name it
2766 // without mentioning it, so its presence is a third reason: in strict mode
2767 // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
2768 // that only happens if the binding exists.
2769 let declared = self.stack[current].vars.iter().any(|v| v.name == name);
2770 if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
2771 return;
2772 }
2773 self.stack[current].self_name_initialized = true;
2774 self.prepend_binding_with(&name, 2, VarKind::FunctionName);
2775 }
2776
2777 /// Insert `special_object magic` plus the store to `name` at the top of the body.
2778 ///
2779 /// Prepending shifts every label that has been placed, so they are all moved by
2780 /// the number of instructions inserted.
2781 fn prepend_binding(&mut self, name: &str, magic: i32) {
2782 self.prepend_binding_with(name, magic, VarKind::Normal);
2783 }
2784
2785 /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
2786 fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
2787 let current = self.stack.len() - 1;
2788 // A function-expression's own name is immutable in strict mode, which is what
2789 // makes `f = 1` inside a strict body throw instead of being dropped.
2790 let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
2791 self.declare_var(
2792 name,
2793 VarDef {
2794 kind,
2795 is_const,
2796 ..VarDef::var(name)
2797 },
2798 );
2799 let init = [
2800 Insn::Fixed {
2801 op: Opcode::SpecialObject,
2802 operands: vec![Op::Int(magic)],
2803 },
2804 Insn::Var {
2805 // An initialisation, not an assignment: sloppy mode drops stores to a
2806 // function-expression's own name, and the prologue is what puts the
2807 // value there in the first place.
2808 action: if kind == VarKind::FunctionName {
2809 VarAction::PutInit
2810 } else {
2811 VarAction::Put
2812 },
2813 name: name.to_string(),
2814 block: 0,
2815 in_params: false,
2816 },
2817 ];
2818 let inserted = init.len();
2819 for (index, instruction) in init.into_iter().enumerate() {
2820 self.stack[current].insns.insert(index, instruction);
2821 }
2822 for placed in self.stack[current].labels.iter_mut().flatten() {
2823 *placed += inserted;
2824 }
2825 // A store sits at the insertion point now, so the `put`/`get` fold must not
2826 // reach across it.
2827 self.stack[current].label_since_insn = true;
2828 }
2829
2830 /// Record a top-level script declaration as a global.
2831 ///
2832 /// A script's top-level `var`/`let`/`function` create properties of the
2833 /// global object, not slots in the script's frame, so they show up as closure
2834 /// variables instead.
2835 fn declare_global(&mut self, name: &str, def: &VarDef) {
2836 let state = self.state();
2837 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2838 // The name was already referenced, from a function compiled before this
2839 // declaration was reached — `function a(){ b() } function b(){}` resolves
2840 // `b` while `b` is still unknown, and that guess has to be corrected here.
2841 // Leaving it as a plain global meant the declaration was never registered,
2842 // so the binding did not exist at run time and `a()` threw
2843 // `b is not defined`.
2844 if matches!(existing.closure_type, ClosureType::Global) {
2845 existing.closure_type = ClosureType::GlobalDecl;
2846 existing.is_const = def.is_const;
2847 existing.is_lexical = def.is_lexical;
2848 }
2849 return;
2850 }
2851 state.closure_vars.push(ClosureVar {
2852 name: name.to_string(),
2853 is_const: def.is_const,
2854 is_lexical: def.is_lexical,
2855 closure_type: ClosureType::GlobalDecl,
2856 var_idx: 0,
2857 });
2858 }
2859
2860 /// Record a module-level declaration as a module variable.
2861 ///
2862 /// The binding is a closure variable of the module body, so reads and writes are
2863 /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
2864 /// *who fills the cell*: the module record does, before the body runs, and an import
2865 /// points its cell at the exporting module's, which is what makes bindings live and
2866 /// cycles work.
2867 fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
2868 let state = self.state();
2869 if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2870 // The name may have been referenced before this declaration was hoisted,
2871 // which resolved it as a plain global. Correct that here, the way
2872 // `declare_global` does.
2873 if matches!(existing.closure_type, ClosureType::Global) {
2874 existing.closure_type = ClosureType::ModuleDecl;
2875 existing.is_const = def.is_const;
2876 existing.is_lexical = def.is_lexical;
2877 }
2878 return 0;
2879 }
2880 state.closure_vars.push(ClosureVar {
2881 name: name.to_string(),
2882 is_const: def.is_const,
2883 is_lexical: def.is_lexical,
2884 closure_type: ClosureType::ModuleDecl,
2885 var_idx: 0,
2886 });
2887 0
2888 }
2889
2890 /// Declare a module variable and answer its closure-variable index.
2891 ///
2892 /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
2893 /// module variable is not one. The import table needs the real index instead, because
2894 /// that is the position the host writes the cell into.
2895 fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
2896 self.declare_module(name, def);
2897 self.cur()
2898 .closure_vars
2899 .iter()
2900 .position(|c| c.name == name)
2901 .map(|index| index as u32)
2902 .unwrap_or(0)
2903 }
2904
2905 /// Declare one imported binding as a module variable.
2906 ///
2907 /// Returns the closure-variable index, which is what the import table records: the
2908 /// host writes the exporter's cell into that slot before the body runs.
2909 fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
2910 let state = self.state();
2911 if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
2912 // Keep the slot, fix the kind: the name may already have been referenced.
2913 state.closure_vars[index].closure_type = ClosureType::ModuleImport;
2914 state.closure_vars[index].is_const = is_const;
2915 return index as u32;
2916 }
2917 state.closure_vars.push(ClosureVar {
2918 name: name.to_string(),
2919 // An imported binding cannot be assigned: `x = 1` on an import is a
2920 // `TypeError` at run time, which the const flag is what produces.
2921 is_const: true,
2922 // Lexical, so reads go through `get_var_ref_check`: before linking has filled
2923 // the cell an import is in its dead zone, and reading it there must say so
2924 // rather than answer `undefined`.
2925 is_lexical: true,
2926 closure_type: ClosureType::ModuleImport,
2927 var_idx: 0,
2928 });
2929 state.closure_vars.len() as u32 - 1
2930 }
2931
2932 /// Emit the code an `export` needs.
2933 ///
2934 /// Only `export default <expr>` has any: everything else is a table entry whose
2935 /// binding is declared elsewhere. The expression is stored into the hidden
2936 /// `*default*` variable rather than returned, because the module body has no value
2937 /// to speak of.
2938 fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2939 match &decl.kind {
2940 ExportKind::Declaration(stmt) => self.stmt(stmt),
2941 ExportKind::Default(expr) => {
2942 // `export default class Foo {}`: evaluate the declaration (which binds
2943 // `Foo`), then copy its value into the hidden `*default*` binding, because a
2944 // class declaration is a *statement* and `expr` cannot be compiled as one.
2945 if let ExprKind::Class(class) = &expr.kind
2946 && class.name.is_some()
2947 {
2948 self.stmt(&Stmt {
2949 kind: StmtKind::ClassDecl(class.clone()),
2950 span: expr.span,
2951 })?;
2952 let Some(name) = &class.name else {
2953 return Ok(());
2954 };
2955 self.emit_var(VarAction::Get, &name.name);
2956 let index = self.declare_export_default();
2957 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
2958 return Ok(());
2959 }
2960 // A named default function/class is already a module binding; the export
2961 // points at it and there is nothing to evaluate.
2962 if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some()) {
2963 return Ok(());
2964 }
2965 self.expr(expr)?;
2966 // §16.2.1.10 step 1.b: an *anonymous* default export is named `"default"`
2967 // by `SetFunctionName`, exactly as `var f = function(){}` is named `f`. The
2968 // name is observable — `imported.default.name` — and without this an
2969 // anonymous `export default class {}` arrived with the empty name.
2970 self.set_name_if_anonymous(expr, &Wtf8::new("default"));
2971 let index = self.declare_export_default();
2972 self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
2973 Ok(())
2974 }
2975 ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
2976 }
2977 }
2978
2979 /// A module name as the string it denotes.
2980 fn module_name_text(name: &ModuleName) -> &str {
2981 match name {
2982 ModuleName::Ident(ident) => &ident.name,
2983 ModuleName::Str(text) => text,
2984 }
2985 }
2986
2987 /// Bind `import`'s local names and record where each one comes from.
2988 ///
2989 /// Nothing is emitted: an import is not an instruction, it is a promise that the
2990 /// binding's cell will be filled before the body runs. The cell lands in the module's
2991 /// environment at a fixed index, and the host fills it from the exporter's cell —
2992 /// which is why a cyclic import can bind before the other module has evaluated.
2993 fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
2994 let request = self.module_request(&decl.source, &decl.attributes);
2995 for specifier in &decl.specifiers {
2996 let (local, name, is_star) = match specifier {
2997 ImportSpecifier::Default(ident) => {
2998 (ident.name.clone(), "default".to_string(), false)
2999 }
3000 ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
3001 ImportSpecifier::Named { imported, local } => (
3002 local.name.clone(),
3003 Self::module_name_text(imported).to_string(),
3004 false,
3005 ),
3006 };
3007 // `import * as ns` is *not* a live binding of another module's variable —
3008 // it is a value of its own, which is why the reference declares it like a
3009 // module variable and the host stores the namespace object in that cell.
3010 let var_idx = if is_star {
3011 // `const`: a namespace object is a value, and the binding is immutable.
3012 self.declare_module_var(&local, &VarDef::constant(local.clone()))
3013 } else {
3014 self.declare_import(&local, true)
3015 };
3016 self.module_meta().imports.push(ImportEntry {
3017 module: request,
3018 name,
3019 var_idx,
3020 is_star,
3021 });
3022 }
3023 Ok(())
3024 }
3025
3026 /// Record what an `export` offers, declaring the binding it exports.
3027 ///
3028 /// `export var x = 1` is a declaration like any other; only the table entry is extra.
3029 fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3030 match &decl.kind {
3031 ExportKind::Declaration(stmt) => {
3032 // The inner declaration keeps its own hoisting, then every name it binds
3033 // becomes an export of the same name.
3034 self.hoist_stmt(stmt)?;
3035 let mut names = Vec::new();
3036 Self::declared_names(stmt, &mut names);
3037 for name in names {
3038 let var_idx = self.module_binding_index(&name);
3039 self.exports_local(&name, var_idx);
3040 }
3041 }
3042 ExportKind::Default(expr) => {
3043 // The reference puts a default export in a hidden `*default*` variable,
3044 // so `export default function f(){}` can export a *value* while `f` stays
3045 // a binding of the module.
3046 if let ExprKind::Function(func) = &expr.kind
3047 && let Some(name) = &func.name
3048 {
3049 let text = name.name.clone();
3050 self.hoist_stmt(&Stmt {
3051 kind: StmtKind::FuncDecl(func.clone()),
3052 span: expr.span,
3053 })?;
3054 let var_idx = self.module_binding_index(&text);
3055 self.module_meta().exports.push(ExportEntry::Local {
3056 export_name: "default".to_string(),
3057 var_idx,
3058 });
3059 return Ok(());
3060 }
3061 if let ExprKind::Class(class) = &expr.kind
3062 && class.name.is_some()
3063 {
3064 // `export default class Foo {}` binds `Foo` in the module scope **and**
3065 // stores the class into the hidden `*default*` binding — it is a
3066 // declaration *and* a value, unlike `export default class {}` which is
3067 // only a value.
3068 //
3069 // Pointing the `default` export straight at `Foo` looked simpler and was
3070 // wrong twice over: `module_binding_index` did not find the lexical
3071 // binding the hoist had just made, so it declared a second one that
3072 // nothing ever wrote, and `export_stmt` then had no code to emit for the
3073 // declaration either. `imported.default` came out `undefined` and `Foo`
3074 // was not in scope inside its own module.
3075 self.hoist_stmt(&Stmt {
3076 kind: StmtKind::ClassDecl(class.clone()),
3077 span: expr.span,
3078 })?;
3079 let var_idx = self.declare_export_default();
3080 self.exports_local("default", var_idx);
3081 return Ok(());
3082 }
3083 let var_idx = self.declare_export_default();
3084 self.module_meta().exports.push(ExportEntry::Local {
3085 export_name: "default".to_string(),
3086 var_idx,
3087 });
3088 }
3089 ExportKind::Named {
3090 specifiers,
3091 source,
3092 attributes,
3093 } => match source {
3094 Some(source) => {
3095 let request = self.module_request(source, attributes);
3096 for specifier in specifiers {
3097 self.module_meta().exports.push(ExportEntry::Indirect {
3098 export_name: Self::module_name_text(&specifier.exported).to_string(),
3099 module: request,
3100 import_name: Self::module_name_text(&specifier.local).to_string(),
3101 });
3102 }
3103 }
3104 None => {
3105 for specifier in specifiers {
3106 let local = Self::module_name_text(&specifier.local).to_string();
3107 let export_name = Self::module_name_text(&specifier.exported).to_string();
3108 // `export { x }` where `x` is itself an **import** re-exports the
3109 // binding the import names, not a binding of this module
3110 // (§16.2.1.6.3: a local export whose local name is imported resolves
3111 // through the imported module). Recording it as a local made two
3112 // modules that both forward one import look like two different
3113 // bindings, and the name was reported ambiguous
3114 // (`import-and-export-propagates-binding`;
3115 // `namespace-unambiguous-if-import-star-as-and-export`).
3116 let closure_names: Vec<String> = self
3117 .cur()
3118 .closure_vars
3119 .iter()
3120 .map(|var| var.name.clone())
3121 .collect();
3122 let forwarded = self
3123 .module_meta()
3124 .imports
3125 .iter()
3126 .filter(|entry| {
3127 closure_names
3128 .get(entry.var_idx as usize)
3129 .is_some_and(|name| *name == local)
3130 })
3131 .map(|entry| (entry.module, entry.name.clone(), entry.is_star))
3132 .find(|(_, name, is_star)| !is_star || name.is_empty());
3133 if let Some((request, name, is_star)) = forwarded {
3134 // A namespace import has no export *name* of its own; the
3135 // resolution is `{ [[Module]]: m, [[BindingName]]: namespace }`,
3136 // which is what the marker below records.
3137 let import_name = if is_star {
3138 "*namespace*".to_string()
3139 } else {
3140 name
3141 };
3142 self.module_meta().exports.push(ExportEntry::Indirect {
3143 export_name,
3144 module: request,
3145 import_name,
3146 });
3147 continue;
3148 }
3149 let var_idx = self.module_binding_index(&local);
3150 self.module_meta().exports.push(ExportEntry::Local {
3151 export_name,
3152 var_idx,
3153 });
3154 }
3155 }
3156 },
3157 ExportKind::All {
3158 source,
3159 exported,
3160 attributes,
3161 } => {
3162 let request = self.module_request(source, attributes);
3163 match exported {
3164 Some(name) => {
3165 self.module_meta().exports.push(ExportEntry::StarAs {
3166 export_name: Self::module_name_text(name).to_string(),
3167 module: request,
3168 });
3169 }
3170 None => {
3171 self.module_meta()
3172 .exports
3173 .push(ExportEntry::Star { module: request });
3174 }
3175 }
3176 }
3177 }
3178 Ok(())
3179 }
3180
3181 /// The names a declaration binds, which is what `export <decl>` exports.
3182 fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
3183 match &stmt.kind {
3184 StmtKind::VarDecl(decl) => {
3185 for declarator in &decl.declarators {
3186 let mut names = Vec::new();
3187 declarator.target.bound_names(&mut names);
3188 out.extend(names.into_iter().map(|name| name.name));
3189 }
3190 }
3191 StmtKind::FuncDecl(func) => {
3192 if let Some(name) = &func.name {
3193 out.push(name.name.clone());
3194 }
3195 }
3196 StmtKind::ClassDecl(class) => {
3197 if let Some(name) = &class.name {
3198 out.push(name.name.clone());
3199 }
3200 }
3201 _ => {}
3202 }
3203 }
3204
3205 /// The closure-variable index of a module binding, declaring it if the name was
3206 /// exported without being declared here.
3207 ///
3208 /// `export { x }` where `x` is not declared in the module is a link-time
3209 /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
3210 fn module_binding_index(&mut self, name: &str) -> u32 {
3211 if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
3212 return index as u32;
3213 }
3214 self.declare_module_var(name, &VarDef::lexical(name.to_string()))
3215 }
3216
3217 fn exports_local(&mut self, export_name: &str, var_idx: u32) {
3218 self.module_meta().exports.push(ExportEntry::Local {
3219 export_name: export_name.to_string(),
3220 var_idx,
3221 });
3222 }
3223
3224 /// The hidden `*default*` binding `export default <expr>` stores into.
3225 fn declare_export_default(&mut self) -> u32 {
3226 const DEFAULT: &str = "*default*";
3227 if let Some(index) = self
3228 .cur()
3229 .closure_vars
3230 .iter()
3231 .position(|c| c.name == DEFAULT)
3232 {
3233 return index as u32;
3234 }
3235 self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
3236 }
3237
3238 /// The module tables, which only the top-level state has.
3239 fn module_meta(&mut self) -> &mut ModuleMeta {
3240 self.state()
3241 .module
3242 .as_mut()
3243 .expect("module tables are only touched while compiling a module")
3244 }
3245
3246 /// The index of `specifier`'s request, adding it if it is new.
3247 ///
3248 /// Deduplicated on the specifier *and* its attributes: the same file imported once as
3249 /// JSON and once as text is two modules with two different contents, which is exactly
3250 /// what `hello_module.js` does.
3251 fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
3252 let attributes: Vec<(String, String)> = attributes
3253 .iter()
3254 .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
3255 .collect();
3256 let meta = self.module_meta();
3257 if let Some(index) = meta
3258 .requests
3259 .iter()
3260 .position(|request| request.specifier == specifier && request.attributes == attributes)
3261 {
3262 return index as u32;
3263 }
3264 meta.requests.push(ModuleRequest {
3265 specifier: specifier.to_string(),
3266 attributes,
3267 });
3268 meta.requests.len() as u32 - 1
3269 }
3270
3271 /// Compile a loop body with a `break`/`continue` target pushed for it.
3272 fn loop_body(
3273 &mut self,
3274 body: &Stmt,
3275 labels: &[String],
3276 continue_label: Label,
3277 break_label: Label,
3278 ) -> Result<(), SyntaxError> {
3279 self.push_jump_target(JumpTarget {
3280 names: labels.to_vec(),
3281 break_label: Some(break_label),
3282 continue_label: Some(continue_label),
3283 // A loop leaves nothing of its own on the value stack.
3284 drop_count: 0,
3285 finally_label: None,
3286 is_regular_stmt: false,
3287 has_iterator: false,
3288 is_async_iterator: false,
3289 });
3290 let result = self.stmt(body);
3291 self.pop_jump_target();
3292 result
3293 }
3294
3295 fn push_jump_target(&mut self, target: JumpTarget) {
3296 self.state().jump_targets.push(target);
3297 }
3298
3299 fn pop_jump_target(&mut self) {
3300 self.state().jump_targets.pop();
3301 }
3302
3303 fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3304 let (label, is_break) = match &stmt.kind {
3305 StmtKind::Break(label) => (label.as_ref(), true),
3306 StmtKind::Continue(label) => (label.as_ref(), false),
3307 _ => unreachable!("control_transfer is only called for break and continue"),
3308 };
3309
3310 // Walk outward from the innermost construct. Everything considered before
3311 // the match is a construct control is leaving, and leaving it has a cost:
3312 // its stack slots go, and its finalizer runs.
3313 let targets = self.cur().jump_targets.clone();
3314 for target in targets.iter().rev() {
3315 let destination = match (label, is_break) {
3316 // An unlabelled `break` skips a labelled non-loop statement: `break`
3317 // may name one, but the bare form only means "leave the loop".
3318 (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3319 (None, false) => target.continue_label,
3320 (Some(name), true) => target
3321 .break_label
3322 .filter(|_| target.names.contains(&name.name)),
3323 (Some(name), false) => target
3324 .continue_label
3325 .filter(|_| target.names.contains(&name.name)),
3326 };
3327
3328 if let Some(destination) = destination {
3329 self.emit_jump(Opcode::Goto, destination, &[]);
3330 return Ok(());
3331 }
3332
3333 // Closing the iterator consumes the three slots the loop keeps on the
3334 // stack (iterator, next method, catch offset), so those are not dropped
3335 // again below.
3336 let mut remaining = target.drop_count;
3337 if target.has_iterator {
3338 self.emit_iterator_close(target.is_async_iterator, false);
3339 remaining = remaining.saturating_sub(3);
3340 }
3341 for _ in 0..remaining {
3342 self.emit(Opcode::Drop, &[]);
3343 }
3344 if let Some(finally) = target.finally_label {
3345 // The finalizer runs as a subroutine and is handed a dummy return
3346 // value, which is dropped afterwards to keep the stack the depth it
3347 // had before.
3348 self.emit(Opcode::Undefined, &[]);
3349 self.emit_jump(Opcode::Gosub, finally, &[]);
3350 self.emit(Opcode::Drop, &[]);
3351 }
3352 }
3353
3354 // The parser rejects a break/continue with no target, so reaching here
3355 // means the compiler's own bookkeeping is wrong.
3356 Err(SyntaxError::new(
3357 if is_break {
3358 "break has no enclosing loop or switch"
3359 } else {
3360 "continue has no enclosing loop"
3361 },
3362 stmt.span,
3363 ))
3364 }
3365
3366 /// Compile a labelled statement.
3367 ///
3368 /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3369 /// that loop's targets, so the chain is collected and handed to the loop. A
3370 /// label on a non-loop statement only provides a `break` target, because
3371 /// `continue` may not target it.
3372 fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3373 let mut names = vec![label.name.clone()];
3374 let mut inner = body;
3375 while let StmtKind::Labeled {
3376 label: next,
3377 body: deeper,
3378 } = &inner.kind
3379 {
3380 names.push(next.name.clone());
3381 inner = deeper;
3382 }
3383 if Self::is_loop(inner) {
3384 return self.stmt_labelled(inner, &names);
3385 }
3386 let end = self.new_label();
3387 self.push_jump_target(JumpTarget {
3388 names,
3389 break_label: Some(end),
3390 continue_label: None,
3391 drop_count: 0,
3392 finally_label: None,
3393 is_regular_stmt: true,
3394 has_iterator: false,
3395 is_async_iterator: false,
3396 });
3397 let result = self.stmt(inner);
3398 self.pop_jump_target();
3399 result?;
3400 self.place_label(end);
3401 let _ = stmt;
3402 Ok(())
3403 }
3404
3405 /// Whether a statement is a loop, i.e. a valid target for `continue`.
3406 fn is_loop(stmt: &Stmt) -> bool {
3407 matches!(
3408 stmt.kind,
3409 StmtKind::While { .. }
3410 | StmtKind::DoWhile { .. }
3411 | StmtKind::For { .. }
3412 | StmtKind::ForIn { .. }
3413 | StmtKind::ForOf { .. }
3414 )
3415 }
3416
3417 /// Compile `switch`.
3418 ///
3419 /// The discriminant is evaluated once and stays on the value stack while the
3420 /// clauses compare against copies of it, so it is dropped at the end — which is
3421 /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3422 /// clause's body jumps over the *next* clause's tests straight into its body.
3423 ///
3424 /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3425 /// the next run's tests. Only the last run's miss reaches the `default` body, or
3426 /// the end of the switch when there is no `default`. That failure path can point
3427 /// backwards (`default` written first), so the runs and their labels are worked
3428 /// out before any code is emitted.
3429 fn switch(
3430 &mut self,
3431 discriminant: &Expr,
3432 cases: &[SwitchCase],
3433 stmt: &Stmt,
3434 ) -> Result<(), SyntaxError> {
3435 self.reset_value();
3436 // The discriminant is evaluated outside the switch's block scope, before
3437 // any `case` clause exists.
3438 self.expr(discriminant)?;
3439
3440 let switch_key = stmt.span.start.offset as u64;
3441 let switch_parent = self.cur().current_block;
3442 self.push_block(switch_key, switch_parent);
3443 self.emit_scope_enter(switch_key);
3444
3445 let break_label = self.new_label();
3446 self.push_jump_target(JumpTarget {
3447 names: Vec::new(),
3448 break_label: Some(break_label),
3449 // `switch` is a valid `break` target but not a `continue` target.
3450 continue_label: None,
3451 // The discriminant stays on the value stack for the whole statement, so
3452 // a `break` aimed further out has to discard it.
3453 drop_count: 1,
3454 finally_label: None,
3455 is_regular_stmt: false,
3456 has_iterator: false,
3457 is_async_iterator: false,
3458 });
3459
3460 // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3461 // its label to the clause after it, so both tests reach the same body.
3462 let mut runs: Vec<(usize, usize)> = Vec::new();
3463 let mut scan = 0;
3464 while scan < cases.len() {
3465 if cases[scan].test.is_some() {
3466 let mut last = scan;
3467 while last + 1 < cases.len()
3468 && cases[last].test.is_some()
3469 && cases[last].body.is_empty()
3470 && cases[last + 1].test.is_some()
3471 {
3472 last += 1;
3473 }
3474 runs.push((scan, last));
3475 scan = last + 1;
3476 } else {
3477 scan += 1;
3478 }
3479 }
3480
3481 let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3482 let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3483 let default_at = cases.iter().position(|case| case.test.is_none());
3484 // Where the last run sends control when nothing matched.
3485 let miss_target = match default_at {
3486 Some(index) => body_labels[index],
3487 None => break_label,
3488 };
3489
3490 // When `default` comes first, control has to jump over it to reach the
3491 // tests. It only needs to when some clause actually has a test; otherwise
3492 // the default body is the entry point.
3493 let mut entry = None;
3494 if default_at == Some(0) && !runs.is_empty() {
3495 self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3496 entry = Some(run_labels[0]);
3497 }
3498
3499 let mut index = 0;
3500 let mut run = 0;
3501 let result = (|| -> Result<(), SyntaxError> {
3502 while index < cases.len() {
3503 if cases[index].test.is_some() {
3504 let (first, last) = runs[run];
3505 // Reaching these tests from the preceding body is a
3506 // fallthrough, which continues inside the body and skips them.
3507 if index > 0 {
3508 self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3509 }
3510 if let Some(label) = entry.take() {
3511 self.place_label(label);
3512 }
3513 self.place_label(run_labels[run]);
3514
3515 for (offset, case) in cases[first..=last].iter().enumerate() {
3516 let test = case.test.as_ref().unwrap();
3517 self.emit(Opcode::Dup, &[]);
3518 self.expr(test)?;
3519 self.emit(Opcode::StrictEq, &[]);
3520 if first + offset < last {
3521 self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3522 } else {
3523 // Hand over to the next run's tests, or give up.
3524 let next = match runs.get(run + 1) {
3525 Some(_) => run_labels[run + 1],
3526 None => miss_target,
3527 };
3528 self.emit_jump(Opcode::IfFalse, next, &[]);
3529 }
3530 }
3531
3532 self.place_label(body_labels[index]);
3533 for case in &cases[first..=last] {
3534 self.stmts(&case.body)?;
3535 }
3536 index = last + 1;
3537 run += 1;
3538 } else {
3539 // `default`: control arrives here either by falling through or
3540 // because every test missed.
3541 self.place_label(body_labels[index]);
3542 self.stmts(&cases[index].body)?;
3543 index += 1;
3544 }
3545 }
3546 Ok(())
3547 })();
3548
3549 if result.is_ok() {
3550 self.place_label(break_label);
3551 // Discard the discriminant now that no test needs it.
3552 self.emit(Opcode::Drop, &[]);
3553 }
3554
3555 self.pop_jump_target();
3556 self.emit_scope_leave(switch_key);
3557 self.state().current_block = switch_parent;
3558 result
3559 }
3560
3561 /// Compile `try`/`catch`/`finally`.
3562 ///
3563 /// The shape is an exception table built out of `catch` instructions, each of
3564 /// which records where control goes if the instructions that follow raise:
3565 ///
3566 /// ```text
3567 /// catch HANDLER <- if the guarded block throws, jump to HANDLER
3568 /// <guarded block>
3569 /// drop <- discard the catch offset
3570 /// undefined; gosub FINALLY; drop
3571 /// goto END
3572 /// HANDLER:
3573 /// <bind the catch parameter>
3574 /// catch CATCH2 <- if the handler itself throws, go to CATCH2
3575 /// <handler body>
3576 /// drop; undefined; gosub FINALLY; drop; goto END
3577 /// CATCH2:
3578 /// gosub FINALLY; throw <- run the finalizer, then let the error out
3579 /// FINALLY:
3580 /// <finalizer>
3581 /// ret <- return to the `gosub`
3582 /// END:
3583 /// ```
3584 ///
3585 /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
3586 /// of the finalizer serves the normal path, the handler path and the
3587 /// propagating-exception path.
3588 ///
3589 /// The `undefined` before each `gosub` is a dummy return value: the finalizer
3590 /// runs with `ret_value` on the stack, and the normal path has no value to
3591 /// keep, so it pushes one to keep the stack depth identical on every path.
3592 fn try_stmt(
3593 &mut self,
3594 stmt: &Stmt,
3595 block: &[Stmt],
3596 handler: &Option<CatchClause>,
3597 finalizer: Option<&[Stmt]>,
3598 ) -> Result<(), SyntaxError> {
3599 self.reset_value();
3600
3601 let catch_label = self.new_label();
3602 let catch2_label = self.new_label();
3603 let finally_label = self.new_label();
3604 let end_label = self.new_label();
3605
3606 self.emit_jump(Opcode::Catch, catch_label, &[]);
3607
3608 // The guarded block. `break` may not target it, so its entry exists purely
3609 // to unwind: a jump out has to discard the catch offset and run the
3610 // finalizer.
3611 self.push_jump_target(JumpTarget {
3612 names: Vec::new(),
3613 break_label: None,
3614 continue_label: None,
3615 drop_count: 1,
3616 finally_label: Some(finally_label),
3617 is_regular_stmt: false,
3618 has_iterator: false,
3619 is_async_iterator: false,
3620 });
3621
3622 let block_key = Self::try_block_key(stmt, TryPart::Block);
3623 let block_parent = self.cur().current_block;
3624 self.push_block(block_key, block_parent);
3625 self.emit_scope_enter(block_key);
3626 self.stmts(block)?;
3627 self.emit_scope_leave(block_key);
3628 self.state().current_block = block_parent;
3629 // A guarded block that ends in a `return`/`throw` never reaches the
3630 // epilogue, so the reference does not emit one.
3631 self.pop_jump_target();
3632 let block_live = !block.last().is_some_and(Self::terminates);
3633
3634 if block_live {
3635 self.emit(Opcode::Drop, &[]);
3636 self.emit(Opcode::Undefined, &[]);
3637 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3638 self.emit(Opcode::Drop, &[]);
3639 self.emit_jump(Opcode::Goto, end_label, &[]);
3640 }
3641
3642 if let Some(handler) = handler {
3643 self.place_label(catch_label);
3644 // The thrown value is on top of the stack: bind it, or discard it for
3645 // `catch { }`.
3646 match &handler.param {
3647 Some(pattern) => {
3648 // The stores resolve the names, so they have to run inside the
3649 // parameter's own scope; otherwise a same-named `catch` further out
3650 // could win. A `catch` binding is never in the dead zone, so the store
3651 // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
3652 let param_key = Self::try_block_key(stmt, TryPart::Param);
3653 let param_parent = self.cur().current_block;
3654 self.push_block(param_key, param_parent);
3655 self.destructure(pattern, Some(VarDeclKind::Var))?;
3656 self.state().current_block = param_parent;
3657 }
3658 None => self.emit(Opcode::Drop, &[]),
3659 }
3660 self.emit_jump(Opcode::Catch, catch2_label, &[]);
3661
3662 self.push_jump_target(JumpTarget {
3663 names: Vec::new(),
3664 break_label: None,
3665 continue_label: None,
3666 drop_count: 1,
3667 finally_label: Some(finally_label),
3668 is_regular_stmt: false,
3669 has_iterator: false,
3670 is_async_iterator: false,
3671 });
3672 let catch_key = Self::try_block_key(stmt, TryPart::Catch);
3673 let catch_parent = self.cur().current_block;
3674 self.push_block(catch_key, catch_parent);
3675 self.emit_scope_enter(catch_key);
3676 self.stmts(&handler.body)?;
3677 self.emit_scope_leave(catch_key);
3678 self.state().current_block = catch_parent;
3679 self.pop_jump_target();
3680 let handler_live = !handler.body.last().is_some_and(Self::terminates);
3681
3682 if handler_live {
3683 self.emit(Opcode::Drop, &[]);
3684 self.emit(Opcode::Undefined, &[]);
3685 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3686 self.emit(Opcode::Drop, &[]);
3687 self.emit_jump(Opcode::Goto, end_label, &[]);
3688 }
3689
3690 // An error raised inside the handler still has to run the finalizer.
3691 self.place_label(catch2_label);
3692 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3693 self.emit(Opcode::Throw, &[]);
3694 } else {
3695 // `try`/`finally` with no handler: the finalizer runs, then the error
3696 // keeps propagating.
3697 self.place_label(catch_label);
3698 self.emit_jump(Opcode::Gosub, finally_label, &[]);
3699 self.emit(Opcode::Throw, &[]);
3700 }
3701
3702 self.place_label(finally_label);
3703 // Inside the finalizer, leaving has a different cost: the return value and
3704 // the `gosub` return address are both on the stack, and neither finalizer nor
3705 // any outer one may run before the block has finished.
3706 self.push_jump_target(JumpTarget {
3707 names: Vec::new(),
3708 break_label: None,
3709 continue_label: None,
3710 drop_count: 2,
3711 finally_label: None,
3712 is_regular_stmt: false,
3713 has_iterator: false,
3714 is_async_iterator: false,
3715 });
3716 if let Some(finalizer) = finalizer {
3717 let finally_key = Self::try_block_key(stmt, TryPart::Finally);
3718 let finally_parent = self.cur().current_block;
3719 self.push_block(finally_key, finally_parent);
3720 self.emit_scope_enter(finally_key);
3721 self.stmts(finalizer)?;
3722 self.emit_scope_leave(finally_key);
3723 self.state().current_block = finally_parent;
3724 }
3725 self.pop_jump_target();
3726 self.emit(Opcode::Ret, &[]);
3727 self.place_label(end_label);
3728 Ok(())
3729 }
3730
3731 /// Compile `for`/`in` and `for`/`of`.
3732 ///
3733 /// Both keep an enumeration record on the value stack for the whole loop, which
3734 /// is what makes leaving early expensive: the record has to be dropped, or the
3735 /// iterator closed. The layout is
3736 ///
3737 /// ```text
3738 /// <iterated expression>
3739 /// for_in_start | for_of_start <- pushes the record
3740 /// goto TEST
3741 /// NEXT:
3742 /// <bind the loop variable>
3743 /// <body>
3744 /// TEST:
3745 /// for_in_next | for_of_next 0
3746 /// if_false NEXT <- not finished: next iteration
3747 /// drop <- finished: discard the leftover value
3748 /// BREAK:
3749 /// drop | iterator_close <- the one cleanup `break` also uses
3750 /// ```
3751 ///
3752 /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
3753 /// normal exit share one copy — which is why `break` inside the loop emits nothing
3754 /// of its own, and only a jump that passes *through* the loop pays for its record.
3755 fn for_in_of(
3756 &mut self,
3757 stmt: &Stmt,
3758 left: &ForHead,
3759 right: &Expr,
3760 body: &Stmt,
3761 kind: ForLoopKind,
3762 labels: &[String],
3763 ) -> Result<(), SyntaxError> {
3764 self.reset_value();
3765
3766 let loop_key = stmt.span.start.offset as u64;
3767 let loop_parent = self.cur().current_block;
3768 self.push_block(loop_key, loop_parent);
3769 self.emit_scope_enter(loop_key);
3770
3771 // The iterated expression is evaluated inside the loop's scope, after the
3772 // bindings exist in the temporal dead zone.
3773 self.expr(right)?;
3774
3775 let next = self.new_label();
3776 let test = self.new_label();
3777 let break_target = self.new_label();
3778
3779 let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
3780 match kind {
3781 ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
3782 ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
3783 ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
3784 }
3785 self.emit_jump(Opcode::Goto, test, &[]);
3786
3787 self.push_jump_target(JumpTarget {
3788 // `outer: for (x of xs) … break outer` needs the name here. Without it the
3789 // loop had no label to break to, and the compiler reported "break has no
3790 // enclosing loop" for a loop that was plainly enclosing it.
3791 names: labels.to_vec(),
3792 break_label: Some(break_target),
3793 continue_label: Some(test),
3794 // Passing through the loop has to dispose of its record. A `for`/`of`
3795 // record is three slots, and closing the iterator consumes all of them.
3796 drop_count: if has_iterator { 3 } else { 1 },
3797 finally_label: None,
3798 is_regular_stmt: false,
3799 has_iterator,
3800 is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
3801 });
3802
3803 self.place_label(next);
3804 self.bind_loop_variable(left)?;
3805
3806 // The reference marks the body with its own label here. Nothing jumps to it
3807 // once the loop is laid out, but it is not decoration: a label between the
3808 // store and the body is why `put_loc v; get_loc v` does *not* fold into
3809 // `set_loc v` when the body starts by reading the loop variable.
3810 let body_label = self.new_label();
3811 self.place_label(body_label);
3812 // `for (using x of …)` disposes once per iteration, so the body is a disposal
3813 // region rather than the whole loop: the resource is the element that this
3814 // iteration produced.
3815 let using_slot = match left {
3816 ForHead::VarDecl(decl) if decl.kind.is_using() => {
3817 decl.declarators
3818 .first()
3819 .and_then(|declarator| match &declarator.target.kind {
3820 PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
3821 _ => None,
3822 })
3823 }
3824 _ => None,
3825 };
3826 match using_slot {
3827 Some(slot) => {
3828 let live = !Self::terminates(body);
3829 self.using_region_around(slot, live, |compiler| compiler.stmt(body))?;
3830 }
3831 None => self.stmt(body)?,
3832 }
3833
3834 // §14.7.5.6 `ForIn/OfBodyEvaluation` step 6: a `let`/`const` head gets a **fresh
3835 // binding each iteration**, so a closure the body creates keeps that iteration's
3836 // value. `CloseCaptured` is the same instruction the C-style `for` uses: it swaps in
3837 // a new reference cell holding the current value.
3838 //
3839 // The position is the *end* of the body, not the start: closing before the body
3840 // would leave the closures pointing at the cell the next `put_loc` overwrites, and
3841 // `for (const x of [1,2,3]) fs.push(() => x)` answered `2,3,3` instead of `1,2,3`.
3842 for name in Self::loop_binding_names(left) {
3843 let pos = self.cur().cur_pos;
3844 self.state().insns.push(Insn::CloseCaptured {
3845 name,
3846 block: loop_key,
3847 });
3848 self.state().insn_pos.push(pos);
3849 }
3850 self.place_label(test);
3851 match kind {
3852 ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
3853 ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
3854 ForLoopKind::AwaitOf => {
3855 // The reference's shape: step, `await` the result, then unpack it.
3856 self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
3857 self.emit(Opcode::Await, &[]);
3858 self.state().has_await = true;
3859 self.emit(Opcode::IteratorGetValueDone, &[]);
3860 }
3861 }
3862 self.emit_jump(Opcode::IfFalse, next, &[]);
3863 // The loop is finished; `for_xx_next` left an `undefined` behind.
3864 self.emit(Opcode::Drop, &[]);
3865
3866 self.pop_jump_target();
3867 self.place_label(break_target);
3868 if has_iterator {
3869 // A loop that ran to completion finds its iterator slot already cleared (see
3870 // `iterator_get_value_done`), so this closes only an iterator abandoned by a
3871 // `break` that jumped here.
3872 self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
3873 } else {
3874 self.emit(Opcode::Drop, &[]);
3875 }
3876
3877 self.emit_scope_leave(loop_key);
3878 self.state().current_block = loop_parent;
3879 Ok(())
3880 }
3881
3882 /// The names a `for (let … of/in …)` head declares, which need a fresh cell per
3883 /// iteration. An assignment head (`for (x of …)`) declares nothing, so it is empty.
3884 fn loop_binding_names(left: &ForHead) -> Vec<String> {
3885 let ForHead::VarDecl(decl) = left else {
3886 return Vec::new();
3887 };
3888 if decl.kind == VarDeclKind::Var {
3889 return Vec::new();
3890 }
3891 let mut names = Vec::new();
3892 for declarator in &decl.declarators {
3893 let mut idents = Vec::new();
3894 declarator.target.bound_names(&mut idents);
3895 names.extend(idents.into_iter().map(|ident| ident.name));
3896 }
3897 names
3898 }
3899
3900 /// Store the value `for_xx_next` left on the stack into the loop variable.
3901 fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
3902 // A declaration *initialises* the binding, which is what takes a `let` out of
3903 // the temporal dead zone, so the store is the unchecked form. Assigning to a
3904 // binding declared elsewhere is an ordinary write and keeps its check.
3905 let (pattern, action) = match left {
3906 ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
3907 ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
3908 };
3909 match &pattern.kind {
3910 PatternKind::Ident(name) => {
3911 // `for (using x of …)` validates and snapshots each iteration's value
3912 // before the body runs, which is what makes a non-disposable element fail
3913 // on the iteration that produced it rather than at the end of the loop.
3914 if let ForHead::VarDecl(decl) = left
3915 && decl.kind.is_using()
3916 {
3917 let method_slot = self
3918 .using_method_slot(&name.name)
3919 .expect("a using binding was declared during hoisting");
3920 self.emit(
3921 Opcode::UsingCheck,
3922 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3923 );
3924 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3925 }
3926 self.emit_var(action, &name.name);
3927 Ok(())
3928 }
3929 // Every other target stores through the same path an assignment pattern
3930 // uses, which is what makes `for (a[0] in obj)` write each key into the
3931 // property instead of refusing the loop outright.
3932 _ => self.destructure(
3933 pattern,
3934 match left {
3935 ForHead::VarDecl(decl) => Some(decl.kind),
3936 ForHead::Assign(_) => None,
3937 },
3938 ),
3939 }
3940 }
3941
3942 fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
3943 for declarator in &decl.declarators {
3944 let Some(init) = &declarator.init else {
3945 // `var x;` stays `undefined`. A lexical binding is different: it
3946 // has to be *initialised* to leave the temporal dead zone, so the
3947 // compiler supplies an explicit `undefined`.
3948 if decl.kind.is_lexical() {
3949 // A lexical binding has to be *initialised* to leave the temporal
3950 // dead zone, and a destructuring one is no different — `let {a}`
3951 // with no initialiser is a syntax error, but `let [a] = []` still
3952 // needs `a` to be initialised from an empty source, which the
3953 // pattern does on its own.
3954 self.emit(Opcode::Undefined, &[]);
3955 self.destructure(&declarator.target, Some(decl.kind))?;
3956 }
3957 continue;
3958 };
3959 match &declarator.target.kind {
3960 PatternKind::Ident(name) => {
3961 self.expr(init)?;
3962 self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
3963 if decl.kind.is_using() {
3964 // `using_check` validates the value and snapshots its dispose
3965 // method: `value -> value, method`. The snapshot is what makes a
3966 // later change to `Symbol.dispose` irrelevant, and validating here
3967 // is what keeps the body from running at all when the value is not
3968 // disposable.
3969 let method_slot = self
3970 .using_method_slot(&name.name)
3971 .expect("a using binding was declared during hoisting");
3972 self.emit(
3973 Opcode::UsingCheck,
3974 &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3975 );
3976 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3977 self.emit_var(VarAction::PutInit, &name.name);
3978 continue;
3979 }
3980 // A declaration statement produces no value, so nothing is
3981 // duplicated onto the stack.
3982 match decl.kind {
3983 VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
3984 _ => self.emit_var(VarAction::PutInit, &name.name),
3985 }
3986 }
3987 _ => {
3988 // A destructuring declaration keeps nothing on the stack: the
3989 // pattern consumes the initialiser.
3990 self.expr(init)?;
3991 self.destructure(&declarator.target, Some(decl.kind))?;
3992 }
3993 }
3994 }
3995 Ok(())
3996 }
3997
3998 /// Bind a destructuring pattern from the value on top of the stack.
3999 ///
4000 /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
4001 /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
4002 /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
4003 /// *assignment*, where a member expression is a legal target and the store is an
4004 /// ordinary property write.
4005 ///
4006 /// The value is consumed. An assignment expression's own result is the right-hand
4007 /// side, which the caller keeps separately — the spec does not make the pattern's
4008 /// last store produce it.
4009 fn destructure(
4010 &mut self,
4011 pattern: &Pattern,
4012 decl: Option<VarDeclKind>,
4013 ) -> Result<(), SyntaxError> {
4014 match &pattern.kind {
4015 PatternKind::Ident(name) => {
4016 match decl {
4017 Some(VarDeclKind::Var) | None => {
4018 self.emit_var(VarAction::Put, &name.name);
4019 }
4020 Some(_) => self.emit_var(VarAction::PutInit, &name.name),
4021 }
4022 Ok(())
4023 }
4024 PatternKind::Assign { target, default } => {
4025 // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
4026 // keeps `null`.
4027 //
4028 // The shape is the reference's: test for `undefined`, and when the value is
4029 // present fall **through** to a single store both paths share. The
4030 // alternatives — branching to the store on each side — need a second store
4031 // and a jump between them, which is what the dump used to show.
4032 let has_value = self.new_label();
4033 self.emit(Opcode::Dup, &[]);
4034 self.emit(Opcode::IsUndefined, &[]);
4035 self.emit_jump(Opcode::IfFalse, has_value, &[]);
4036 self.emit(Opcode::Drop, &[]);
4037 self.expr(default)?;
4038 // `var {f = function(){}} = {}` names the function `f`, like a plain
4039 // `var f = function(){}` does. Both pattern forms do it:
4040 // `BindingInitialization` names the value for a *binding* target, and since
4041 // ES2018 `DestructuringAssignmentEvaluation` does the same, so
4042 // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
4043 // no name to give, which is why only an identifier qualifies.
4044 if let PatternKind::Ident(name) = &target.kind {
4045 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
4046 }
4047 self.place_label(has_value);
4048 self.destructure(target, decl)
4049 }
4050 PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
4051 PatternKind::Object { properties, rest } => {
4052 self.destructure_object(properties, rest, decl, pattern)
4053 }
4054 PatternKind::Member(member) if decl.is_none() => {
4055 // An assignment pattern may store into a property. The value is on the
4056 // stack, so the receiver and the key go above it and `rot3l`/`swap2`
4057 // put the three in the order `put_array_el`/`put_field` expect.
4058 self.expr(&member.object)?;
4059 match &member.property {
4060 MemberProp::Ident(name) => {
4061 // `value obj` -> `obj value`, the order `put_field` takes.
4062 // Nothing needs to be left behind: a pattern element's value is
4063 // consumed by its own store.
4064 self.emit(Opcode::Swap, &[]);
4065 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4066 }
4067 MemberProp::Computed(index) => {
4068 self.expr(index)?;
4069 // `value obj key` -> `obj key value`.
4070 self.emit(Opcode::Rot3l, &[]);
4071 self.emit(Opcode::PutArrayEl, &[]);
4072 }
4073 MemberProp::Private(name) => {
4074 // `value obj` -> `obj value`, and the store half of the assignment is
4075 // the same one `obj.#x = value` uses — only without `insert2`,
4076 // because a pattern element's value is not wanted back.
4077 let binding = format!("#{}", name.name);
4078 let (kind, setter) = self.private_use(&binding, member.span)?;
4079 self.emit(Opcode::Swap, &[]);
4080 self.private_store(&binding, kind, setter.as_deref())?;
4081 }
4082 }
4083 Ok(())
4084 }
4085 PatternKind::Rest(inner) => self.destructure(inner, decl),
4086 PatternKind::Invalid(expr) => {
4087 Err(SyntaxError::new("invalid assignment target", expr.span))
4088 }
4089 _ => Err(SyntaxError::new(
4090 "this destructuring target is not supported by the compiler yet",
4091 pattern.span,
4092 )),
4093 }
4094 }
4095
4096 /// `[…]` on the left: drain an iterator, binding one target per element.
4097 ///
4098 /// A target that stores into a **property** — `[o.p] = it` — has its reference worked
4099 /// out *before* the value is pulled. That ordering is observable twice over
4100 /// (`array-elem-iter-thrw-close`):
4101 ///
4102 /// * `next` must not have been called yet when the reference throws, so
4103 /// `[ {}[thrower()] ] = iterable` reports `nextCount === 0`;
4104 /// * the iterator must still be closed, because the throw happens while the record is
4105 /// live — which is `catch_here`'s `catch_offset 0` doing its work.
4106 ///
4107 /// Doing it the other way round — pull the value, then evaluate the reference — got
4108 /// both wrong: an extra `next` call, and, when the reference threw, an iterator that had
4109 /// already been drained past.
4110 fn destructure_array(
4111 &mut self,
4112 elements: &[Option<PatternElement>],
4113 rest: &Option<Box<RestElement>>,
4114 decl: Option<VarDeclKind>,
4115 ) -> Result<(), SyntaxError> {
4116 // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
4117 // pattern accepts any iterable and closes the iterator when the pattern ends
4118 // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
4119 // first because it is on top.
4120 //
4121 // It also counts as an open iterator for `return` and `break`: a pattern is not a
4122 // loop, but the record is live across everything the pattern evaluates, so
4123 // `function* g(){ [ {} = yield ] = it }` resumed with `return()` has to close it
4124 // (`array-elem-iter-rtrn-close`). `emit_unwind_for_return` finds it by this entry
4125 // and `nip_catch` uncovers exactly the `iter next` pairs it left behind.
4126 //
4127 // A `break`/`continue` cannot occur inside a pattern, so `names` and both labels
4128 // are empty and `drop_count` — read only by that unreachable path — keeps the
4129 // reference's 2.
4130 self.push_jump_target(JumpTarget {
4131 names: Vec::new(),
4132 break_label: None,
4133 continue_label: None,
4134 drop_count: 2,
4135 finally_label: None,
4136 is_regular_stmt: false,
4137 has_iterator: true,
4138 is_async_iterator: false,
4139 });
4140 self.emit(Opcode::ForOfStart, &[]);
4141 for element in elements {
4142 match element {
4143 Some(PatternElement::Pattern(pattern)) => {
4144 match Self::member_element_target(pattern, decl) {
4145 // A prepared reference sits above the record, so `for_of_next` is
4146 // told how many values are in the way.
4147 Some(member) => {
4148 let extra = self.prepare_member_target(member)?;
4149 self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4150 self.emit(Opcode::Drop, &[]);
4151 self.destructure_prepared(pattern, member)?;
4152 }
4153 None => {
4154 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4155 self.emit(Opcode::Drop, &[]);
4156 self.destructure(pattern, decl)?;
4157 }
4158 }
4159 }
4160 Some(PatternElement::Property { span, .. }) => {
4161 return Err(SyntaxError::new(
4162 "a property pattern is not a valid array element",
4163 *span,
4164 ));
4165 }
4166 // An elision skips the value, which is already on the stack.
4167 None => {
4168 self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4169 self.emit(Opcode::Drop, &[]);
4170 self.emit(Opcode::Drop, &[]);
4171 }
4172 }
4173 }
4174 if let Some(rest) = rest {
4175 // The remaining values go into a fresh array. The target and its running
4176 // index stay on the stack above the iterator, which is what the operand of
4177 // `for_of_next` accounts for: two values sit above the iterator triple.
4178 let prepared = match decl {
4179 None => Self::member_rest_target(rest),
4180 // A binding pattern cannot store into a property.
4181 Some(_) => None,
4182 };
4183 let extra = match prepared {
4184 Some(member) => 2 + self.prepare_member_target(member)?,
4185 None => 2,
4186 };
4187 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4188 self.emit(Opcode::Push0, &[]);
4189 let top = self.new_label();
4190 self.place_label(top);
4191 self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4192 let done = self.new_label();
4193 self.emit_jump(Opcode::IfTrue, done, &[]);
4194 self.emit(Opcode::DefineArrayEl, &[]);
4195 self.emit(Opcode::Inc, &[]);
4196 self.emit_jump(Opcode::Goto, top, &[]);
4197 self.place_label(done);
4198 self.emit(Opcode::Drop, &[]);
4199 self.emit(Opcode::Drop, &[]);
4200 match prepared {
4201 Some(member) => self.store_member_value(member)?,
4202 None => self.destructure_rest(rest, decl)?,
4203 }
4204 }
4205 self.emit(Opcode::IteratorClose, &[]);
4206 self.pop_jump_target();
4207 Ok(())
4208 }
4209
4210 /// The property an array element stores into, when it stores into one at all.
4211 ///
4212 /// `Assign` is peeled because `[o.p = d] = it` evaluates `o.p`'s reference at the same
4213 /// point `[o.p] = it` does; the default value is applied afterwards, on the pulled
4214 /// value. Nothing deeper is: a nested pattern's own targets are reached by recursing
4215 /// into `destructure`, and those never straddle a `for_of_next`.
4216 fn member_element_target(
4217 pattern: &Pattern,
4218 decl: Option<VarDeclKind>,
4219 ) -> Option<&ast::MemberPattern> {
4220 if decl.is_some() {
4221 return None;
4222 }
4223 match &pattern.kind {
4224 PatternKind::Member(member) => Some(member),
4225 PatternKind::Assign { target, .. } => Self::member_element_target(target, decl),
4226 _ => None,
4227 }
4228 }
4229
4230 /// The same, for a rest element.
4231 fn member_rest_target(rest: &RestElement) -> Option<&ast::MemberPattern> {
4232 match rest {
4233 RestElement::Member(member) => Some(member),
4234 RestElement::Pattern(pattern) => match &pattern.kind {
4235 PatternKind::Member(member) => Some(member),
4236 _ => None,
4237 },
4238 }
4239 }
4240
4241 /// Push a member target's reference — the object, and the key when the property is
4242 /// computed — and answer how many values that put above the iterator record.
4243 fn prepare_member_target(&mut self, member: &ast::MemberPattern) -> Result<i32, SyntaxError> {
4244 self.expr(&member.object)?;
4245 match &member.property {
4246 MemberProp::Ident(_) | MemberProp::Private(_) => Ok(1),
4247 MemberProp::Computed(index) => {
4248 self.expr(index)?;
4249 Ok(2)
4250 }
4251 }
4252 }
4253
4254 /// Store the value on top of the stack through a prepared member reference.
4255 ///
4256 /// `obj value` for a named property, `obj key value` for a computed one — the orders
4257 /// `put_field` and `put_array_el` take, so no reordering is needed here. The `swap` and
4258 /// `rot3l` in [`Compiler::destructure`]'s member case exist only because *it* starts
4259 /// with the value already on the stack.
4260 fn store_member_value(&mut self, member: &ast::MemberPattern) -> Result<(), SyntaxError> {
4261 match &member.property {
4262 MemberProp::Ident(name) => {
4263 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4264 }
4265 MemberProp::Computed(_) => self.emit(Opcode::PutArrayEl, &[]),
4266 MemberProp::Private(name) => {
4267 let binding = format!("#{}", name.name);
4268 let (kind, setter) = self.private_use(&binding, member.span)?;
4269 self.private_store(&binding, kind, setter.as_deref())?;
4270 }
4271 }
4272 Ok(())
4273 }
4274
4275 /// The value of an array element whose member reference is already prepared.
4276 ///
4277 /// Only the default-value test differs from [`Compiler::destructure`]: the reference
4278 /// and the value are both on the stack while the test runs, which is why the object is
4279 /// evaluated before the default rather than after it.
4280 fn destructure_prepared(
4281 &mut self,
4282 pattern: &Pattern,
4283 member: &ast::MemberPattern,
4284 ) -> Result<(), SyntaxError> {
4285 if let PatternKind::Assign { default, .. } = &pattern.kind {
4286 let has_value = self.new_label();
4287 self.emit(Opcode::Dup, &[]);
4288 self.emit(Opcode::IsUndefined, &[]);
4289 self.emit_jump(Opcode::IfFalse, has_value, &[]);
4290 self.emit(Opcode::Drop, &[]);
4291 self.expr(default)?;
4292 self.place_label(has_value);
4293 }
4294 self.store_member_value(member)
4295 }
4296
4297 /// `{…}` on the left: read properties off one boxed source object.
4298 fn destructure_object(
4299 &mut self,
4300 properties: &[Option<PatternElement>],
4301 rest: &Option<Box<RestElement>>,
4302 decl: Option<VarDeclKind>,
4303 pattern: &Pattern,
4304 ) -> Result<(), SyntaxError> {
4305 // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
4306 // aside for the rest element below.
4307 self.emit(Opcode::ToObject, &[]);
4308 let mut taken: Vec<Wtf8> = Vec::new();
4309 // A computed key's *value* is only known at run time, so with a rest element the
4310 // exclusion list cannot be an `ArrayFrom` over literal atoms. It becomes a hidden
4311 // local array that every key is written into as the pattern is walked — literal
4312 // keys by name, computed ones by the value the expression produced. Without this,
4313 // `let { [k]: a, ...rest } = o` was refused outright.
4314 let needs_key_log = rest.is_some() && computed_key_count(properties) > 0;
4315 let key_log = if needs_key_log {
4316 let name = "<rest_exclude>";
4317 self.declare_hidden_local(name, VarKind::Normal);
4318 self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4319 self.emit_var(VarAction::Put, name);
4320 Some(name)
4321 } else {
4322 None
4323 };
4324 for property in properties {
4325 let Some(PatternElement::Property {
4326 key, value, span, ..
4327 }) = property
4328 else {
4329 return Err(SyntaxError::new(
4330 "a bare pattern is not a valid object property",
4331 properties
4332 .iter()
4333 .flatten()
4334 .map(|element| match element {
4335 PatternElement::Pattern(pattern) => pattern.span,
4336 PatternElement::Property { span, .. } => *span,
4337 })
4338 .next()
4339 .unwrap_or(pattern.span),
4340 ));
4341 };
4342 // Every read needs the source twice: to read from, and to keep for the next
4343 // property. `get_field2` is that duplicate-and-read in one instruction, but it
4344 // leaves the copy *under* the value, so it is only usable when whatever
4345 // consumes the value tolerates that. See [`reads_with_get_field2`].
4346 let nested = reads_with_get_field2(decl, value);
4347 if !nested {
4348 self.emit(Opcode::Dup, &[]);
4349 }
4350 let slot = taken.len();
4351 match key {
4352 PropName::Literal(literal) => {
4353 let name = self.property_key_text(literal, *span)?;
4354 taken.push(name.clone());
4355 if let Some(log) = &key_log {
4356 // `arr index key -> arr`: the key is written into the log before
4357 // the read, so the order of observable operations is unchanged.
4358 self.emit_var(VarAction::Get, log);
4359 self.push_number(slot as f64);
4360 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&name))]);
4361 self.emit(Opcode::PutArrayEl, &[]);
4362 }
4363 self.emit(
4364 if nested {
4365 Opcode::GetField2
4366 } else {
4367 Opcode::GetField
4368 },
4369 &[Op::Atom(Atom::from_wtf8(&name))],
4370 );
4371 }
4372 PropName::Computed(index) => {
4373 self.expr(index)?;
4374 // `key key`: one stays on the stack for the read, the other goes into
4375 // the exclusion log. The index is a compile-time constant, so no counter
4376 // local is needed.
4377 if let Some(log) = &key_log {
4378 taken.push(Wtf8::default());
4379 self.emit(Opcode::Dup, &[]);
4380 self.emit_var(VarAction::Get, log);
4381 self.emit(Opcode::Swap, &[]);
4382 self.push_number(slot as f64);
4383 self.emit(Opcode::Swap, &[]);
4384 self.emit(Opcode::PutArrayEl, &[]);
4385 }
4386 self.emit(Opcode::GetArrayEl, &[]);
4387 }
4388 PropName::Private(_) => {
4389 return Err(SyntaxError::new(
4390 "private fields are not supported by the compiler yet",
4391 value.span,
4392 ));
4393 }
4394 }
4395 self.destructure(value, decl)?;
4396 }
4397 match rest {
4398 Some(rest) => {
4399 // `target src exclude`: the exclusion list is an array of the keys the
4400 // literal part already took, so the rest object gets only the others.
4401 self.emit(Opcode::Object, &[]);
4402 self.emit(Opcode::Swap, &[]);
4403 match &key_log {
4404 // Built while walking the pattern; see `needs_key_log`.
4405 Some(log) => {
4406 self.emit_var(VarAction::Get, log);
4407 }
4408 None => {
4409 for name in &taken {
4410 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
4411 }
4412 self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
4413 }
4414 }
4415 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4416 self.emit(Opcode::Drop, &[]);
4417 self.emit(Opcode::Drop, &[]);
4418 self.destructure_rest(rest, decl)?;
4419 }
4420 // The source was only kept for a rest element.
4421 None => self.emit(Opcode::Drop, &[]),
4422 }
4423 Ok(())
4424 }
4425
4426 /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
4427 fn destructure_rest(
4428 &mut self,
4429 rest: &RestElement,
4430 decl: Option<VarDeclKind>,
4431 ) -> Result<(), SyntaxError> {
4432 match rest {
4433 RestElement::Pattern(pattern) => self.destructure(pattern, decl),
4434 // `[...a.b] = c` stores into a property.
4435 RestElement::Member(member) => {
4436 let pattern = Pattern {
4437 kind: PatternKind::Member(member.clone()),
4438 span: member.span,
4439 };
4440 self.destructure(&pattern, decl)
4441 }
4442 }
4443 }
4444
4445 /// Compile a function declaration and queue it for instantiation at scope
4446 /// entry.
4447 ///
4448 /// A declaration is visible before the statement that declares it, so the
4449 /// code that creates the function object belongs at the top of the enclosing
4450 /// scope, not at the declaration.
4451 fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
4452 let name = func.name.as_ref().expect("a declaration has a name");
4453 let function = self.compile_function(func)?;
4454 let pool_index = self.push_constant(Constant::Function(Box::new(function)));
4455 let target = self.hoist_target(&name.name);
4456 let block = self.cur().current_block;
4457 self.state().hoisted.push((block, target, pool_index));
4458 Ok(())
4459 }
4460
4461 /// Where a name lives, for a hoisted declaration.
4462 fn hoist_target(&self, name: &str) -> HoistTarget {
4463 let state = self.cur();
4464 if let Some(index) = state.args.iter().position(|a| a.name == name) {
4465 return HoistTarget::Arg(index as u32);
4466 }
4467 if let Some(index) = state.vars.iter().position(|v| v.name == name) {
4468 return HoistTarget::Loc(index as u32);
4469 }
4470 // A global function declaration is not a slot at all.
4471 HoistTarget::Global(name.to_string())
4472 }
4473
4474 // -- expressions -------------------------------------------------------
4475
4476 /// Compile one expression, recording where its instructions sit.
4477 ///
4478 /// The position is the node's operator when it has one and its first token
4479 /// otherwise, and it is restored on the way out so a parent's own instructions —
4480 /// which are emitted *after* its children — are blamed on the parent. Without the
4481 /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4482 fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4483 // `discard_value` belongs to the *statement* that is about to be compiled, so it
4484 // may only be honoured by that statement's own top-level expression. Taking it here
4485 // is what enforces that: `f(x = 1)` sets it for the call, and the assignment inside
4486 // the argument list is a different expression — it must still leave its value on the
4487 // stack. Without this the argument vanished, and `call` then consumed the callee as
4488 // its argument (`TypeError: undefined is not a function` from `f(x = 1)` inside any
4489 // function).
4490 self.discard_root = std::mem::take(&mut self.state().discard_value);
4491 let saved = self.cur().cur_pos;
4492 // Only the node kinds the reference calls `emit_source_pos` for record a position:
4493 // the operator a node exists for, and a variable *read*, which the reference
4494 // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4495 // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4496 // start, a parenthesised group, an anonymous function expression — leaves the
4497 // previous position in place, because a table entry the reference never writes is
4498 // one we must not write either: the instruction that inherits a position (the
4499 // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4500 // report a more recent token than the reference does.
4501 let pos = expr.op_pos.or(match &expr.kind {
4502 ExprKind::Ident(ident) => Some(ident.span.start),
4503 _ => None,
4504 });
4505 match pos {
4506 Some(pos) => self.state().cur_pos = Some(pos),
4507 // A node the reference records nothing for: its own instructions stay
4508 // unpositioned, so they inherit whatever was written last — which is what an
4509 // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4510 // enclosing position instead would blame them on a token the reference has not
4511 // reached yet: a spread's `iterator_open` reports the expression it follows, and
4512 // a template's `to_propkey` the interpolation.
4513 None => self.state().cur_pos = None,
4514 }
4515 // Note a direct `eval` call before compiling it, because the *whole* function
4516 // is affected: an eval can name any binding the function declares, so every one
4517 // of them has to live in a cell for a closure it creates to capture it.
4518 self.note_direct_eval(expr);
4519 let result = self.expr_inner(expr);
4520 self.discard_root = false;
4521 self.state().cur_pos = saved;
4522 result
4523 }
4524
4525 /// Record which bindings are in scope at a direct `eval` call.
4526 ///
4527 /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
4528 /// resolves names from a string at run time, so the only chance to pin down *which*
4529 /// slot a name means is here. Visibility is the lexical rule: a binding counts when
4530 /// its block is the current block, an enclosing one, or the function scope.
4531 fn materialize_eval_sites(&mut self) {
4532 let pending = std::mem::take(&mut self.state().pending_eval_sites);
4533 for (span, site_block, in_params, private, arguments_allowed) in pending {
4534 self.resolve_eval_site(span, site_block, in_params, private, arguments_allowed);
4535 }
4536 }
4537
4538 /// Resolve the bindings visible at one `eval` call.
4539 fn resolve_eval_site(
4540 &mut self,
4541 span: Span,
4542 site_block: u64,
4543 site_in_params: bool,
4544 private_names: Vec<EvalPrivate>,
4545 arguments_allowed: bool,
4546 ) {
4547 /// How near a binding is: function distance first, then block depth, then the
4548 /// later declaration (which shadows the earlier one in the same block).
4549 type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
4550
4551 // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
4552 // walked, innermost function first: a direct `eval` sees every enclosing
4553 // function's bindings, and none of them can be resolved at run time because the
4554 // runtime only has names to go on.
4555 let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
4556 let deepest = self.stack.len() - 1;
4557 for (level, state) in self.stack.iter().enumerate().rev() {
4558 let owner = (deepest - level) as u32;
4559 // The innermost function's block is the one the call sat in, which is not
4560 // the block the compiler is in now; the enclosing functions are still at
4561 // the point where this one was created.
4562 let here = if level == deepest {
4563 site_block
4564 } else {
4565 state.current_block
4566 };
4567 // The chain of live blocks, innermost first, with a depth for each. The walk
4568 // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
4569 // block can start at source offset zero.
4570 let mut live: Vec<(u64, usize)> = vec![(here, 0)];
4571 let mut block = here;
4572 while let Some(parent) = state
4573 .blocks
4574 .iter()
4575 .find(|candidate| candidate.key == block)
4576 .map(|candidate| candidate.parent)
4577 .filter(|parent| *parent != NO_PARENT)
4578 .filter(|parent| parent != &block)
4579 {
4580 live.push((parent, live.len()));
4581 block = parent;
4582 }
4583 let depth_of = |key: u64| {
4584 live.iter()
4585 .find(|(candidate, _)| *candidate == key)
4586 .map(|(_, depth)| *depth)
4587 // The function scope is the outermost depth there is. A binding of a
4588 // block this site is not inside lands here too, which pushes it
4589 // behind every live one — the right answer: it is out of scope.
4590 .unwrap_or(live.len())
4591 };
4592 for (index, arg) in state.args.iter().enumerate() {
4593 bindings.push((
4594 (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
4595 EvalVisible {
4596 name: arg.name.clone(),
4597 is_arg: true,
4598 index: index as u32,
4599 owner,
4600 },
4601 ));
4602 }
4603 // A parameter list cannot see the body, so a body `var` is not a binding the
4604 // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
4605 // not let that eval write the body's `c`.
4606 let hides_body = if level == deepest {
4607 site_in_params
4608 } else {
4609 state.created_in_params
4610 };
4611 for (index, var) in state.vars.iter().enumerate() {
4612 let block = state
4613 .var_block
4614 .get(index)
4615 .copied()
4616 .unwrap_or(FUNCTION_SCOPE);
4617 if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
4618 continue;
4619 }
4620 bindings.push((
4621 (
4622 owner as usize,
4623 depth_of(block),
4624 std::cmp::Reverse(index as u32),
4625 ),
4626 EvalVisible {
4627 name: var.name.clone(),
4628 is_arg: false,
4629 index: index as u32,
4630 owner,
4631 },
4632 ));
4633 }
4634 }
4635 // Innermost function first, then innermost block, then the later declaration
4636 // (which shadows the earlier one within a block).
4637 bindings.sort_by_key(|(priority, _)| *priority);
4638 let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
4639 self.state().eval_sites.push(EvalSite {
4640 line: span.start.line,
4641 column: span.start.column,
4642 bindings,
4643 private_names,
4644 arguments_allowed,
4645 });
4646 }
4647
4648 /// The private names visible from the compiler's current position, innermost last.
4649 ///
4650 /// A direct `eval` inherits these because private names are lexically scoped
4651 /// (§15.10.2). Flattened with the **first** occurrence winning as the scopes are walked
4652 /// outermost-first, so a nested class's `#x` shadows an outer class's — the same
4653 /// shadowing `ClassPlan::find` gives a use site inside the body.
4654 fn visible_private_names(&self) -> Vec<EvalPrivate> {
4655 let mut out: Vec<EvalPrivate> = Vec::new();
4656 for scope in &self.private_scopes {
4657 for (name, use_) in scope {
4658 if out.iter().any(|entry| &entry.name == name) {
4659 continue;
4660 }
4661 out.push(EvalPrivate {
4662 name: name.clone(),
4663 kind: match use_.kind {
4664 PrivateKind::Field => EvalPrivateKind::Field,
4665 PrivateKind::Method => EvalPrivateKind::Method,
4666 PrivateKind::Getter => EvalPrivateKind::Getter,
4667 PrivateKind::Setter => EvalPrivateKind::Setter,
4668 },
4669 setter: use_.setter.clone(),
4670 });
4671 }
4672 }
4673 out
4674 }
4675
4676 /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
4677 ///
4678 /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
4679 /// a bare identifier callee counts.
4680 /// Record everything a direct `eval` call site has to tell the runtime.
4681 ///
4682 /// Called from both places a call can be compiled: [`Compiler::expr`] for an ordinary
4683 /// one, and [`Compiler::expr_if_tail_call`] for a `return eval(…)`, which skips `expr`
4684 /// entirely. Missing the tail-call path is not hypothetical — it is why
4685 /// `class C { #m; f() { return eval("this.#m") } }` still failed after the private
4686 /// names were otherwise wired through.
4687 fn note_direct_eval(&mut self, expr: &Expr) {
4688 if !Self::is_direct_eval(expr) {
4689 return;
4690 }
4691 // Every enclosing function is affected too: the eval sees the whole scope chain,
4692 // and a closure it creates can capture a binding of any of them.
4693 // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a cell,
4694 // because the closure the eval builds outlives the loop iteration.
4695 for state in &mut self.stack {
4696 state.has_direct_eval = true;
4697 }
4698 let block = self.cur().current_block;
4699 let in_params = self.cur().in_params;
4700 // The private names are snapshotted **here**, at the call site, not when the sites
4701 // are materialised: materialisation happens once the whole function is compiled, by
4702 // which point every class scope has been popped and the answer would always be
4703 // empty.
4704 let private = self.visible_private_names();
4705 // An arrow has no `arguments` of its own and inherits the restriction from the
4706 // nearest real function: `x = () => { () => eval('arguments') }` is still a
4707 // class field initializer's arrow, and still has no `arguments` to see.
4708 let arguments_allowed = !self
4709 .stack
4710 .iter()
4711 .rev()
4712 .find(|state| !state.is_arrow)
4713 .is_some_and(|state| state.no_arguments_binding);
4714 self.state().pending_eval_sites.push((
4715 expr.span,
4716 block,
4717 in_params,
4718 private,
4719 arguments_allowed,
4720 ));
4721 }
4722
4723 fn is_direct_eval(expr: &Expr) -> bool {
4724 matches!(
4725 &expr.kind,
4726 ExprKind::Call { callee, .. }
4727 if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
4728 )
4729 }
4730
4731 fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4732 match &expr.kind {
4733 ExprKind::Number(value) => self.push_number(*value),
4734 ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
4735 ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
4736 ExprKind::Null => self.emit(Opcode::Null, &[]),
4737 ExprKind::String(text) => self.push_string(text),
4738 ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
4739 ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
4740 ExprKind::This => self.this_expression(),
4741 ExprKind::NewTarget => self.new_target_expression(),
4742 ExprKind::Paren(inner) => self.expr(inner)?,
4743 ExprKind::Binary { op, left, right } => {
4744 self.expr(left)?;
4745 self.expr(right)?;
4746 self.emit(binary_opcode(*op), &[]);
4747 }
4748 ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
4749 ExprKind::Unary {
4750 op: UnaryOp::Minus,
4751 argument,
4752 } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
4753 let ExprKind::Number(value) = argument.unparen().kind else {
4754 unreachable!("matched above")
4755 };
4756 // The reference folds a negative literal only when the negation is
4757 // exact in the integer range: `-1` becomes `push_minus1` and
4758 // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
4759 // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
4760 // `-Infinity`, not `Infinity` — and folding a fraction would change
4761 // which instruction the reference emits.
4762 let negated = -value;
4763 // `-2147483648` is deliberately excluded: its magnitude is one past
4764 // `i32::MAX`, so the reference sends it through the constant pool and
4765 // negates at run time instead.
4766 if value > 0.0
4767 && negated == negated.trunc()
4768 && negated >= -(i32::MAX as f64)
4769 && negated < 0.0
4770 {
4771 self.push_number(negated);
4772 } else {
4773 self.push_number(value);
4774 self.emit(Opcode::Neg, &[]);
4775 }
4776 }
4777 ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
4778 ExprKind::Conditional { test, cons, alt } => {
4779 let else_label = self.new_label();
4780 let end_label = self.new_label();
4781 self.expr(test)?;
4782 self.emit_jump(Opcode::IfFalse, else_label, &[]);
4783 self.expr(cons)?;
4784 self.emit_jump(Opcode::Goto, end_label, &[]);
4785 self.place_label(else_label);
4786 self.expr(alt)?;
4787 self.place_label(end_label);
4788 }
4789 ExprKind::Assign { op, target, value } => {
4790 let discard = std::mem::take(&mut self.discard_root);
4791 self.assign(*op, target, value, discard)?
4792 }
4793 ExprKind::Update {
4794 op,
4795 argument,
4796 prefix,
4797 } => self.update(*op, argument, *prefix)?,
4798 ExprKind::Sequence(items) => {
4799 for (index, item) in items.iter().enumerate() {
4800 self.expr(item)?;
4801 if index + 1 != items.len() {
4802 self.emit(Opcode::Drop, &[]);
4803 }
4804 }
4805 }
4806 ExprKind::Call { .. } => self.chain_link_top(expr)?,
4807 ExprKind::Member { .. } => self.chain_link_top(expr)?,
4808 ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
4809 ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
4810 ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
4811 ExprKind::Template(template) => self.template_literal(template)?,
4812 ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
4813 ExprKind::New { callee, arguments } => {
4814 // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
4815 // The `dup` is not redundant: `call_constructor` takes the
4816 // constructor twice, once as the target and once as `new.target`,
4817 // which is what makes `new.target === C` inside the body.
4818 self.expr(callee)?;
4819 self.emit(Opcode::Dup, &[]);
4820 let args = arguments.as_deref().unwrap_or(&[]);
4821 if Self::has_spread(args) {
4822 // `C C array`: the duplicated callee is already both the target
4823 // and `new.target`, so no reordering is needed before `apply 1`.
4824 self.argument_array(args)?;
4825 self.emit(Opcode::Apply, &[Op::Int(1)]);
4826 return Ok(());
4827 }
4828 for argument in args {
4829 self.expr(argument)?;
4830 }
4831 self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
4832 }
4833 ExprKind::Class(class) => self.class_definition(class, true)?,
4834 ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
4835 ExprKind::Yield { argument, delegate } => {
4836 self.yield_expression(argument.as_deref(), *delegate)?
4837 }
4838 ExprKind::Await(argument) => self.await_expression(argument)?,
4839 ExprKind::RegExp { pattern, flags } => {
4840 // A literal is compiled *here*, at parse time, not when the line runs. The
4841 // spec is explicit that an invalid pattern is an early error (§12.9.4:
4842 // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
4843 // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
4844 // also validates `\p{…}` names: 163 conformance cases are patterns that have
4845 // to be rejected before any code runs.
4846 //
4847 // This is the whole reason the engine lives in its own crate rather than
4848 // inside `quickjs-pure`: the compiler could not depend on the interpreter
4849 // (`pure` depends on `compile`), but both need this.
4850 // The lexer already rejected an unknown or repeated flag, so an unparsable
4851 // flag string here would be a bug in the lexer rather than in the script;
4852 // fall back to the default flags instead of inventing a second message.
4853 let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
4854 let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
4855 SyntaxError::new(
4856 format!("invalid regular expression: {}", error.message),
4857 expr.span,
4858 )
4859 })?;
4860 // The tree is thrown away and rebuilt when the literal first runs: keeping it
4861 // would mean serialising the syntax tree into the function's constant pool,
4862 // and a literal is created once per evaluation of its expression anyway.
4863 let _ = parsed;
4864 // The pattern and its flags travel as two string constants; `regexp` builds
4865 // the object. A dedicated opcode (rather than a call to the constructor) is
4866 // what the reference does too, so that a literal never goes through the
4867 // public `RegExp` function and its string-coercion rules.
4868 self.push_string(&Wtf8::new(pattern));
4869 self.push_string(&Wtf8::new(flags));
4870 self.emit(Opcode::Regexp, &[]);
4871 }
4872 ExprKind::Arrow(func) => {
4873 let function = self.compile_function(func)?;
4874 let index = self.push_constant(Constant::Function(Box::new(function)));
4875 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4876 }
4877 ExprKind::Function(func) => {
4878 let function = self.compile_function_with_name(func, true)?;
4879 let index = self.push_constant(Constant::Function(Box::new(function)));
4880 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4881 }
4882 // `import.meta`: the host fills a per-module object at link time.
4883 ExprKind::ImportMeta => {
4884 self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
4885 }
4886 // `import("x")` compiles to a two-slot push followed by one opcode: the
4887 // specifier, then the options object. Both are evaluated, in that order, because
4888 // §13.3.10.1 numbers them that way and their side effects are observable — the
4889 // absent second argument is a literal `undefined`, which evaluates to nothing.
4890 ExprKind::ImportCall(specifier, options) => {
4891 self.expr(specifier)?;
4892 match options {
4893 Some(options) => self.expr(options)?,
4894 None => {
4895 self.emit(Opcode::Undefined, &[]);
4896 }
4897 }
4898 self.emit(Opcode::Import, &[]);
4899 }
4900 ExprKind::PrivateIn { name, object } => {
4901 // `#x in o`: the object, then the binding, then one opcode which decides what
4902 // to do with the second operand. A field's binding holds a symbol and the
4903 // answer is an own-property test; a method's holds a function and the answer
4904 // is a brand check — both live in `private_in`, so the compiler emits the
4905 // same instruction for either.
4906 self.expr(object)?;
4907 self.emit_var(VarAction::Get, &format!("#{}", name.name));
4908 self.emit(Opcode::PrivateIn, &[]);
4909 }
4910 _ => {
4911 return Err(SyntaxError::new(
4912 "this expression form is not supported by the compiler yet",
4913 expr.span,
4914 ));
4915 }
4916 }
4917 Ok(())
4918 }
4919
4920 /// Build one array holding the evaluated call arguments, which is how a call
4921 /// containing a spread is compiled: the reference does the same, building the
4922 /// list on the stack and handing it to `apply`.
4923 fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
4924 let elements: Vec<Option<ArrayElement>> = arguments
4925 .iter()
4926 .map(|argument| match &argument.unparen().kind {
4927 ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
4928 _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
4929 })
4930 .collect();
4931 self.array_literal(&elements, Span::default())
4932 }
4933
4934 /// Whether any argument is a spread, which is what selects the `apply` form.
4935 fn has_spread(arguments: &[Expr]) -> bool {
4936 arguments
4937 .iter()
4938 .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
4939 }
4940
4941 /// Compile `a${x}b`.
4942 ///
4943 /// A template is a `+` chain built left to right: the leading chunk (or an empty
4944 /// string when the template starts with a substitution), then for each
4945 /// substitution its value, `to_propkey` and `add`, then the following chunk when
4946 /// it is not empty. `to_propkey` is what makes a number or object substitute the
4947 /// way `ToString` would while leaving the result a string for `add` to
4948 /// concatenate.
4949 ///
4950 /// The chunk is an atom rather than a constant-pool string, because a non-empty
4951 /// chunk always lands where a value is pushed and `push_atom_value` is the
4952 /// instruction the reference uses for it; the empty first chunk has its own
4953 /// zero-byte form.
4954 fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
4955 let first = template.quasis.first();
4956 match first.and_then(|quasi| quasi.cooked.clone()) {
4957 Some(text) if !text.is_empty() => {
4958 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4959 }
4960 // Either the template begins with a substitution, or the chunk is
4961 // empty — in both cases the chain needs a string to start from.
4962 _ => self.emit(Opcode::PushEmptyString, &[]),
4963 }
4964 for (index, expression) in template.expressions.iter().enumerate() {
4965 self.expr(expression)?;
4966 self.emit(Opcode::ToPropkey, &[]);
4967 self.emit(Opcode::Add, &[]);
4968 if let Some(text) = template
4969 .quasis
4970 .get(index + 1)
4971 .and_then(|quasi| quasi.cooked.clone())
4972 && !text.is_empty()
4973 {
4974 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4975 self.emit(Opcode::Add, &[]);
4976 }
4977 }
4978 Ok(())
4979 }
4980
4981 /// Compile an object literal.
4982 ///
4983 /// The object is built in place: `object` pushes it, and each property leaves it
4984 /// on the stack with one field more, so no temporary is needed and later
4985 /// properties can overwrite earlier ones.
4986 ///
4987 /// The instruction depends on *how* the property was written, not on what kind
4988 /// of value it holds:
4989 ///
4990 /// | source | instruction |
4991 /// |---|---|
4992 /// | `{ a: v }` | `define_field a` |
4993 /// | `{ __proto__: v }` | `set_proto` |
4994 /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
4995 /// | `{ m() {} }` | `define_method m,4` |
4996 /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
4997 /// | `{ [k]() {} }` | `define_method_computed 4` |
4998 /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
4999 ///
5000 /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
5001 /// key itself, which is why the trailing `drop` is absent there too.
5002 /// `tag`…``: a call whose first argument is the call site's template object.
5003 ///
5004 /// The template object is a frozen array of the cooked chunks with a frozen `raw`
5005 /// array beside it, so `String.raw` can read the source text back. It is a constant
5006 /// because its contents never change; the reference builds one per call site and
5007 /// reuses it, while this builds one per evaluation, which only `tag` code that
5008 /// compares template objects across calls could tell apart.
5009 fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
5010 let cooked = quasi
5011 .quasis
5012 .iter()
5013 .map(|chunk| chunk.cooked.clone())
5014 .collect();
5015 let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
5016 let index = self.push_constant(Constant::Template { cooked, raw });
5017 let count = quasi.expressions.len() + 1;
5018 // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
5019 if let ExprKind::Member {
5020 object, property, ..
5021 } = &tag.unparen().kind
5022 {
5023 self.expr(object)?;
5024 match property {
5025 MemberProp::Ident(name) => {
5026 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
5027 }
5028 MemberProp::Computed(key) => {
5029 self.expr(key)?;
5030 self.emit(Opcode::GetArrayEl2, &[]);
5031 }
5032 MemberProp::Private(name) => {
5033 let binding = format!("#{}", name.name);
5034 let (kind, _) = self.private_use(&binding, tag.span)?;
5035 self.private_callee(&binding, kind)?;
5036 }
5037 }
5038 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5039 for expression in &quasi.expressions {
5040 self.expr(expression)?;
5041 }
5042 self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
5043 return Ok(());
5044 }
5045 self.expr(tag)?;
5046 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5047 for expression in &quasi.expressions {
5048 self.expr(expression)?;
5049 }
5050 self.emit(Opcode::Call, &[Op::Int(count as i32)]);
5051 Ok(())
5052 }
5053
5054 fn object_literal(
5055 &mut self,
5056 properties: &[ObjectProperty],
5057 span: Span,
5058 ) -> Result<(), SyntaxError> {
5059 self.emit(Opcode::Object, &[]);
5060 for property in properties {
5061 match property {
5062 ObjectProperty::Spread(value) => {
5063 // `copy_data_properties` takes the target, the source and an
5064 // exclusion list; a literal `null` means "exclude nothing".
5065 // Flag bit 1 copies symbols, bits 2/5 pick the source and the
5066 // exclusion list by stack offset.
5067 self.expr(spread_argument(value))?;
5068 self.emit(Opcode::Null, &[]);
5069 self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
5070 self.emit(Opcode::Drop, &[]);
5071 self.emit(Opcode::Drop, &[]);
5072 }
5073 ObjectProperty::Property {
5074 key,
5075 value,
5076 kind,
5077 shorthand,
5078 span: property_span,
5079 } => match key {
5080 PropName::Computed(key_expr) => {
5081 self.expr(key_expr)?;
5082 match kind {
5083 PropertyKind::Value => {
5084 self.emit(Opcode::ToPropkey, &[]);
5085 self.expr(value)?;
5086 self.set_name_if_anonymous_computed(value);
5087 self.emit(Opcode::DefineArrayEl, &[]);
5088 // `define_array_el` leaves the object and the key;
5089 // the key is no longer needed.
5090 self.emit(Opcode::Drop, &[]);
5091 }
5092 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5093 self.emit_method_function(value)?;
5094 self.emit(
5095 Opcode::DefineMethodComputed,
5096 &[Op::Int(define_method_flags(*kind))],
5097 );
5098 }
5099 }
5100 }
5101 PropName::Literal(key) => {
5102 let name = self.property_key_text(key, *property_span)?;
5103 match kind {
5104 PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5105 self.emit_method_function(value)?;
5106 self.emit(
5107 Opcode::DefineMethod,
5108 &[
5109 Op::Atom(Atom::from_wtf8(&name)),
5110 Op::Int(define_method_flags(*kind)),
5111 ],
5112 );
5113 }
5114 PropertyKind::Value => {
5115 self.expr(value)?;
5116 // `{__proto__: x}` sets the prototype instead of
5117 // creating a property; the shorthand `{__proto__}`
5118 // is an ordinary property and does not.
5119 if name == "__proto__" && !shorthand {
5120 self.emit(Opcode::SetProto, &[]);
5121 } else {
5122 self.set_name_if_anonymous(value, &name);
5123 self.emit(
5124 Opcode::DefineField,
5125 &[Op::Atom(Atom::from_wtf8(&name))],
5126 );
5127 }
5128 }
5129 }
5130 }
5131 PropName::Private(_) => {
5132 return Err(SyntaxError::new(
5133 "private names are not valid in object literals",
5134 *property_span,
5135 ));
5136 }
5137 },
5138 }
5139 }
5140 let _ = span;
5141 Ok(())
5142 }
5143
5144 /// Emit the function a method/accessor property defines.
5145 fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
5146 self.expr(value)
5147 }
5148
5149 /// The name a literal property key contributes.
5150 ///
5151 /// String keys are used as written. A numeric key is converted the way
5152 /// `ToString` would convert it, because the atom is made from that spelling:
5153 /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
5154 fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
5155 match key {
5156 PropKey::Str(text) => Ok(text.clone()),
5157 PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
5158 }
5159 }
5160
5161 /// Compile an optional chain.
5162 ///
5163 /// `?.` short-circuits the *whole remaining spine*, not just its own link:
5164 /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
5165 /// `undefined`. So the chain is compiled with one end label and every guard
5166 /// jumps to it. The parser hands us the extent of that spine as an
5167 /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
5168 /// exactly the scope the label has to cover.
5169 fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
5170 let end = self.new_label();
5171 self.chain_link(inner, end)?;
5172 self.place_label(end);
5173 Ok(())
5174 }
5175
5176 /// A member access or call reached from outside any optional chain.
5177 ///
5178 /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
5179 /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
5180 /// still created because [`Self::chain_link`] takes it, and placing it at the
5181 /// end is a no-op that keeps a single code path.
5182 fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
5183 let end = self.new_label();
5184 self.chain_link(expr, end)?;
5185 self.place_label(end);
5186 Ok(())
5187 }
5188
5189 /// One link of a chain, where `end` is the label a `?.` guard jumps to.
5190 fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
5191 match &expr.kind {
5192 ExprKind::Member {
5193 object,
5194 property,
5195 optional,
5196 } => {
5197 // `super.x` is not a lookup on a value: it starts at the home object's
5198 // prototype and keeps `this` as the receiver, so it cannot go through
5199 // `chain_link` and the ordinary field read.
5200 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5201 self.super_base();
5202 match property {
5203 MemberProp::Ident(name) => self.emit(
5204 Opcode::PushAtomValue,
5205 &[Op::Atom(Atom::from_text(&name.name))],
5206 ),
5207 MemberProp::Computed(index) => self.expr(index)?,
5208 MemberProp::Private(_) => {
5209 return Err(SyntaxError::new(
5210 "private fields are not supported by the compiler yet",
5211 expr.span,
5212 ));
5213 }
5214 }
5215 self.emit(Opcode::GetSuperValue, &[]);
5216 return Ok(());
5217 }
5218 self.chain_link(object, end)?;
5219 if *optional {
5220 self.optional_guard(end);
5221 }
5222 match property {
5223 // `.length` has its own opcode. The reference emits it for every
5224 // object, not just arrays, so a name-based rule is right and
5225 // cheaper than the generic field read.
5226 MemberProp::Ident(name) if name.name == "length" => {
5227 self.emit(Opcode::GetLength, &[]);
5228 }
5229 MemberProp::Ident(name) => {
5230 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
5231 }
5232 MemberProp::Computed(index) => {
5233 self.expr(index)?;
5234 self.emit(Opcode::GetArrayEl, &[]);
5235 }
5236 MemberProp::Private(name) => {
5237 // The binding comes from the class scope, so a read from outside the
5238 // class cannot name it at all. `?.` checks the object, not the field:
5239 // `o?.#x` guards on `o` being nullish.
5240 let binding = format!("#{}", name.name);
5241 let (kind, _) = self.private_use(&binding, expr.span)?;
5242 self.private_load(&binding, kind, expr.span)?;
5243 }
5244 }
5245 Ok(())
5246 }
5247 ExprKind::Call {
5248 callee,
5249 arguments,
5250 optional,
5251 } => {
5252 // `o.m(args)` has to pass `o` as `this`, which a plain `call`
5253 // cannot: it reads the function and then calls it with no
5254 // receiver at all. The reference's answer is to keep the object
5255 // under the function value — `get_field2` reads a field and leaves
5256 // its base in place — and to use `call_method`, which takes the
5257 // receiver from the stack. Missing this does not just cost an
5258 // instruction, it loses the `this` binding.
5259 if let ExprKind::Member {
5260 object,
5261 property,
5262 optional: member_optional,
5263 } = &callee.unparen().kind
5264 {
5265 // `super.m()` reads the method off the home object's prototype but
5266 // calls it with `this`, so the receiver goes under the read instead of
5267 // being replaced by it.
5268 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5269 self.super_base();
5270 match property {
5271 MemberProp::Ident(name) => self.emit(
5272 Opcode::PushAtomValue,
5273 &[Op::Atom(Atom::from_text(&name.name))],
5274 ),
5275 MemberProp::Computed(index) => self.expr(index)?,
5276 MemberProp::Private(_) => {
5277 return Err(SyntaxError::new(
5278 "private fields are not supported by the compiler yet",
5279 expr.span,
5280 ));
5281 }
5282 }
5283 // The two-output form would drop the receiver; this one replaces
5284 // the prototype and the key, leaving `this` underneath.
5285 self.emit(Opcode::GetArrayEl, &[]);
5286 if Self::has_spread(arguments) {
5287 self.argument_array(arguments)?;
5288 self.emit(Opcode::Perm3, &[]);
5289 self.emit(Opcode::Apply, &[Op::Int(0)]);
5290 return Ok(());
5291 }
5292 for argument in arguments {
5293 self.expr(argument)?;
5294 }
5295 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5296 return Ok(());
5297 }
5298 self.chain_link(object, end)?;
5299 if *member_optional {
5300 self.optional_guard(end);
5301 }
5302 match property {
5303 MemberProp::Ident(name) => {
5304 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5305 }
5306 MemberProp::Computed(index) => {
5307 self.expr(index)?;
5308 // The key is not needed after the read, so this is the
5309 // two-output form: object, value.
5310 self.emit(Opcode::GetArrayEl2, &[]);
5311 }
5312 MemberProp::Private(name) => {
5313 // The receiver is already under the callee, which is exactly the
5314 // shape `call_method` and `apply` want — so nothing is dropped.
5315 let binding = format!("#{}", name.name);
5316 let (kind, _) = self.private_use(&binding, expr.span)?;
5317 self.private_callee(&binding, kind)?;
5318 }
5319 }
5320 if Self::has_spread(arguments) {
5321 // Stack is `obj func`; the array goes on top, then `perm3`
5322 // reorders to the `func this array` that `apply` wants.
5323 self.argument_array(arguments)?;
5324 self.emit(Opcode::Perm3, &[]);
5325 self.emit(Opcode::Apply, &[Op::Int(0)]);
5326 return Ok(());
5327 }
5328 for argument in arguments {
5329 self.expr(argument)?;
5330 }
5331 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5332 return Ok(());
5333 }
5334 // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
5335 // with `get_field2` so the base stays under it, and on the short-circuit
5336 // path pushes an extra `undefined` as a placeholder receiver — the call
5337 // then throws, which is what calling a missing optional chain should do.
5338 if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
5339 && let ExprKind::Member {
5340 object,
5341 property,
5342 optional: member_optional,
5343 } = &inner.unparen().kind
5344 {
5345 let call = self.new_label();
5346 // A guard target of its own: the outer `end` skips the whole
5347 // expression, and a short-circuited receiver still has to reach the
5348 // call so that calling it throws.
5349 let short = self.new_label();
5350 self.chain_link(object, end)?;
5351 if *member_optional {
5352 self.optional_guard(short);
5353 }
5354 match property {
5355 MemberProp::Ident(name) => {
5356 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5357 }
5358 MemberProp::Computed(index) => {
5359 self.expr(index)?;
5360 self.emit(Opcode::GetArrayEl2, &[]);
5361 }
5362 MemberProp::Private(name) => {
5363 let binding = format!("#{}", name.name);
5364 let (kind, _) = self.private_use(&binding, expr.span)?;
5365 self.private_callee(&binding, kind)?;
5366 }
5367 }
5368 self.emit_jump(Opcode::Goto, call, &[]);
5369 self.place_label(short);
5370 self.emit(Opcode::Undefined, &[]);
5371 self.place_label(call);
5372 if Self::has_spread(arguments) {
5373 self.argument_array(arguments)?;
5374 self.emit(Opcode::Perm3, &[]);
5375 self.emit(Opcode::Apply, &[Op::Int(0)]);
5376 return Ok(());
5377 }
5378 for argument in arguments {
5379 self.expr(argument)?;
5380 }
5381 self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5382 return Ok(());
5383 }
5384 self.chain_link(callee, end)?;
5385 if *optional {
5386 self.optional_guard(end);
5387 }
5388 if Self::has_spread(arguments) {
5389 // `func array -> func undefined array`, which is the plain-call
5390 // form of `apply`: the receiver is `undefined`.
5391 self.argument_array(arguments)?;
5392 self.emit(Opcode::Undefined, &[]);
5393 self.emit(Opcode::Swap, &[]);
5394 self.emit(Opcode::Apply, &[Op::Int(0)]);
5395 return Ok(());
5396 }
5397 for argument in arguments {
5398 self.expr(argument)?;
5399 }
5400 self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
5401 Ok(())
5402 }
5403 _ => self.expr(expr),
5404 }
5405 }
5406
5407 /// Compile `expr` as a tail call when it is one, reporting whether it was.
5408 ///
5409 /// `tail_call` reuses the current frame instead of pushing a new one, so a
5410 /// tail-recursive function runs in constant stack space. It also has to be the
5411 /// *last* thing the function does, which is why only a `return` reaches here.
5412 fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
5413 let ExprKind::Call {
5414 callee,
5415 arguments,
5416 optional: false,
5417 } = &expr.unparen().kind
5418 else {
5419 return Ok(false);
5420 };
5421 // A spread call has no tail form: `tail_call` takes its arguments one at a time off
5422 // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
5423 // as an ordinary call costs the one frame the optimisation was saving and keeps the
5424 // semantics — the alternative was reaching the spread expression below and failing
5425 // with "this expression form is not supported", which is how `return super.m(...a)`
5426 // stopped compiling. Checked before anything is emitted, because the decision cannot
5427 // be taken back once `super_base` or a `get_field2` is on the stack.
5428 if Self::has_spread(arguments) {
5429 return Ok(false);
5430 }
5431 let end = self.new_label();
5432 if let ExprKind::Member {
5433 object,
5434 property,
5435 optional: false,
5436 } = &callee.unparen().kind
5437 {
5438 // `super.m()` in tail position is still an ordinary method call with `this`
5439 // as the receiver; only the read of the method differs.
5440 if matches!(object.unparen().kind, ExprKind::SuperProp) {
5441 self.super_base();
5442 match property {
5443 MemberProp::Ident(name) => self.emit(
5444 Opcode::PushAtomValue,
5445 &[Op::Atom(Atom::from_text(&name.name))],
5446 ),
5447 MemberProp::Computed(index) => self.expr(index)?,
5448 MemberProp::Private(_) => return Ok(false),
5449 }
5450 self.emit(Opcode::GetArrayEl, &[]);
5451 for argument in arguments {
5452 self.expr(argument)?;
5453 }
5454 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5455 self.place_label(end);
5456 return Ok(true);
5457 }
5458 self.chain_link(object, end)?;
5459 match property {
5460 MemberProp::Ident(name) => {
5461 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5462 }
5463 MemberProp::Computed(index) => {
5464 self.expr(index)?;
5465 self.emit(Opcode::GetArrayEl2, &[]);
5466 }
5467 MemberProp::Private(_) => return Ok(false),
5468 }
5469 for argument in arguments {
5470 self.expr(argument)?;
5471 }
5472 self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5473 self.place_label(end);
5474 return Ok(true);
5475 }
5476 self.chain_link(callee, end)?;
5477 for argument in arguments {
5478 self.expr(argument)?;
5479 }
5480 self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
5481 self.place_label(end);
5482 Ok(true)
5483 }
5484
5485 /// The `?.` guard: keep the value if it is neither null nor undefined,
5486 /// otherwise replace it with `undefined` and leave the whole chain.
5487 fn optional_guard(&mut self, end: Label) {
5488 let cont = self.new_label();
5489 self.emit(Opcode::Dup, &[]);
5490 self.emit(Opcode::IsUndefinedOrNull, &[]);
5491 self.emit_jump(Opcode::IfFalse, cont, &[]);
5492 self.emit(Opcode::Drop, &[]);
5493 self.emit(Opcode::Undefined, &[]);
5494 self.emit_jump(Opcode::Goto, end, &[]);
5495 self.place_label(cont);
5496 }
5497
5498 fn push_number(&mut self, value: f64) {
5499 // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
5500 // goes into the constant pool.
5501 if value == value.trunc() && value.abs() <= i32::MAX as f64 {
5502 let int = value as i32;
5503 if (-1..=7).contains(&int) {
5504 self.emit(Opcode::PushI32, &[Op::Int(int)]);
5505 return;
5506 }
5507 if (-128..=127).contains(&int) {
5508 self.emit(Opcode::PushI8, &[Op::Int(int)]);
5509 return;
5510 }
5511 if (-32768..=32767).contains(&int) {
5512 self.emit(Opcode::PushI16, &[Op::Int(int)]);
5513 return;
5514 }
5515 self.emit(Opcode::PushI32, &[Op::Int(int)]);
5516 return;
5517 }
5518 let index = self.push_constant(Constant::Number(value));
5519 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5520 }
5521
5522 /// Push a `BigInt` literal.
5523 ///
5524 /// A value that fits an `i32` uses the immediate form, which is what the reference
5525 /// emits too; anything larger goes into the constant pool, because the operand of
5526 /// `push_bigint` is only four bytes wide.
5527 fn push_bigint(&mut self, digits: &str, radix: u32) {
5528 if radix == 10
5529 && let Ok(value) = digits.parse::<i64>()
5530 && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
5531 {
5532 self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
5533 return;
5534 }
5535 let index = self.push_constant(Constant::BigInt {
5536 digits: digits.to_string(),
5537 radix,
5538 });
5539 self.emit(Opcode::PushConst, &[Op::Const(index)]);
5540 }
5541
5542 fn push_string(&mut self, text: &Wtf8) {
5543 if text.is_empty() {
5544 self.emit(Opcode::PushEmptyString, &[]);
5545 return;
5546 }
5547 self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
5548 }
5549
5550 /// Name an anonymous function from the binding it is assigned to.
5551 ///
5552 /// `var f = function(){}` produces a function whose `name` is `f`, which the
5553 /// runtime cannot know without being told: the function object is created
5554 /// before the store. `set_name` carries the name across.
5555 fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
5556 if value.is_anonymous_function_definition() {
5557 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
5558 }
5559 }
5560
5561 /// The same, for a computed key: the name comes from the value on the stack
5562 /// rather than from an atom, so a different instruction carries it.
5563 fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
5564 if value.is_anonymous_function_definition() {
5565 self.emit(Opcode::SetNameComputed, &[]);
5566 }
5567 }
5568
5569 /// Compile a function body that exists only in the compiler's head — a class's
5570 /// implicit constructor or its field initialiser.
5571 ///
5572 /// Everything structural is the same as a written function: a fresh `FnState`, its
5573 /// own body block, and resolution while the frame is still on the stack. Only the
5574 /// statements differ.
5575 fn compile_synthetic_function(
5576 &mut self,
5577 name: &str,
5578 strict: bool,
5579 span: Span,
5580 body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
5581 ) -> Result<CompiledFunction, SyntaxError> {
5582 let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
5583 state.span = Some((span.start.offset as usize, span.end.offset as usize));
5584 state.strict = strict;
5585 state.created_in_block = self.cur().current_block;
5586 state.with_names = self.cur().with_names.clone();
5587 state.line = span.start.line;
5588 state.column = span.start.column;
5589 let depth = self.stack.len();
5590 self.stack.push(state);
5591 let body_key = span.start.offset as u64;
5592 self.push_block(body_key, NO_PARENT);
5593 self.state().body_block = body_key;
5594 let result = (|| {
5595 self.emit_scope_enter(body_key);
5596 body(self)?;
5597 if self.end_is_reachable() {
5598 self.emit(Opcode::ReturnUndef, &[]);
5599 }
5600 Ok(())
5601 })();
5602 if result.is_err() {
5603 self.stack.truncate(depth);
5604 return result.map(|()| unreachable!());
5605 }
5606 Ok(self.finish_current())
5607 }
5608
5609 /// The implicit return of a class constructor.
5610 ///
5611 /// A constructor that falls off the end initialises its instance fields first, and a
5612 /// derived one returns `this` — which is what makes `new D()` the object `super()`
5613 /// built rather than `undefined`.
5614 fn emit_class_constructor_tail(&mut self) {
5615 match self.cur().ctor_kind {
5616 CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
5617 // Nothing to install: a base constructor did it in its prologue and a derived
5618 // one at each `super()` site, which is where `this` first exists.
5619 CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
5620 CtorKind::Derived => {
5621 // `get_loc_check` rather than `get_loc`: reaching the end without ever
5622 // running `super()` is a ReferenceError, not `undefined`.
5623 self.emit_var(VarAction::Get, "this");
5624 self.emit(Opcode::Return, &[]);
5625 }
5626 }
5627 }
5628
5629 /// `yield expr` / `yield* expr`.
5630 ///
5631 /// The suspension itself is one instruction: the value is on the stack, `yield` hands
5632 /// it to the caller and parks the frame. On resume the stack holds the value the
5633 /// caller passed *and* a "magic" number saying which method resumed it — `next`
5634 /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
5635 /// `if_false <continue>` asks whether this was an ordinary `next`:
5636 ///
5637 /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
5638 /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
5639 /// and uses the value sitting under the magic number.
5640 ///
5641 /// A `throw` never reaches here: the interpreter unwinds instead (see
5642 /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
5643 fn yield_expression(
5644 &mut self,
5645 argument: Option<&Expr>,
5646 delegate: bool,
5647 ) -> Result<(), SyntaxError> {
5648 if delegate {
5649 return self.yield_star(argument);
5650 }
5651 // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
5652 // does the same for the `return(v)` that can resume it — which is why an async
5653 // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
5654 // generator's is just `yield`.
5655 let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
5656 match argument {
5657 Some(value) => self.expr(value)?,
5658 None => self.emit(Opcode::Undefined, &[]),
5659 }
5660 if is_async {
5661 self.emit(Opcode::Await, &[]);
5662 self.state().has_await = true;
5663 }
5664 self.emit(Opcode::Yield, &[]);
5665 let resume = self.new_label();
5666 self.emit_jump(Opcode::IfFalse, resume, &[]);
5667 // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
5668 // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
5669 // finished the generator and never ran the `finally`.
5670 if is_async {
5671 self.emit(Opcode::Await, &[]);
5672 }
5673 self.emit_unwind_for_return(true);
5674 self.emit(Opcode::ReturnAsync, &[]);
5675 self.place_label(resume);
5676 // Nothing is emitted here: the value the caller passed to `next` *is* the value
5677 // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
5678 // it through the ordinary expression-statement discard.
5679 Ok(())
5680 }
5681
5682 /// `yield* iterable`.
5683 ///
5684 /// The shape is the reference's, and it is a fall-through chain rather than a
5685 /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
5686 /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
5687 /// the inner iterator and finishes, `throw` forwards the exception into it and
5688 /// continues only if it has a `throw` method.
5689 ///
5690 /// The stack is `iter next catch value` throughout, `catch` being the offset
5691 /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
5692 fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
5693 match argument {
5694 Some(value) => self.expr(value)?,
5695 // The parser rejects a bare `yield*`, so this is unreachable in practice.
5696 None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
5697 }
5698 // `for await of` is the same protocol as `for of` with two differences that matter
5699 // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
5700 // every `next()` result is a promise the delegate has to await.
5701 let is_async = self.cur().kind.is_async();
5702 self.emit(
5703 if is_async {
5704 Opcode::ForAwaitOfStart
5705 } else {
5706 Opcode::ForOfStart
5707 },
5708 &[],
5709 );
5710 self.emit(Opcode::Drop, &[]);
5711 self.emit(Opcode::Undefined, &[]);
5712 self.emit(Opcode::Undefined, &[]);
5713 let next = self.new_label();
5714 let resume = self.new_label();
5715 let finished = self.new_label();
5716 let rethrow = self.new_label();
5717 let throw_no_method = self.new_label();
5718 let done = self.new_label();
5719 self.place_label(next);
5720 self.emit(Opcode::IteratorNext, &[]);
5721 if is_async {
5722 self.emit(Opcode::Await, &[]);
5723 self.state().has_await = true;
5724 }
5725 self.emit(Opcode::IteratorCheckObject, &[]);
5726 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5727 self.emit_jump(Opcode::IfTrue, done, &[]);
5728 // The suspension. `resume` is both the label the return path jumps back to in order
5729 // to yield one more value and where the caller's answer arrives, as the value
5730 // followed by the magic number.
5731 //
5732 // The two forms differ in what they hand the suspension: `yield_star` takes the
5733 // result object itself, `async_yield_star` takes `.value`, because an async
5734 // generator awaits and re-wraps whatever it yields.
5735 self.place_label(resume);
5736 if is_async {
5737 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5738 self.emit(Opcode::AsyncYieldStar, &[]);
5739 } else {
5740 self.emit(Opcode::YieldStar, &[]);
5741 }
5742 self.emit(Opcode::Dup, &[]);
5743 self.emit_jump(Opcode::IfTrue, rethrow, &[]);
5744 self.emit(Opcode::Drop, &[]);
5745 self.emit_jump(Opcode::Goto, next, &[]);
5746
5747 // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
5748 self.place_label(rethrow);
5749 self.emit(Opcode::PushI32, &[Op::Int(2)]);
5750 self.emit(Opcode::StrictEq, &[]);
5751 self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
5752 // A `return` closes the inner iterator; if it had none, the delegate simply
5753 // finishes with the requested value. In an async generator both the call and its
5754 // result are awaited, because the inner `return` may itself be async.
5755 if is_async {
5756 self.emit(Opcode::Await, &[]);
5757 }
5758 self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
5759 self.emit_jump(Opcode::IfTrue, finished, &[]);
5760 if is_async {
5761 self.emit(Opcode::Await, &[]);
5762 }
5763 self.emit(Opcode::IteratorCheckObject, &[]);
5764 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5765 self.emit_jump(Opcode::IfFalse, resume, &[]);
5766 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5767 self.place_label(finished);
5768 self.emit(Opcode::Nip, &[]);
5769 self.emit(Opcode::Nip, &[]);
5770 self.emit(Opcode::Nip, &[]);
5771 // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
5772 // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
5773 // awaits the value in an async generator and then runs the same `finally`/iterator
5774 // unwinding a written `return` would. Skipping the unwinding made
5775 // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
5776 if is_async {
5777 self.emit(Opcode::Await, &[]);
5778 }
5779 self.emit_unwind_for_return(true);
5780 self.emit(Opcode::ReturnAsync, &[]);
5781
5782 // `throw(e)`: forward it into the inner iterator.
5783 self.place_label(throw_no_method);
5784 self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
5785 let no_throw = self.new_label();
5786 self.emit_jump(Opcode::IfTrue, no_throw, &[]);
5787 if is_async {
5788 self.emit(Opcode::Await, &[]);
5789 }
5790 self.emit(Opcode::IteratorCheckObject, &[]);
5791 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5792 self.emit_jump(Opcode::IfFalse, resume, &[]);
5793 self.emit_jump(Opcode::Goto, done, &[]);
5794 // No `throw` method: close the iterator, then report the spec's TypeError. The
5795 // `if_true` before the `await` is the reference's shape — the flag it consumes is
5796 // what `iterator_call` leaves behind, and a close that *did* find no `return`
5797 // method has nothing to await.
5798 self.place_label(no_throw);
5799 self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
5800 let no_close = self.new_label();
5801 self.emit_jump(Opcode::IfTrue, no_close, &[]);
5802 if is_async {
5803 self.emit(Opcode::Await, &[]);
5804 }
5805 self.place_label(no_close);
5806 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
5807
5808 // The inner iterator finished: the delegate's value is the `yield*` expression's
5809 // value, so it is left on the stack for whatever consumes it.
5810 self.place_label(done);
5811 self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5812 self.emit(Opcode::Nip, &[]);
5813 self.emit(Opcode::Nip, &[]);
5814 self.emit(Opcode::Nip, &[]);
5815 Ok(())
5816 }
5817
5818 /// `await expr`: exactly one instruction.
5819 ///
5820 /// No resume-magic branch follows it. The reference's `await` leaves a single value
5821 /// on the stack and completion is signalled by the `return_async` at the end of the
5822 /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
5823 /// reference never emits, and a `for await` loop — which reaches `await` through the
5824 /// same opcode — would then spill a value the loop's unpacking does not expect.
5825 fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
5826 self.expr(argument)?;
5827 self.emit(Opcode::Await, &[]);
5828 self.state().has_await = true;
5829 Ok(())
5830 }
5831
5832 /// The `super` base: the receiver followed by the home object's prototype.
5833 ///
5834 /// Everything `super` does needs both. A *read* starts at the prototype but reports
5835 /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
5836 /// prototype but calls it with the receiver.
5837 fn super_base(&mut self) {
5838 self.this_expression();
5839 self.home_object();
5840 self.emit(Opcode::GetSuper, &[]);
5841 }
5842
5843 /// `[[HomeObject]]` as `super` sees it.
5844 ///
5845 /// A method, a constructor and a field initialiser each carry one — `set_home_object`
5846 /// put it there — so for them the special object *is* the answer. An arrow and a
5847 /// static block have none: they read the enclosing function's, which has to be
5848 /// materialised into a local, exactly as `this` is for an arrow.
5849 ///
5850 /// The name matches what the reference stores, so the disassembly agrees; it is not a
5851 /// name any program can write.
5852 fn home_object(&mut self) {
5853 if !self.cur().is_arrow {
5854 self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
5855 return;
5856 }
5857 if let Some(target) = self.enclosing_function() {
5858 self.state_at(target).needs_home_object_local = true;
5859 self.declare_at(target, HOME_OBJECT);
5860 }
5861 self.emit_var(VarAction::Get, HOME_OBJECT);
5862 }
5863
5864 /// `super(args)`: construct the parent class and adopt the result as `this`.
5865 ///
5866 /// The parent is the prototype of the constructor that is running, which is exactly
5867 /// what `extends` set up. `new.target` is passed through unchanged so that
5868 /// `new.target` inside the parent is the class actually being constructed.
5869 fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5870 self.active_func_expression();
5871 self.emit(Opcode::GetSuper, &[]);
5872 self.new_target_expression();
5873 if Self::has_spread(arguments) {
5874 self.argument_array(arguments)?;
5875 self.emit(Opcode::Apply, &[Op::Int(1)]);
5876 } else {
5877 for argument in arguments {
5878 self.expr(argument)?;
5879 }
5880 self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
5881 }
5882 // The value stays on the stack: `super()` is an expression, and a derived
5883 // constructor's `this` may only be initialised once.
5884 self.emit(Opcode::Dup, &[]);
5885 self.emit_var(VarAction::PutInitChecked, "this");
5886 // Instance fields are installed here, not at the top of the body: a derived
5887 // constructor has no `this` to install them on until `super()` returns. The
5888 // reference emits the same call at every `super()` site.
5889 self.call_field_initialiser();
5890 Ok(())
5891 }
5892
5893 /// `this` as a local, which every class constructor and field initialiser needs.
5894 ///
5895 /// The reference materialises the receiver into a local rather than reading
5896 /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
5897 /// and a field initialiser has to see the final value.
5898 fn begin_this_local(&mut self) {
5899 self.declare_hidden_local("this", VarKind::Normal);
5900 self.emit(Opcode::PushThis, &[]);
5901 self.emit_var(VarAction::Put, "this");
5902 // The store is already at the top of the body, so `provide_this_local` has
5903 // nothing left to prepend. Without this the initialiser ended up with
5904 // `push_this; put_loc0 this` twice whenever the class also held a field
5905 // initialiser whose body read `this` through an arrow.
5906 self.state().has_this_prologue = true;
5907 }
5908
5909 /// Compile a constructor the class wrote.
5910 ///
5911 /// The flags have to be in place before the body is compiled, but
5912 /// `compile_function_with_name` creates its own state — so the caller's state is
5913 /// marked instead and the new one inherits it. That is the same trick the parameter
5914 /// prologue uses, and it keeps one code path for both.
5915 fn compile_class_constructor(
5916 &mut self,
5917 func: &ast::Function,
5918 has_heritage: bool,
5919 ) -> Result<CompiledFunction, SyntaxError> {
5920 let saved = self.cur().ctor_kind;
5921 self.state().class_ctor_pending = Some(if has_heritage {
5922 CtorKind::Derived
5923 } else {
5924 CtorKind::Base
5925 });
5926 let result = self.compile_function_with_name(func, false);
5927 self.state().ctor_kind = saved;
5928 self.state().class_ctor_pending = None;
5929 result
5930 }
5931
5932 /// The constructor a class gets when it does not declare one.
5933 ///
5934 /// A base class's is empty; a derived class's forwards every argument to the parent
5935 /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
5936 /// instance field initialiser afterwards when the class has fields, which is why the
5937 /// initialiser is captured rather than inlined.
5938 fn compile_implicit_constructor(
5939 &mut self,
5940 class: &Class,
5941 has_heritage: bool,
5942 ) -> Result<CompiledFunction, SyntaxError> {
5943 self.compile_synthetic_function(
5944 "",
5945 true,
5946 Span::new(class.body_end, class.body_end),
5947 |compiler| {
5948 if has_heritage {
5949 // A derived constructor's `this` does not exist until `super()` returns,
5950 // so it starts in the dead zone and `init_ctor` fills it.
5951 compiler.declare("this", VarDef::lexical("this"));
5952 compiler.emit(
5953 Opcode::SetLocUninitialized,
5954 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5955 );
5956 compiler.emit(Opcode::InitCtor, &[]);
5957 compiler.emit(
5958 Opcode::PutLocCheckInit,
5959 &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5960 );
5961 } else {
5962 compiler.begin_this_local();
5963 compiler.emit(Opcode::CheckCtor, &[]);
5964 }
5965 compiler.call_field_initialiser();
5966 // A derived constructor returns `this`, the object `super()` built. Without
5967 // this the implicit constructor fell through to `return_undef`, and `new B()`
5968 // handed back the empty object `construct` had made instead of the one the
5969 // parent constructor initialised.
5970 if has_heritage {
5971 compiler.emit_var(VarAction::Get, "this");
5972 compiler.emit(Opcode::Return, &[]);
5973 }
5974 Ok(())
5975 },
5976 )
5977 }
5978
5979 /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
5980 ///
5981 /// A class with no instance fields leaves the binding `undefined`, and calling it
5982 /// would throw; the reference emits the same guard rather than branching at compile
5983 /// time because a class can be extended by a subclass whose fields still have to run.
5984 fn call_field_initialiser(&mut self) {
5985 let skip = self.new_label();
5986 self.emit_var(VarAction::Get, "<class_fields_init>");
5987 self.emit(Opcode::Dup, &[]);
5988 self.emit_jump(Opcode::IfFalse, skip, &[]);
5989 self.emit_var(VarAction::Get, "this");
5990 self.emit(Opcode::Swap, &[]);
5991 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
5992 self.place_label(skip);
5993 self.emit(Opcode::Drop, &[]);
5994 }
5995
5996 /// The function that defines one class's fields on `this`, and runs its static blocks.
5997 ///
5998 /// `define_field` rather than `put_field`: a field is an own property created
5999 /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
6000 /// `x = 1` field must not call the setter.
6001 ///
6002 /// One function serves the whole class: it is called once per instance (or once, for
6003 /// the static half) and walks the members in source order. Static blocks are compiled
6004 /// into the same function because they *are* part of the same sequence — `static a =
6005 /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
6006 /// different values, so the two kinds cannot be split apart.
6007 fn compile_field_initialiser(
6008 &mut self,
6009 items: &[StaticInitItem<'_>],
6010 span: Span,
6011 instance: bool,
6012 add_brand: bool,
6013 ) -> Result<CompiledFunction, SyntaxError> {
6014 self.compile_synthetic_function("", true, span, |compiler| {
6015 // A field initialiser and a static block are not functions, so neither has an
6016 // `arguments` of its own; see `FnState::no_arguments_binding`.
6017 let current = compiler.stack.len() - 1;
6018 compiler.stack[current].no_arguments_binding = true;
6019 if instance {
6020 // An instance initialiser always carries a `<home_object>` local, because the
6021 // brand block below reads it — even when that block turns out to be dead. The
6022 // reference has the same artefact, and the store is visible in its dump.
6023 let current = compiler.stack.len() - 1;
6024 compiler.stack[current].needs_home_object_local = true;
6025 }
6026 compiler.begin_this_local();
6027 if instance {
6028 // `this` gets the brand the prototype created, before any field is defined —
6029 // which is what makes `#m()` usable from inside a field initialiser.
6030 //
6031 // The reference always emits `push_false; if_false L; this; home; add_brand;
6032 // L:` and patches the `push_false` to `push_true` from the class parse when
6033 // the class has private methods; either way the branch folds, but the *mark*
6034 // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
6035 // `this` local from being fused into a `set_loc`.
6036 let skip = compiler.new_label();
6037 if add_brand {
6038 compiler.emit(Opcode::PushTrue, &[]);
6039 } else {
6040 compiler.emit(Opcode::PushFalse, &[]);
6041 }
6042 compiler.emit_jump(Opcode::IfFalse, skip, &[]);
6043 compiler.emit_var(VarAction::Get, "this");
6044 compiler.emit_var(VarAction::Get, HOME_OBJECT);
6045 compiler.emit(Opcode::AddBrand, &[]);
6046 compiler.place_label(skip);
6047 }
6048 for item in items {
6049 match item {
6050 StaticInitItem::Field(key, value) => {
6051 // A private field is *defined*, not assigned: `define_private_field`
6052 // reads `obj symbol value`, and its point is that it fails on a
6053 // receiver that is not this class's — which `put_field` would not.
6054 //
6055 // The three shapes are the reference's: `define_field <atom>` for a
6056 // static name, `define_array_el` for a key that is only known at run
6057 // time (`obj key value`), `define_private_field` for `#x`, and a
6058 // computed key is read from its binding rather than recomputed.
6059 compiler.emit_var(VarAction::Get, "this");
6060 match key {
6061 FieldKey::Private(binding) | FieldKey::Computed(binding) => {
6062 compiler.emit_var(VarAction::Get, binding);
6063 }
6064 FieldKey::Literal(_) => {}
6065 }
6066 match value {
6067 Some(value) => compiler.expr(value)?,
6068 None => compiler.emit(Opcode::Undefined, &[]),
6069 }
6070 match key {
6071 FieldKey::Literal(literal) => {
6072 let text = compiler.property_key_text(literal, span)?;
6073 compiler
6074 .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
6075 }
6076 FieldKey::Computed(_) => {
6077 compiler.emit(Opcode::DefineArrayEl, &[]);
6078 // `define_array_el` leaves `obj key`; the key is consumed by
6079 // the copy the pattern machinery wants, so both go.
6080 compiler.emit(Opcode::Drop, &[]);
6081 }
6082 FieldKey::Private(_) => {
6083 compiler.emit(Opcode::DefinePrivateField, &[]);
6084 }
6085 }
6086 compiler.emit(Opcode::Drop, &[]);
6087 }
6088 StaticInitItem::Block { body, body_start } => {
6089 let block = compiler.compile_static_block(body, *body_start)?;
6090 let index = compiler.push_constant(Constant::Function(Box::new(block)));
6091 // `this fclosure`, so `call_method` finds the receiver below the
6092 // callee: the block runs with `this` bound to the class.
6093 compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
6094 compiler.emit_var(VarAction::Get, "this");
6095 compiler.emit(Opcode::Swap, &[]);
6096 compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
6097 // Nothing the block evaluates is wanted; its effects are the point.
6098 compiler.emit(Opcode::Drop, &[]);
6099 }
6100 }
6101 }
6102 Ok(())
6103 })
6104 }
6105
6106 /// Compile a `static { … }` body into the function the class calls for it.
6107 ///
6108 /// Shaped like an arrow, because that is the one function form with no `this`,
6109 /// `new.target` or `arguments` of its own: all three reach the enclosing static
6110 /// initialiser, and through it the class. `arguments` never gets that far — the parser
6111 /// rejects the reference — but `this` and `super` both depend on it.
6112 ///
6113 /// The body is hoisted like a function body's, because the reference parses it as one:
6114 /// `var` inside a block is a local of the block's function, not of whatever encloses
6115 /// the class.
6116 fn compile_static_block(
6117 &mut self,
6118 body: &[Stmt],
6119 body_start: Position,
6120 ) -> Result<CompiledFunction, SyntaxError> {
6121 let mut state = FnState::new(String::new(), FunctionKind::Normal);
6122 // Class bodies are strict, so a static block is too.
6123 state.strict = true;
6124 // The one property that makes this an arrow: nothing of its own to bind `this` to,
6125 // so `this` and `super` come from the initialiser that calls it.
6126 state.is_arrow = true;
6127 state.created_in_block = self.cur().current_block;
6128 state.with_names = self.cur().with_names.clone();
6129 state.line = body_start.line;
6130 state.column = body_start.column;
6131 let depth = self.stack.len();
6132 self.stack.push(state);
6133 let body_key = body_start.offset as u64;
6134 self.push_block(body_key, NO_PARENT);
6135 self.state().body_block = body_key;
6136 let result = (|| {
6137 self.hoist(body, body_key)?;
6138 self.emit_scope_enter(body_key);
6139 for statement in body {
6140 self.stmt(statement)?;
6141 }
6142 if self.end_is_reachable() {
6143 self.emit(Opcode::ReturnUndef, &[]);
6144 }
6145 Ok(())
6146 })();
6147 if result.is_err() {
6148 self.stack.truncate(depth);
6149 return result.map(|()| unreachable!());
6150 }
6151 Ok(self.finish_current())
6152 }
6153
6154 /// Compile a class, leaving the constructor on the stack when `keep`.
6155 ///
6156 /// The shape follows the reference: the class body is its own scope holding the
6157 /// class's *inner* name as a `const` — which is what lets a method refer to the
6158 /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
6159 /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
6160 /// on the top of the stack: the prototype for instance members, the constructor
6161 /// itself for `static` ones, which is why a static member costs an extra `swap`.
6162 fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
6163 let parent_block = self.cur().current_block;
6164 let key = class.span.start.offset as u64;
6165 self.push_block(key, parent_block);
6166 let name = class.name.as_ref().map(|ident| ident.name.clone());
6167 // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
6168 // resolves `E` without a global lookup. An *unnamed* class expression has no such
6169 // binding, and `define_class` is handed the empty name.
6170 if let Some(name) = &name {
6171 self.declare(name, VarDef::constant(name.clone()));
6172 }
6173 self.emit_scope_enter(key);
6174
6175 // The heritage clause is evaluated outside the class's own scope: it cannot see
6176 // the class binding it is about to initialise.
6177 let saved_block = self.cur().current_block;
6178 self.state().current_block = parent_block;
6179 match &class.super_class {
6180 Some(parent) => self.expr(parent)?,
6181 None => self.emit(Opcode::Undefined, &[]),
6182 }
6183 self.state().current_block = saved_block;
6184 let has_heritage = class.super_class.is_some();
6185
6186 // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
6187 // lands after the heritage's code — which is where the reference puts it, because it
6188 // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
6189 // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
6190 // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
6191 // came out in the opposite order from the reference's.
6192 //
6193 // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
6194 // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
6195 // a const accepts — so the old comment's worry ("a const would refuse the second
6196 // store") did not apply: there is no second store.
6197 // Every `#name` the class declares gets a `const` binding in the class scope, and so
6198 // does every computed field key. That is how the reference does it
6199 // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
6200 // what makes a private name resolve like any other class-scope variable — including
6201 // through a nested function's closure — while remaining invisible outside.
6202 //
6203 // All of them are declared *before* `<class_fields_init>`, in member order, because
6204 // that is when the reference's parser creates them.
6205 let plan = ClassPlan::build(class);
6206 // The body's private names are visible from here to the end of the class, and shadow
6207 // any outer class's of the same spelling. Pushed *before* the constructor is compiled
6208 // — it is compiled first because `define_class` consumes it, but its body can name
6209 // `#x` like any other member's.
6210 self.private_scopes.push(plan.uses.clone());
6211 let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
6212 for binding in &plan.bindings {
6213 class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
6214 }
6215 let fci = self.declare(
6216 "<class_fields_init>",
6217 VarDef::constant("<class_fields_init>"),
6218 );
6219 // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
6220 // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
6221 // members' bindings follow in reverse.
6222 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
6223 for slot in class_slots.iter().rev() {
6224 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
6225 }
6226
6227 // The constructor is compiled before `define_class` because that instruction
6228 // consumes it; a class without one gets the implicit version.
6229 let constructor = class.elements.iter().find_map(|element| match element {
6230 ClassElement::Method {
6231 kind: MethodKind::Constructor,
6232 func,
6233 ..
6234 } => Some(&**func),
6235 _ => None,
6236 });
6237 // A constructor is compiled differently from a method: it owns `this`. The flags
6238 // go on the *enclosing* state because a constructor is a nested function and
6239 // `compile_function_with_name` starts a fresh one.
6240 let ctor = match constructor {
6241 Some(func) => self.compile_class_constructor(func, has_heritage)?,
6242 None => self.compile_implicit_constructor(class, has_heritage)?,
6243 };
6244 // A closure, not the bare constant: the constructor captures
6245 // `<class_fields_init>`, which is only filled after `define_class` has run, so it
6246 // has to hold the cell rather than a copy of its value.
6247 //
6248 // The pool slot is left unassigned for now, because the reference gives the
6249 // constructor the *last* index of the members' range: `js_parse_class` emits a
6250 // `push_const` whose operand is patched at the end of the class parse, after every
6251 // method has taken a slot. Emitting the members first and the constant second is how
6252 // the numbering comes out the same; the instruction itself stays where it is.
6253 let ctor_insn = self.cur().insns.len();
6254 self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
6255 let flags = if has_heritage { 1 } else { 0 };
6256 self.emit(
6257 Opcode::DefineClass,
6258 &[
6259 Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
6260 Op::Int(flags),
6261 ],
6262 );
6263
6264 // Instance fields and static fields are two different functions: the first runs
6265 // per instance from the constructor, the second runs once, here.
6266 let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
6267 let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
6268 for (index, element) in class.elements.iter().enumerate() {
6269 match element {
6270 ClassElement::Method {
6271 key: member_key,
6272 is_static,
6273 kind,
6274 func,
6275 span,
6276 } => {
6277 if *kind == MethodKind::Constructor {
6278 continue;
6279 }
6280 // `static(x)` is a *method* named `static`, not a static method; the
6281 // parser already decided which by putting it in `kind`.
6282 if *is_static {
6283 self.emit(Opcode::Swap, &[]);
6284 }
6285 // A computed key is evaluated *here*, before the method's closure
6286 // exists, and stays under it: `define_method_computed` pops
6287 // `function, key, object`, so the stack has to read
6288 // `[class, prototype, key, function]`. Evaluating the key after the
6289 // `fclosure` and swapping the two put the prototype *below* the
6290 // closure, which defined the method on the function and lost the
6291 // prototype: `class C { [k]() {} }` left `C` undefined. The order is
6292 // also the spec's — a class body evaluates every element's name before
6293 // that element's function.
6294 if let PropName::Computed(key) = member_key {
6295 self.expr(key)?;
6296 }
6297 let function = self.compile_function_with_name(func, true)?;
6298 let index = self.push_constant(Constant::Function(Box::new(function)));
6299 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6300 match member_key {
6301 // A private method is not a property of the prototype: it is a
6302 // closure in the class scope, which is why nothing outside can reach
6303 // it and why a use site has to brand-check. `set_name` gives the
6304 // function its `name` (`#m`), which an accessor does not get — the
6305 // reference leaves that commented out.
6306 PropName::Private(ident) => {
6307 let name = format!("#{}", ident.name);
6308 // `set_home_object` first: the brand check reads the function's
6309 // home object, and for a method that is the prototype.
6310 self.emit(Opcode::SetHomeObject, &[]);
6311 let binding = if *kind == MethodKind::Set {
6312 format!("{name}<set>")
6313 } else {
6314 name.clone()
6315 };
6316 if *kind == MethodKind::Method {
6317 self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
6318 }
6319 self.emit_var(VarAction::PutInit, &binding);
6320 }
6321 PropName::Computed(_) => {
6322 self.emit(
6323 Opcode::DefineMethodComputed,
6324 &[Op::Int(class_method_flags(*kind))],
6325 );
6326 }
6327 PropName::Literal(literal) => {
6328 let text = self.property_key_text(literal, *span)?;
6329 self.emit(
6330 Opcode::DefineMethod,
6331 &[
6332 Op::Atom(Atom::from_wtf8(&text)),
6333 Op::Int(class_method_flags(*kind)),
6334 ],
6335 );
6336 }
6337 }
6338 if *is_static {
6339 self.emit(Opcode::Swap, &[]);
6340 }
6341 }
6342 ClassElement::Field {
6343 key: field_key,
6344 is_static,
6345 value,
6346 ..
6347 } => {
6348 // A private field's *symbol* is created here, at the member, and stored
6349 // in its binding: the field's property is keyed by it, so it has to exist
6350 // before any initialiser runs, and a fresh one per class body is what
6351 // makes two classes that both write `#x` independent.
6352 //
6353 // A computed key is evaluated once, here, and `to_propkey`'d once — a key
6354 // whose `toString` has a side effect must not run again per instance.
6355 let key = match field_key {
6356 PropName::Private(ident) => {
6357 let binding = format!("#{}", ident.name);
6358 if *is_static {
6359 self.emit(Opcode::Swap, &[]);
6360 }
6361 self.emit(
6362 Opcode::PrivateSymbol,
6363 &[Op::Atom(Atom::from_text(&binding))],
6364 );
6365 self.emit_var(VarAction::PutInit, &binding);
6366 if *is_static {
6367 self.emit(Opcode::Swap, &[]);
6368 }
6369 FieldKey::Private(binding)
6370 }
6371 PropName::Computed(expression) => {
6372 let binding = plan
6373 .computed
6374 .get(&index)
6375 .cloned()
6376 .expect("every computed key got a binding");
6377 if *is_static {
6378 self.emit(Opcode::Swap, &[]);
6379 }
6380 self.expr(expression)?;
6381 self.emit(Opcode::ToPropkey, &[]);
6382 self.emit_var(VarAction::PutInit, &binding);
6383 if *is_static {
6384 self.emit(Opcode::Swap, &[]);
6385 }
6386 FieldKey::Computed(binding)
6387 }
6388 PropName::Literal(literal) => FieldKey::Literal(literal),
6389 };
6390 if *is_static {
6391 static_items.push(StaticInitItem::Field(key, value.as_deref()));
6392 } else {
6393 instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
6394 }
6395 }
6396 ClassElement::StaticBlock {
6397 body, body_start, ..
6398 } => static_items.push(StaticInitItem::Block {
6399 body,
6400 body_start: *body_start,
6401 }),
6402 }
6403 }
6404
6405 // Now that every member has its slot, the constructor can have the next one and the
6406 // `fclosure` above can name it.
6407 let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
6408 match self.state().insns.get_mut(ctor_insn) {
6409 Some(Insn::Fixed { operands, .. }) => {
6410 operands[0] = Op::Const(ctor_index);
6411 }
6412 // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
6413 // loudly beats emitting a `fclosure` of slot 4294967295.
6414 _ => {
6415 return Err(SyntaxError::new(
6416 "the class constructor's fclosure went missing",
6417 class.span,
6418 ));
6419 }
6420 }
6421
6422 // The instance brand: a symbol created once on the prototype, which every instance
6423 // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
6424 // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
6425 // copy is created. The prototype is on top of the stack at this point.
6426 if plan.instance_brand {
6427 self.emit(Opcode::Dup, &[]);
6428 self.emit(Opcode::Null, &[]);
6429 self.emit(Opcode::Swap, &[]);
6430 self.emit(Opcode::AddBrand, &[]);
6431 }
6432
6433 // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
6434 // class has no instance fields. The constructor calls it only when it is defined.
6435 //
6436 // A class with private *methods* but no fields still needs one, because adding the
6437 // brand to each new instance is the initialiser's job.
6438 if instance_fields.is_empty() && !plan.instance_brand {
6439 self.emit(Opcode::Undefined, &[]);
6440 } else {
6441 let initialiser = self.compile_field_initialiser(
6442 &instance_fields,
6443 class.span,
6444 true,
6445 plan.instance_brand,
6446 )?;
6447 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6448 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6449 // `set_home_object` reads `obj func`, so the prototype stays where it is.
6450 self.emit(Opcode::SetHomeObject, &[]);
6451 }
6452 self.emit_var(VarAction::PutInit, "<class_fields_init>");
6453 // The prototype has done its job: every instance member is defined on it. What
6454 // is left under it is the constructor.
6455 self.emit(Opcode::Drop, &[]);
6456
6457 // The static brand, for `static #m() {}`: same opcode, but the home object is the
6458 // constructor itself, so the symbol lands on the class and the class carries it.
6459 if plan.static_brand {
6460 self.emit(Opcode::Dup, &[]);
6461 self.emit(Opcode::Dup, &[]);
6462 self.emit(Opcode::AddBrand, &[]);
6463 }
6464
6465 // The class binding is initialised *before* static fields run, so a static field
6466 // can refer to the class by name (`static y = S.x`).
6467 // `set_loc` leaves the constructor on the stack, which is what the static field
6468 // call and the outer store both consume.
6469 //
6470 // Only when there *is* such a binding: an anonymous class expression declares no
6471 // class-scope name, and asking for one by the empty string resolved to nothing —
6472 // which made `var x = class {}` assign `undefined` and put a bogus global store in
6473 // the instruction stream.
6474 if let Some(name) = &name {
6475 self.emit_var(VarAction::SetInit, name);
6476 }
6477 if !static_items.is_empty() {
6478 // The static half has no brand prologue of its own: the constructor got its
6479 // brand above, before this runs.
6480 let initialiser =
6481 self.compile_field_initialiser(&static_items, class.span, false, false)?;
6482 let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6483 self.emit(Opcode::Dup, &[]);
6484 self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6485 self.emit(Opcode::SetHomeObject, &[]);
6486 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6487 self.emit(Opcode::Drop, &[]);
6488 }
6489 // The body is over, and with it this class's private names.
6490 let _ = self.private_scopes.pop();
6491 self.emit_scope_leave(key);
6492 self.state().current_block = parent_block;
6493 if keep {
6494 // A class *expression* is its own value; the class-scope binding was only
6495 // ever an alias for it.
6496 return Ok(());
6497 }
6498 // A declaration stores into the binding the enclosing statement declared.
6499 self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
6500 Ok(())
6501 }
6502
6503 fn push_this(&mut self) {
6504 self.emit(Opcode::PushThis, &[]);
6505 }
6506
6507 /// `this`, which an arrow does not have of its own.
6508 ///
6509 /// The reference gives the enclosing function a local named `this`, initialised from
6510 /// `push_this` at the top of its body, and the arrow then reads it as a captured
6511 /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
6512 /// the arrow is called with none.
6513 fn this_expression(&mut self) {
6514 // In a class constructor `this` is a local: a derived constructor only gets one
6515 // when `super()` returns, and reading the raw receiver would give the *outer*
6516 // one instead.
6517 if self.cur().ctor_kind != CtorKind::None {
6518 self.emit_var(VarAction::Get, "this");
6519 return;
6520 }
6521 if !self.cur().is_arrow {
6522 self.push_this();
6523 return;
6524 }
6525 // An arrow at the **top level** of a script or module has no enclosing function,
6526 // but it still inherits `this` — the script's or module's own. Falling through to
6527 // `emit_var(Get, "this")` without a target made that a *global* lookup, so
6528 // `var f = () => typeof this` at top level reported
6529 // `ReferenceError: 'this' is not defined` instead of `"object"`
6530 // (`Set/prototype/forEach/this-arg-explicit-cannot-override-lexical-this-arrow`
6531 // is the test262 case that reaches it, through a native `forEach`).
6532 //
6533 // The script state is the bottom of the stack, so it is the fallback target. Its
6534 // own `provide_this_local` then prepends the `push_this` the arrow reads.
6535 let target = self.enclosing_function().unwrap_or(0);
6536 self.state_at(target).needs_this_local = true;
6537 self.declare_at(target, "this");
6538 self.emit_var(VarAction::Get, "this");
6539 }
6540
6541 /// `new.target`, which an arrow likewise does not own.
6542 fn new_target_expression(&mut self) {
6543 if !self.cur().is_arrow {
6544 self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
6545 return;
6546 }
6547 if let Some(target) = self.enclosing_function() {
6548 self.state_at(target).needs_new_target_local = true;
6549 self.declare_at(target, NEW_TARGET);
6550 }
6551 self.emit_var(VarAction::Get, NEW_TARGET);
6552 }
6553
6554 /// `this.active_func`: the function `super()` resolves against.
6555 ///
6556 /// In a constructor or a method that is the function being run, so the special object
6557 /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
6558 /// a closure variable — see [`FnState::needs_active_func_local`].
6559 fn active_func_expression(&mut self) {
6560 if !self.cur().is_arrow {
6561 self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
6562 return;
6563 }
6564 if let Some(target) = self.enclosing_function() {
6565 self.state_at(target).needs_active_func_local = true;
6566 self.declare_at(target, ACTIVE_FUNC);
6567 }
6568 self.emit_var(VarAction::Get, ACTIVE_FUNC);
6569 }
6570
6571 /// Give the function a local `<active_func>`, for an arrow inside it to capture.
6572 fn provide_active_func_local(&mut self) {
6573 let current = self.stack.len() - 1;
6574 if !self.stack[current].needs_active_func_local {
6575 return;
6576 }
6577 if !self.stack[current]
6578 .vars
6579 .iter()
6580 .any(|var| var.name == ACTIVE_FUNC)
6581 {
6582 self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
6583 }
6584 self.prepend_initialiser(
6585 ACTIVE_FUNC,
6586 Insn::Fixed {
6587 op: Opcode::SpecialObject,
6588 operands: vec![Op::Int(2)],
6589 },
6590 );
6591 }
6592
6593 /// Give the function a local `new.target`, for an arrow inside it to capture.
6594 fn provide_new_target_local(&mut self) {
6595 let current = self.stack.len() - 1;
6596 if !self.stack[current].needs_new_target_local {
6597 return;
6598 }
6599 if !self.stack[current]
6600 .vars
6601 .iter()
6602 .any(|var| var.name == NEW_TARGET)
6603 {
6604 self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
6605 }
6606 self.prepend_initialiser(
6607 NEW_TARGET,
6608 Insn::Fixed {
6609 op: Opcode::SpecialObject,
6610 operands: vec![Op::Int(3)],
6611 },
6612 );
6613 }
6614
6615 /// `arguments` reached from an arrow, which likewise belongs to the enclosing
6616 /// function.
6617 fn ensure_enclosing_arguments(&mut self) {
6618 // An arrow created in a parameter list needs the *parameter* scope's
6619 // `arguments`, not the body's: the two are separate bindings and the arrow was
6620 // born before the body existed.
6621 let from_params = self.cur().created_in_params;
6622 if let Some(target) = self.enclosing_function() {
6623 self.state_at(target).needs_arguments_local = true;
6624 if from_params {
6625 self.state_at(target).needs_param_arguments = true;
6626 // Declare it now, not at the enclosing function's `finish_current`: the
6627 // arrow resolves its own `arguments` before that runs, and a binding that
6628 // does not exist yet resolves as a global.
6629 declare_param_var_at(&mut self.stack[target], "arguments");
6630 }
6631 self.declare_at(target, "arguments");
6632 }
6633 }
6634
6635 /// The innermost enclosing frame that is a real function — an arrow inherits from it
6636 /// rather than starting a scope of its own.
6637 /// The innermost enclosing frame that can own a lexical binding an arrow reads —
6638 /// a real function, or a **script** top level.
6639 ///
6640 /// A script is in the list because an `eval` body is compiled as one and an arrow
6641 /// written in eval'd code still has to find the caller's `new.target`, `this.active_func`
6642 /// and `[[HomeObject]]`. Excluding it made `eval("() => new.target")` compile the read as
6643 /// a *global* lookup of `new.target`, which no frame provides — so it raised
6644 /// `ReferenceError` instead of answering the caller's value
6645 /// (`arrow-body-direct-eval-err-contains-newtarget`).
6646 fn enclosing_function(&self) -> Option<usize> {
6647 (0..self.stack.len())
6648 .rev()
6649 .find(|index| !self.stack[*index].is_arrow)
6650 }
6651
6652 fn state_at(&mut self, index: usize) -> &mut FnState {
6653 &mut self.stack[index]
6654 }
6655
6656 /// Declare a `var` binding directly in a specific frame.
6657 fn declare_at(&mut self, index: usize, name: &str) {
6658 let state = &mut self.stack[index];
6659 if state.vars.iter().any(|var| var.name == name) {
6660 return;
6661 }
6662 state.var_block.push(FUNCTION_SCOPE);
6663 state.vars.push(VarDef::var(name));
6664 }
6665
6666 /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
6667 /// the reference calls a `special_object` gets initialised on entry.
6668 fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
6669 let current = self.stack.len() - 1;
6670 let init = [
6671 producer,
6672 Insn::Var {
6673 action: VarAction::Put,
6674 name: name.to_string(),
6675 block: 0,
6676 // A prologue initialiser runs before the body proper, but it is body
6677 // code: `this` and `arguments` are provided for it, not by it.
6678 in_params: false,
6679 },
6680 ];
6681 let inserted = init.len();
6682 for (index, instruction) in init.into_iter().enumerate() {
6683 self.stack[current].insns.insert(index, instruction);
6684 }
6685 for placed in self.stack[current].labels.iter_mut().flatten() {
6686 *placed += inserted;
6687 }
6688 self.stack[current].label_since_insn = true;
6689 }
6690
6691 fn push_constant(&mut self, constant: Constant) -> u32 {
6692 let state = self.state();
6693 let index = state.cpool.len() as u32;
6694 state.cpool.push(constant);
6695 index
6696 }
6697
6698 /// Compile `a && b`, `a || b`, `a ?? b`.
6699 ///
6700 /// A run of the *same* operator shares one end label, so `a || b || c` tests
6701 /// `a` once and jumps past everything when it is truthy, instead of falling
6702 /// into `b`'s test. The parser builds such a run left-associated —
6703 /// `((a || b) || c)` — so the operands are collected off the left spine.
6704 ///
6705 /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
6706 /// `||`'s label, because the inner chain really does end before `&&` begins.
6707 fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
6708 let mut operands = Vec::new();
6709 collect_same_operator(op, left, &mut operands);
6710 operands.push(right);
6711
6712 let end = self.new_label();
6713 // Every operand but the last decides whether the chain stops here.
6714 let last = operands.pop().expect("the right operand is always present");
6715 for operand in operands {
6716 self.expr(operand)?;
6717 self.emit(Opcode::Dup, &[]);
6718 match op {
6719 LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
6720 LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
6721 // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
6722 // `0 || b` is `b`. The dedicated test keeps the value unless it is
6723 // null-ish, so the jump is taken on `false`.
6724 LogicalOp::Coalesce => {
6725 self.emit(Opcode::IsUndefinedOrNull, &[]);
6726 self.emit_jump(Opcode::IfFalse, end, &[]);
6727 }
6728 }
6729 self.emit(Opcode::Drop, &[]);
6730 }
6731 self.expr(last)?;
6732 self.place_label(end);
6733 Ok(())
6734 }
6735
6736 fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
6737 match op {
6738 UnaryOp::Typeof => {
6739 // `typeof x` must not throw on an undeclared name.
6740 if let ExprKind::Ident(name) = &argument.kind {
6741 self.emit_var(VarAction::GetUndef, &name.name);
6742 } else {
6743 self.expr(argument)?;
6744 }
6745 self.emit(Opcode::Typeof, &[]);
6746 }
6747 UnaryOp::Delete => {
6748 // `delete obj.prop` really deletes, and answers whether it could.
6749 // Deleting a *binding* is always `false`: a local, an argument and a
6750 // declared global are all non-configurable, which the reference encodes
6751 // as a constant `push_false` rather than a runtime check. Only a
6752 // property access has anything to do at run time.
6753 // `delete super.x` is not a delete at all: the spec refuses it, and the
6754 // reference encodes the refusal as a `throw_error`. The receiver and the
6755 // key are still evaluated first, which is what keeps the evaluation order
6756 // of the operand intact.
6757 // `delete z?.b.c` answers `true` when the chain short-circuits: there is
6758 // nothing to delete, and a failed delete is not the same as a skipped
6759 // one. The reference emits the guards so they land on a `drop; push_true`
6760 // tail, which is what this reproduces.
6761 if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
6762 && let ExprKind::Member {
6763 object, property, ..
6764 } = &inner.unparen().kind
6765 {
6766 let end = self.new_label();
6767 let done = self.new_label();
6768 self.chain_link(object, end)?;
6769 match property {
6770 MemberProp::Ident(name) => self.emit(
6771 Opcode::PushAtomValue,
6772 &[Op::Atom(Atom::from_text(&name.name))],
6773 ),
6774 MemberProp::Computed(index) => self.expr(index)?,
6775 MemberProp::Private(_) => {
6776 return Err(SyntaxError::new(
6777 "deleting a private field is not allowed",
6778 argument.span,
6779 ));
6780 }
6781 }
6782 self.emit(Opcode::Delete, &[]);
6783 self.emit_jump(Opcode::Goto, done, &[]);
6784 self.place_label(end);
6785 self.emit(Opcode::Drop, &[]);
6786 self.emit(Opcode::PushTrue, &[]);
6787 self.place_label(done);
6788 return Ok(());
6789 }
6790 if let ExprKind::Member { object, .. } = &argument.unparen().kind
6791 && matches!(object.unparen().kind, ExprKind::SuperProp)
6792 {
6793 self.super_base();
6794 self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
6795 return Ok(());
6796 }
6797 // Parentheses are transparent to `delete`: `(x)` is still a Reference to
6798 // the binding `x`, so `delete (x)` answers `false` exactly as `delete x`
6799 // does, and `delete (a().b)` still evaluates `a()`. Matching on the
6800 // unparenthesised operand is what keeps both — matching on `argument.kind`
6801 // sent every parenthesised form to the "not a Reference" arm, which cost
6802 // `delete(__variable) === false` in test262's `S12.2_A2`.
6803 match &argument.unparen().kind {
6804 ExprKind::Member {
6805 object, property, ..
6806 } => {
6807 self.expr(object)?;
6808 match property {
6809 MemberProp::Ident(name) => {
6810 self.emit(
6811 Opcode::PushAtomValue,
6812 &[Op::Atom(Atom::from_text(&name.name))],
6813 );
6814 }
6815 MemberProp::Computed(index) => self.expr(index)?,
6816 MemberProp::Private(_) => {
6817 return Err(SyntaxError::new(
6818 "deleting a private field is not allowed",
6819 argument.span,
6820 ));
6821 }
6822 }
6823 self.emit(Opcode::Delete, &[]);
6824 }
6825 ExprKind::Ident(name) => {
6826 // `delete name`: a declared global, a local and an argument all
6827 // answer `false`, but an *implicit* global (`x = 1` with no
6828 // declaration) is a configurable property of the global object
6829 // and really goes away. Which of those a name is only the
6830 // resolver knows, so the decision waits for it.
6831 let pos = self.cur().cur_pos;
6832 self.state().insns.push(Insn::DeleteVar {
6833 name: name.name.clone(),
6834 });
6835 self.state().insn_pos.push(pos);
6836 }
6837 // §13.5.1.2 step 2: an operand that is **not** a Reference Record
6838 // answers `true` — there is nothing to delete, and "nothing needed
6839 // deleting" is success. `delete !0`, `delete (1 + 2)` and
6840 // `delete typeof 0` are all `true`, and the operand is still evaluated
6841 // (which is why it is `Drop`ed rather than skipped:
6842 // `delete f()` must call `f`).
6843 //
6844 // Answering `false` here is the C reference's old behaviour and was
6845 // wrong in an observable way: test262's
6846 // `dynamic-import/assignment-expression/logical-and-expr` builds a
6847 // specifier out of `delete void typeof +-~! 0 && b`, and a `false` left
6848 // half turned the whole `&&` into `false`, so the import asked for a
6849 // module named "false".
6850 _ => {
6851 self.expr(argument)?;
6852 self.emit(Opcode::Drop, &[]);
6853 self.emit(Opcode::PushTrue, &[]);
6854 }
6855 }
6856 }
6857 UnaryOp::Void => {
6858 self.expr(argument)?;
6859 self.emit(Opcode::Drop, &[]);
6860 self.emit(Opcode::Undefined, &[]);
6861 }
6862 UnaryOp::Minus => {
6863 self.expr(argument)?;
6864 self.emit(Opcode::Neg, &[]);
6865 }
6866 UnaryOp::Plus => {
6867 self.expr(argument)?;
6868 self.emit(Opcode::Plus, &[]);
6869 }
6870 UnaryOp::Not => {
6871 self.expr(argument)?;
6872 self.emit(Opcode::Lnot, &[]);
6873 }
6874 UnaryOp::BitNot => {
6875 self.expr(argument)?;
6876 self.emit(Opcode::Not, &[]);
6877 }
6878 }
6879 Ok(())
6880 }
6881
6882 /// Compile an assignment.
6883 ///
6884 /// Three operator families, three shapes:
6885 ///
6886 /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
6887 /// the value is kept, because `put_field`/`put_array_el` consume both the
6888 /// object and the value: `insert2` is `obj a -> a obj a`, so the store sees
6889 /// the pair it wants and leaves a copy on top.
6890 /// * **compound** `+=` … — read the place, apply the operator, store. A member
6891 /// reads through `get_field2`/`get_array_el3`, which leave the object (and
6892 /// index) underneath the value precisely so the store can follow.
6893 /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
6894 /// right-hand side. The test *keeps* the current value and skips the store
6895 /// entirely, which is the whole point: `a ||= b` must not evaluate `b` when
6896 /// `a` is already truthy.
6897 fn assign(
6898 &mut self,
6899 op: AssignOp,
6900 target: &Pattern,
6901 value: &Expr,
6902 discard: bool,
6903 ) -> Result<(), SyntaxError> {
6904 // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
6905 // about, so it is set only when this assignment *is* that expression.
6906 let keep = !discard;
6907 match &target.kind {
6908 PatternKind::Ident(name) => {
6909 // A *simple* store is blamed on the identifier, not on the `=`: a
6910 // strict-mode `not_def = 1` raises when the name is written, which the
6911 // reference reports at the name's column. A compound store is blamed on
6912 // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
6913 // which the reference reports at the `+=`), so only the simple case
6914 // moves the position.
6915 let saved = self.cur().cur_pos;
6916 let name_pos = Some(name.span.start);
6917 if matches!(op, AssignOp::Assign) {
6918 self.state().cur_pos = name_pos;
6919 }
6920 // A *compound* store reads the binding before it combines, and that read
6921 // is blamed on the identifier: `not_def += 2` fails while reading
6922 // `not_def`, so the position is the name's, not the `+=`'s. The
6923 // combination that follows is blamed on the operator, which is why
6924 // `cur_pos` is put back to the operator position before it is emitted.
6925 self.state().cur_pos = name_pos;
6926 match op {
6927 AssignOp::Assign => {
6928 self.expr(value)?;
6929 self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
6930 // A discarded store to a *slot* consumes its value, so no copy
6931 // is needed. A global store goes through `put_var`, which the
6932 // reference always pairs with a `dup` — matching it keeps the
6933 // bytecode identical. Getting this wrong is not only an extra
6934 // instruction: a stray copy gives the peephole a chance to fold
6935 // the store into an unrelated later read.
6936 let slot = self.is_slot(&name.name);
6937 if keep || !slot {
6938 self.emit(Opcode::Dup, &[]);
6939 }
6940 self.state().no_value = !keep && slot;
6941 self.emit_var(VarAction::Put, &name.name);
6942 }
6943 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6944 let end = self.new_label();
6945 self.emit_var(VarAction::Get, &name.name);
6946 self.state().cur_pos = saved;
6947 self.emit(Opcode::Dup, &[]);
6948 self.emit_logical_test(op);
6949 self.emit_jump(logical_jump(op), end, &[]);
6950 self.emit(Opcode::Drop, &[]);
6951 self.expr(value)?;
6952 self.emit(Opcode::Dup, &[]);
6953 self.emit_var(VarAction::Put, &name.name);
6954 self.place_label(end);
6955 }
6956 _ => {
6957 self.emit_var(VarAction::Get, &name.name);
6958 self.expr(value)?;
6959 self.state().cur_pos = saved;
6960 self.emit(compound_opcode(op), &[]);
6961 self.emit(Opcode::Dup, &[]);
6962 self.emit_var(VarAction::Put, &name.name);
6963 }
6964 }
6965 self.state().cur_pos = saved;
6966 Ok(())
6967 }
6968 PatternKind::Member(member) => {
6969 // `super.x = v` is not a store through a value: it starts at the home
6970 // object's prototype but writes to `this`, so it goes through
6971 // `put_super_value` rather than `put_field`. The receiver, prototype, key
6972 // and value are handed over together.
6973 if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
6974 return self.assign_super(member, op, value);
6975 }
6976 // A store is blamed on the selector punctuator (`.` or `[`), the same
6977 // token a load is blamed on — the reference records `put_field obj.a`
6978 // at the `.`, so a setter that throws reports that column and not the
6979 // `=` of the assignment it sits in. The inner expressions restore their
6980 // own positions, so the selector's sticks for the store instructions.
6981 let saved = self.cur().cur_pos;
6982 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6983 self.expr(&member.object)?;
6984 match &member.property {
6985 MemberProp::Ident(property) => {
6986 let atom = Atom::from_text(&property.name);
6987 match op {
6988 AssignOp::Assign => {
6989 self.expr(value)?;
6990 // `put_field` consumes the object and the value, so
6991 // without `insert2` nothing is left over for the
6992 // statement to drop.
6993 self.state().no_value = !keep;
6994 if keep {
6995 self.emit(Opcode::Insert2, &[]);
6996 }
6997 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6998 }
6999 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7000 // `get_field2` leaves the object under the value, so
7001 // the keep path has an object to dispose of. The store
7002 // path must jump *over* that cleanup: falling into it
7003 // would `nip` a stack that only holds the value.
7004 let (keep_label, end) = (self.new_label(), self.new_label());
7005 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7006 self.emit(Opcode::Dup, &[]);
7007 self.emit_logical_test(op);
7008 self.emit_jump(logical_jump(op), keep_label, &[]);
7009 self.emit(Opcode::Drop, &[]);
7010 self.expr(value)?;
7011 self.emit(Opcode::Insert2, &[]);
7012 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7013 self.emit_jump(Opcode::Goto, end, &[]);
7014 self.place_label(keep_label);
7015 self.emit(Opcode::Nip, &[]);
7016 self.place_label(end);
7017 }
7018 _ => {
7019 self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7020 self.expr(value)?;
7021 self.emit(compound_opcode(op), &[]);
7022 self.state().no_value = !keep;
7023 if keep {
7024 self.emit(Opcode::Insert2, &[]);
7025 }
7026 self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7027 }
7028 }
7029 }
7030 MemberProp::Computed(index) => {
7031 self.expr(index)?;
7032 match op {
7033 AssignOp::Assign => {
7034 self.expr(value)?;
7035 self.state().no_value = !keep;
7036 if keep {
7037 self.emit(Opcode::Insert3, &[]);
7038 }
7039 self.emit(Opcode::PutArrayEl, &[]);
7040 }
7041 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7042 let (keep_label, end) = (self.new_label(), self.new_label());
7043 self.emit(Opcode::GetArrayEl3, &[]);
7044 self.emit(Opcode::Dup, &[]);
7045 self.emit_logical_test(op);
7046 self.emit_jump(logical_jump(op), keep_label, &[]);
7047 self.emit(Opcode::Drop, &[]);
7048 self.expr(value)?;
7049 self.emit(Opcode::Insert3, &[]);
7050 self.emit(Opcode::PutArrayEl, &[]);
7051 self.emit_jump(Opcode::Goto, end, &[]);
7052 self.place_label(keep_label);
7053 // Both the object and the index are left over.
7054 self.emit(Opcode::Nip, &[]);
7055 self.emit(Opcode::Nip, &[]);
7056 self.place_label(end);
7057 }
7058 _ => {
7059 self.emit(Opcode::GetArrayEl3, &[]);
7060 self.expr(value)?;
7061 self.emit(compound_opcode(op), &[]);
7062 self.state().no_value = !keep;
7063 if keep {
7064 self.emit(Opcode::Insert3, &[]);
7065 }
7066 self.emit(Opcode::PutArrayEl, &[]);
7067 }
7068 }
7069 }
7070 MemberProp::Private(name) => {
7071 // `obj value` is on the stack, and every private store wants exactly
7072 // that. A top-level private name cannot be assigned (the parser rejects
7073 // `#x = 1`), so the only way here is `this.#x = …` inside the class.
7074 //
7075 // The reference emits `insert2` whether or not the value is wanted,
7076 // so this does too: the copy left behind is the assignment expression's
7077 // value, and a discarded one is simply never read.
7078 let binding = format!("#{}", name.name);
7079 let (kind, setter) = self.private_use(&binding, member.span)?;
7080 match op {
7081 AssignOp::Assign => {
7082 self.expr(value)?;
7083 if keep {
7084 self.emit(Opcode::Insert2, &[]);
7085 }
7086 self.private_store(&binding, kind, setter.as_deref())?;
7087 self.state().no_value = !keep;
7088 }
7089 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7090 let (keep_label, end) = (self.new_label(), self.new_label());
7091 self.emit(Opcode::Dup, &[]);
7092 self.private_load(&binding, kind, member.span)?;
7093 self.emit(Opcode::Dup, &[]);
7094 self.emit_logical_test(op);
7095 self.emit_jump(logical_jump(op), keep_label, &[]);
7096 self.emit(Opcode::Drop, &[]);
7097 self.expr(value)?;
7098 self.emit(Opcode::Insert2, &[]);
7099 self.private_store(&binding, kind, setter.as_deref())?;
7100 self.emit_jump(Opcode::Goto, end, &[]);
7101 self.place_label(keep_label);
7102 self.emit(Opcode::Nip, &[]);
7103 self.place_label(end);
7104 }
7105 _ => {
7106 self.emit(Opcode::Dup, &[]);
7107 self.private_load(&binding, kind, member.span)?;
7108 self.expr(value)?;
7109 self.emit(compound_opcode(op), &[]);
7110 self.emit(Opcode::Insert2, &[]);
7111 self.private_store(&binding, kind, setter.as_deref())?;
7112 }
7113 }
7114 }
7115 }
7116 self.state().cur_pos = saved;
7117 Ok(())
7118 }
7119 // A destructuring assignment: the right-hand side is the expression's own
7120 // value, so it is evaluated once and kept under the pattern's stores.
7121 PatternKind::Array { .. } | PatternKind::Object { .. } => {
7122 self.expr(value)?;
7123 if keep {
7124 self.emit(Opcode::Dup, &[]);
7125 }
7126 self.destructure(target, None)?;
7127 self.state().no_value = !keep;
7128 Ok(())
7129 }
7130 _ => Err(SyntaxError::new(
7131 "this assignment target is not supported by the compiler yet",
7132 target.span,
7133 )),
7134 }
7135 }
7136
7137 /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
7138 ///
7139 /// The stack has to carry four values — receiver, prototype, key, value — because
7140 /// `put_super_value` takes them together; the receiver is what makes a setter found on
7141 /// the prototype run with `this`, and the key has to survive until the store, which is
7142 /// why a compound form converts it to a property key once and `dup3`s rather than
7143 /// evaluating it twice.
7144 fn assign_super(
7145 &mut self,
7146 member: &MemberPattern,
7147 op: AssignOp,
7148 value: &Expr,
7149 ) -> Result<(), SyntaxError> {
7150 let saved = self.cur().cur_pos;
7151 self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7152 self.super_base();
7153 match &member.property {
7154 MemberProp::Ident(property) => self.emit(
7155 Opcode::PushAtomValue,
7156 &[Op::Atom(Atom::from_text(&property.name))],
7157 ),
7158 MemberProp::Computed(index) => self.expr(index)?,
7159 MemberProp::Private(_) => {
7160 return Err(SyntaxError::new(
7161 "private fields are not supported by the compiler yet",
7162 member.span,
7163 ));
7164 }
7165 }
7166 match op {
7167 AssignOp::Assign => {
7168 // The key is only converted once, by `put_super_value` itself, so a
7169 // computed key's `toString` runs exactly once.
7170 self.expr(value)?;
7171 self.emit(Opcode::Insert4, &[]);
7172 self.emit(Opcode::PutSuperValue, &[]);
7173 }
7174 AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7175 let (keep_label, end) = (self.new_label(), self.new_label());
7176 self.emit(Opcode::ToPropkey, &[]);
7177 self.emit(Opcode::Dup3, &[]);
7178 self.emit(Opcode::GetSuperValue, &[]);
7179 self.emit(Opcode::Dup, &[]);
7180 self.emit_logical_test(op);
7181 self.emit_jump(logical_jump(op), keep_label, &[]);
7182 self.emit(Opcode::Drop, &[]);
7183 self.expr(value)?;
7184 self.emit(Opcode::Insert4, &[]);
7185 self.emit(Opcode::PutSuperValue, &[]);
7186 self.emit_jump(Opcode::Goto, end, &[]);
7187 self.place_label(keep_label);
7188 // The prototype and the key are still under the value that was read.
7189 self.emit(Opcode::Nip, &[]);
7190 self.emit(Opcode::Nip, &[]);
7191 self.emit(Opcode::Nip, &[]);
7192 self.place_label(end);
7193 }
7194 _ => {
7195 self.emit(Opcode::ToPropkey, &[]);
7196 self.emit(Opcode::Dup3, &[]);
7197 self.emit(Opcode::GetSuperValue, &[]);
7198 self.expr(value)?;
7199 self.emit(compound_opcode(op), &[]);
7200 self.emit(Opcode::Insert4, &[]);
7201 self.emit(Opcode::PutSuperValue, &[]);
7202 }
7203 }
7204 // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
7205 // is still on the stack when the store finishes, and the expression statement is
7206 // what disposes of it — the same arrangement as `put_field`, reached from the other
7207 // side: there the store consumes the value (`no_value`), here it leaves it
7208 // (`keep` already false, so nothing tells the statement otherwise).
7209 self.state().cur_pos = saved;
7210 Ok(())
7211 }
7212
7213 /// The test a logical assignment applies to the current value.
7214 ///
7215 /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
7216 /// assign, while `0 ||= b` must not.
7217 fn emit_logical_test(&mut self, op: AssignOp) {
7218 if op == AssignOp::Coalesce {
7219 self.emit(Opcode::IsUndefinedOrNull, &[]);
7220 }
7221 }
7222
7223 /// The private name `#name` this use site resolves against.
7224 ///
7225 /// The parser has already rejected a name no enclosing class declares, so a miss here
7226 /// means the compiler lost track of a class scope — which is worth a real error rather
7227 /// than an `unwrap`.
7228 fn private_use(
7229 &self,
7230 binding: &str,
7231 span: Span,
7232 ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
7233 ClassPlan::find(self, binding)
7234 .map(|use_| (use_.kind, use_.setter.clone()))
7235 .ok_or_else(|| {
7236 SyntaxError::new(
7237 format!("the private name '{binding}' is out of scope here"),
7238 span,
7239 )
7240 })
7241 }
7242
7243 /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
7244 ///
7245 /// The three readable kinds take three different instructions, because a private name
7246 /// holds three different things — a symbol, a method function, a getter function — and
7247 /// only the first one is a property read at all.
7248 fn private_load(
7249 &mut self,
7250 binding: &str,
7251 kind: PrivateKind,
7252 span: Span,
7253 ) -> Result<(), SyntaxError> {
7254 match kind {
7255 PrivateKind::Field => {
7256 self.emit_var(VarAction::Get, binding);
7257 self.emit(Opcode::GetPrivateField, &[]);
7258 }
7259 PrivateKind::Method => {
7260 self.emit_var(VarAction::Get, binding);
7261 self.emit(Opcode::CheckBrand, &[]);
7262 // `check_brand` reads `obj func` and leaves both; the method itself is what
7263 // `this.#m` evaluates to.
7264 self.emit(Opcode::Nip, &[]);
7265 }
7266 PrivateKind::Getter => {
7267 self.emit_var(VarAction::Get, binding);
7268 self.emit(Opcode::CheckBrand, &[]);
7269 self.emit(Opcode::CallMethod, &[Op::Int(0)]);
7270 }
7271 // `#a` is declared but never filled when only a setter exists, so reading it is
7272 // the same refusal as assigning to a `const`. The reference reports it with the
7273 // generic read-only wording and leaves the better message as a `XXX`.
7274 PrivateKind::Setter => self.emit(
7275 Opcode::ThrowError,
7276 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7277 ),
7278 }
7279 let _ = span;
7280 Ok(())
7281 }
7282
7283 /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
7284 fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
7285 match kind {
7286 // A method *is* the callee, so only the check goes in between.
7287 PrivateKind::Method => {
7288 self.emit_var(VarAction::Get, binding);
7289 self.emit(Opcode::CheckBrand, &[]);
7290 }
7291 _ => self.private_load(binding, kind, Span::default())?,
7292 }
7293 Ok(())
7294 }
7295
7296 /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
7297 /// wanted back.
7298 ///
7299 /// A getter/setter pair is a *method call*, not a property store: the reference reads
7300 /// the setter out of its own binding and calls it with the receiver, which is why the
7301 /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
7302 /// keeps the assignment's value for an expression context.
7303 fn private_store(
7304 &mut self,
7305 binding: &str,
7306 kind: PrivateKind,
7307 setter: Option<&str>,
7308 ) -> Result<(), SyntaxError> {
7309 match kind {
7310 PrivateKind::Field => {
7311 self.emit_var(VarAction::Get, binding);
7312 self.emit(Opcode::PutPrivateField, &[]);
7313 }
7314 PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
7315 Some(setter) => {
7316 self.emit_var(VarAction::Get, setter);
7317 // `obj func value` -> `value obj func` for the check, and back again for
7318 // the call, which wants `obj func arg`.
7319 self.emit(Opcode::Swap, &[]);
7320 self.emit(Opcode::Rot3r, &[]);
7321 self.emit(Opcode::CheckBrand, &[]);
7322 self.emit(Opcode::Rot3l, &[]);
7323 self.emit(Opcode::CallMethod, &[Op::Int(1)]);
7324 // The setter's return value is discarded; the assignment's own value is
7325 // whatever the caller left underneath.
7326 self.emit(Opcode::Drop, &[]);
7327 }
7328 None => self.emit(
7329 Opcode::ThrowError,
7330 &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7331 ),
7332 },
7333 }
7334 Ok(())
7335 }
7336
7337 fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
7338 let instruction = match (op, prefix) {
7339 (UpdateOp::Increment, true) => Opcode::Inc,
7340 (UpdateOp::Increment, false) => Opcode::PostInc,
7341 (UpdateOp::Decrement, true) => Opcode::Dec,
7342 (UpdateOp::Decrement, false) => Opcode::PostDec,
7343 };
7344 if let ExprKind::Member {
7345 object,
7346 property,
7347 optional: _,
7348 } = &argument.kind
7349 {
7350 // `o.x++` needs the receiver twice, so the last link is read with the
7351 // `get_*2`/`get_*3` form that keeps it, and the update is written back
7352 // with `put_field`/`put_array_el`. The reordering in between is what puts
7353 // the old value below the receiver for a postfix update and the new one
7354 // above it for a prefix one:
7355 //
7356 // `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
7357 // `obj val` → `inc` → `obj new new` → `insert2` → `new obj new`
7358 //
7359 // This mirrors the reference instruction for instruction.
7360 self.expr(object)?;
7361 match property {
7362 MemberProp::Ident(name) => {
7363 self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
7364 self.emit(instruction, &[]);
7365 self.emit(
7366 if prefix {
7367 Opcode::Insert2
7368 } else {
7369 Opcode::Perm3
7370 },
7371 &[],
7372 );
7373 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
7374 }
7375 MemberProp::Computed(index) => {
7376 self.expr(index)?;
7377 self.emit(Opcode::GetArrayEl3, &[]);
7378 self.emit(instruction, &[]);
7379 self.emit(
7380 if prefix {
7381 Opcode::Insert3
7382 } else {
7383 Opcode::Perm4
7384 },
7385 &[],
7386 );
7387 self.emit(Opcode::PutArrayEl, &[]);
7388 }
7389 MemberProp::Private(name) => {
7390 // The receiver is duplicated and the read keeps it, exactly as `get_field2`
7391 // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
7392 // `perm3` -> `old obj new` -> store.
7393 let binding = format!("#{}", name.name);
7394 let (kind, setter) = self.private_use(&binding, argument.span)?;
7395 self.emit(Opcode::Dup, &[]);
7396 self.private_load(&binding, kind, argument.span)?;
7397 self.emit(instruction, &[]);
7398 self.emit(
7399 if prefix {
7400 Opcode::Insert2
7401 } else {
7402 Opcode::Perm3
7403 },
7404 &[],
7405 );
7406 self.private_store(&binding, kind, setter.as_deref())?;
7407 }
7408 }
7409 return Ok(());
7410 }
7411 let ExprKind::Ident(name) = &argument.kind else {
7412 return Err(SyntaxError::new(
7413 "increment of a non-variable is not supported by the compiler yet",
7414 argument.span,
7415 ));
7416 };
7417 // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
7418 // reference's `inc_loc` folds those three into one, but it does so only in some
7419 // positions (a `for` update and not a bare statement, and never for a lexical
7420 // binding), so emitting it unconditionally would move *away* from its output.
7421 // The instruction is equivalent either way; matching the reference matters more
7422 // than saving two instructions.
7423 let _ = !std::mem::take(&mut self.state().discard_value);
7424 self.emit_var(VarAction::Get, &name.name);
7425 self.emit(instruction, &[]);
7426 if prefix {
7427 self.emit(Opcode::Dup, &[]);
7428 }
7429 self.emit_var(VarAction::Put, &name.name);
7430 Ok(())
7431 }
7432
7433 /// Compile an array literal.
7434 ///
7435 /// The reference splits this into three phases, and the split is load-bearing
7436 /// rather than an optimisation detail:
7437 ///
7438 /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
7439 /// the array in one instruction.
7440 /// 2. **Everything up to the first spread** is appended with explicit indices
7441 /// (`define_field <index>`), because a hole has no element to pass to
7442 /// `array_from`. A hole here is what makes `length` need fixing up: an
7443 /// explicit index does not extend the array the way a pushed element does.
7444 /// 3. **From the first spread on** the index lives on the stack, so `append` and
7445 /// `define_array_el` can consume it and `inc` advances it.
7446 ///
7447 /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
7448 /// forces phase 2, and `[...a]` forces phase 3.
7449 fn array_literal(
7450 &mut self,
7451 elements: &[Option<ArrayElement>],
7452 span: Span,
7453 ) -> Result<(), SyntaxError> {
7454 let _ = span;
7455 let mut index: u32 = 0;
7456 let mut cursor = 0usize;
7457
7458 // Phase 1: a leading run of plain elements, at most 32 of them.
7459 while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
7460 if index >= 32 {
7461 break;
7462 }
7463 self.expr(element)?;
7464 index += 1;
7465 cursor += 1;
7466 }
7467 self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
7468
7469 // Phase 2: explicit indices, up to the first spread.
7470 let mut need_length = false;
7471 while let Some(element) = elements.get(cursor) {
7472 if matches!(element, Some(ArrayElement::Spread(_))) {
7473 break;
7474 }
7475 need_length = true;
7476 if let Some(ArrayElement::Expr(expression)) = element {
7477 self.expr(expression)?;
7478 self.emit_define_index(index);
7479 need_length = false;
7480 }
7481 index += 1;
7482 cursor += 1;
7483 }
7484
7485 if cursor >= elements.len() {
7486 if need_length {
7487 // `define_field` cannot set `length`, which is not configurable.
7488 self.emit(Opcode::Dup, &[]);
7489 self.push_number(index as f64);
7490 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7491 }
7492 return Ok(());
7493 }
7494
7495 // Phase 3: the index moves onto the stack for the spreading tail.
7496 //
7497 // `need_length` deliberately carries over from phase 2: a hole before the
7498 // first spread still has to be reflected in `length`, and only the final
7499 // check can do it because the array is not finished until the tail is
7500 // appended.
7501 self.push_number(index as f64);
7502 while let Some(element) = elements.get(cursor) {
7503 match element {
7504 Some(ArrayElement::Spread(expression)) => {
7505 // `append` copies an iterable and leaves the next index behind,
7506 // so no `inc` is needed here.
7507 self.expr(spread_argument(expression))?;
7508 self.emit(Opcode::Append, &[]);
7509 }
7510 None | Some(ArrayElement::Expr(_)) => {
7511 need_length = true;
7512 if let Some(ArrayElement::Expr(expression)) = element {
7513 self.expr(expression)?;
7514 self.emit(Opcode::DefineArrayEl, &[]);
7515 need_length = false;
7516 }
7517 self.emit(Opcode::Inc, &[]);
7518 }
7519 }
7520 cursor += 1;
7521 }
7522 if need_length {
7523 self.emit(Opcode::Dup1, &[]);
7524 self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7525 } else {
7526 self.emit(Opcode::Drop, &[]);
7527 }
7528 Ok(())
7529 }
7530
7531 /// `define_field` with an array-index atom, which is how phase 2 stores elements.
7532 fn emit_define_index(&mut self, index: u32) {
7533 self.emit(
7534 Opcode::DefineField,
7535 &[Op::Atom(Atom::from_text(&index.to_string()))],
7536 );
7537 }
7538
7539 // -- functions ---------------------------------------------------------
7540
7541 fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
7542 self.compile_function_with_name(func, false)
7543 }
7544
7545 /// Compile a function, recording whether it is a *named function expression*.
7546 ///
7547 /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
7548 /// must not leak outside. The reference does that by declaring `g` as a local of
7549 /// the function itself and initialising it with `special_object 2` (the current
7550 /// function), which is why this has to be known at compile time.
7551 fn compile_function_with_name(
7552 &mut self,
7553 func: &ast::Function,
7554 is_expression: bool,
7555 ) -> Result<CompiledFunction, SyntaxError> {
7556 let kind = match (func.is_generator, func.is_async) {
7557 (false, false) => FunctionKind::Normal,
7558 (true, false) => FunctionKind::Generator,
7559 (false, true) => FunctionKind::Async,
7560 (true, true) => FunctionKind::AsyncGenerator,
7561 };
7562 let mut state = FnState::new(
7563 func.name
7564 .as_ref()
7565 .map(|n| n.name.clone())
7566 .unwrap_or_default(),
7567 kind,
7568 );
7569 // The function's own mode, recorded by the parser. Inheriting the enclosing
7570 // function's instead let a nested `"use strict"` directive be ignored, so the
7571 // body ran with sloppy `this`, sloppy `arguments` and no const checks.
7572 state.strict = func.strict;
7573 // A function defined inside a `with` block keeps seeing that object: the guard
7574 // chain names the enclosing `<with>` locals, which resolve outward into closure
7575 // variables exactly like any other captured binding.
7576 state.with_names = self.cur().with_names.clone();
7577 state.is_arrow = func.is_arrow;
7578 state.created_in_block = self.cur().current_block;
7579 // A default anywhere in the parameter list is what gives the function two
7580 // variable environments. The reference decides this the same way: it scans the
7581 // parenthesis for a top-level `=`, so a destructured name without a default
7582 // stays a plain function-scope binding.
7583 state.in_params = false;
7584 // The reference scans the parenthesis for *any* `=`, including one nested inside
7585 // a pattern, so `function f({a = 1})` has parameter expressions even though the
7586 // parameter itself carries no initialiser.
7587 state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
7588 // `IsSimpleParameterList`: no default, no rest, no destructuring. Unlike the
7589 // flag above this looks at the *shape* of each parameter, not just for `=`.
7590 state.simple_parameter_list = func
7591 .params
7592 .iter()
7593 .all(|pattern| matches!(pattern.kind, PatternKind::Ident(_)));
7594 // A function born inside a parameter list inherits the prohibition: it must not
7595 // see the body bindings of the function it was created in.
7596 state.created_in_params = self.cur().in_params || self.cur().created_in_params;
7597 // A class constructor knows what it is only because the class told it.
7598 if let Some(kind) = self.cur().class_ctor_pending {
7599 state.ctor_kind = kind;
7600 }
7601 // A named *expression* binds its own name; a declaration's name is already
7602 // bound in the enclosing scope.
7603 state.self_name = if is_expression && !func.is_arrow {
7604 func.name.as_ref().map(|n| n.name.clone())
7605 } else {
7606 None
7607 };
7608 // Keep the written range so `Function.prototype.toString` can answer with the
7609 // original text rather than `[native code]`.
7610 //
7611 // It starts at the *parameter list*, not at the function: §20.2.3.5 removes the
7612 // accessor and generator prefixes, and for a method it must not include the name
7613 // or a leading `static`. `params_span` is exactly that boundary.
7614 // A *method* keeps the old `[native code]` answer: its reported text is defined
7615 // by the method-definition grammar (no name, no `static`, no `get`/`set`, but
7616 // the comments in between kept verbatim), and reconstructing that from a byte
7617 // span got it wrong in more cases than it got right. A plain function and an
7618 // arrow are the shapes libraries actually introspect, and those are exact.
7619 // A method's reported text starts at its **key** — `m(){}`, `[expr](){}`,
7620 // `#f /* a */ ( /* b */ ) {}` — which is exactly where the parser put `span.start`,
7621 // so the same slice works for every form. (`Params_span` is the boundary that
7622 // excludes `static`/`async`/`get`, which the spec's method grammar also omits.)
7623 // `source_span` is set only where the reported text is not the function's own
7624 // range — a class's constructor reports the whole class definition.
7625 let reported = func.source_span.unwrap_or(func.span);
7626 state.span = Some((reported.start.offset as usize, reported.end.offset as usize));
7627 state.line = func.span.start.line;
7628 state.column = func.span.start.column;
7629 // A function body has no hidden `<ret>` local; the value comes back on
7630 // the stack. Only a script keeps one.
7631 // Parameters are positional, so even a pattern occupies one argument slot. A
7632 // simple name is that slot itself; anything else (a pattern, a default, a rest
7633 // parameter) takes an anonymous slot and is unpicked into locals at the top of
7634 // the body, which is the only way one argument can bind several names.
7635 let mut prologue: Vec<(usize, Pattern)> = Vec::new();
7636 // `.length` stops at the first parameter that can be substituted: a default
7637 // fills a missing argument in, and a rest parameter absorbs the rest.
7638 let mut defined_args = func.params.len() as u32;
7639 for (index, param) in func.params.iter().enumerate() {
7640 match simple_parameter(param) {
7641 Some(name) => state.args.push(VarDef::var(name.name.clone())),
7642 None => {
7643 state.args.push(VarDef::var(ANONYMOUS_BINDING));
7644 prologue.push((index, param.clone()));
7645 }
7646 }
7647 }
7648 // A default anywhere before the end also ends the count, which the loop above
7649 // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
7650 for (position, param) in func.params.iter().enumerate() {
7651 if matches!(
7652 param.kind,
7653 PatternKind::Assign { .. } | PatternKind::Rest(_)
7654 ) {
7655 defined_args = position as u32;
7656 break;
7657 }
7658 }
7659 state.defined_args = defined_args;
7660 state.param_prologue = prologue;
7661 let depth = self.stack.len();
7662 self.stack.push(state);
7663 let result = self.compile_function_body(func);
7664 if result.is_err() {
7665 // A failed compile must not leave its `FnState` behind. Every caller
7666 // reads `self.state()` as "the function being compiled", so a leftover
7667 // frame silently retargets all later bookkeeping at a dead function.
7668 self.stack.truncate(depth);
7669 }
7670 result
7671 }
7672
7673 /// The body of a function, with its frame already pushed.
7674 fn compile_function_body(
7675 &mut self,
7676 func: &ast::Function,
7677 ) -> Result<CompiledFunction, SyntaxError> {
7678 let body_key = func.params_span.end.offset as u64;
7679 // Where the body begins, in source order. The runtime needs this to tell a
7680 // closure created by a default expression from one the body creates — the two see
7681 // different variable environments — and a bytecode offset would not survive the
7682 // instruction shuffling that building the frame does. Positions are in source
7683 // order, so a comparison answers it.
7684 self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
7685 self.push_block(body_key, NO_PARENT);
7686 self.state().body_block = body_key;
7687 // An arrow with an expression body has no statements; the expression is
7688 // its `return`. Building the statement here keeps one code path below, and
7689 // matters for correctness beyond convenience: returning early with the new
7690 // `FnState` still on the stack would leave the compiler looking at the
7691 // wrong function, which surfaces as an unrelated underflow later.
7692 let concise = match &func.body {
7693 js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
7694 StmtKind::Return(Some(Box::new((**value).clone()))),
7695 value.span,
7696 )),
7697 js_parse::ast::FunctionBody::Block(_) => None,
7698 };
7699 let body: &[Stmt] = match &concise {
7700 Some(stmt) => std::slice::from_ref(stmt),
7701 None => func
7702 .body
7703 .statements()
7704 .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
7705 };
7706 let prologue = std::mem::take(&mut self.state().param_prologue);
7707 let has_param_scope = self.cur().has_parameter_expressions;
7708 // The parameter scope's own bindings, declared in source order.
7709 //
7710 // With parameter expressions the list gets a variable environment of its own, and
7711 // every name it binds is a `let` there. That is what puts the *list* in the
7712 // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
7713 // and `function f(x = y, y){}` does the same, where a single shared environment
7714 // would answer `undefined` to both.
7715 if has_param_scope {
7716 let mut declared: Vec<String> = Vec::new();
7717 for param in &func.params {
7718 let mut names = Vec::new();
7719 param.bound_names(&mut names);
7720 for name in names {
7721 if declared.contains(&name.name) {
7722 continue;
7723 }
7724 declared.push(name.name.clone());
7725 self.declare_param_binding(&name.name);
7726 }
7727 }
7728 }
7729 // A pattern parameter binds its names as function-scope locals, so they have to
7730 // exist — and be unpicked from the argument — before the body runs. With a
7731 // parameter scope these are the *second* environment: the pattern fills the
7732 // parameter's copy, and the body's binding is filled from it afterwards.
7733 for (_, pattern) in &prologue {
7734 let mut names = Vec::new();
7735 pattern.bound_names(&mut names);
7736 for name in names {
7737 self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
7738 }
7739 }
7740 self.hoist(body, body_key)?;
7741 // A constructor's prologue is not a parameter unpacking but the `this` binding:
7742 // a base constructor takes the receiver, a derived one starts in the dead zone
7743 // because only `super()` may produce it.
7744 match self.cur().ctor_kind {
7745 CtorKind::None => {}
7746 CtorKind::Base => {
7747 self.begin_this_local();
7748 self.emit(Opcode::CheckCtor, &[]);
7749 // Instance fields are installed at the top of a base constructor's body,
7750 // before any statement — `class C { x = 1; constructor() { this.x } }` sees
7751 // `1`. This used to be emitted at the *tail*, which made every field read
7752 // `undefined` inside the constructor that declared it.
7753 self.call_field_initialiser();
7754 }
7755 CtorKind::Derived => {
7756 self.declare("this", VarDef::lexical("this"));
7757 let slot = self.cur().vars.len() as u32 - 1;
7758 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7759 self.emit(Opcode::CheckCtor, &[]);
7760 }
7761 }
7762 // Entering the parameter list: everything it binds starts in the dead zone.
7763 // The order is the reference's — it walks the scope chain, which is prepended, so
7764 // the bindings come out newest first.
7765 for name in self.param_binding_names().into_iter().rev() {
7766 if let Some(slot) = self.param_binding_slot(&name) {
7767 self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7768 }
7769 }
7770 // The whole parameter list is one scope, and nothing in the body exists yet, so
7771 // every name it mentions resolves against the parameter bindings and outward.
7772 self.state().in_params = has_param_scope;
7773 for (index, param) in func.params.iter().enumerate() {
7774 if let Some(pattern) = prologue_pattern(&prologue, index) {
7775 // A destructuring parameter *initialises* its bindings: with a parameter
7776 // scope they are the list's own `let`s, which is why the stores skip the
7777 // dead-zone check, and why the reference reads their properties with
7778 // `get_field2` — a `let` needs no reference.
7779 let kind = if has_param_scope {
7780 VarDeclKind::Let
7781 } else {
7782 VarDeclKind::Var
7783 };
7784 match &pattern.kind {
7785 // `...rest` collects what is left rather than reading one slot.
7786 PatternKind::Rest(inner) => {
7787 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7788 self.destructure(inner, Some(kind))?;
7789 }
7790 _ => {
7791 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7792 self.destructure(pattern, Some(kind))?;
7793 }
7794 }
7795 continue;
7796 }
7797 // A plain name binds straight from its argument slot. With a parameter scope
7798 // the slot is also copied into the parameter binding, which is what a later
7799 // default (or a closure made among the defaults) reads.
7800 let Some(name) = simple_parameter(param) else {
7801 continue;
7802 };
7803 let target = self.param_binding_slot(&name.name);
7804 if matches!(param.kind, PatternKind::Rest(_)) {
7805 self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7806 if let Some(slot) = target {
7807 self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
7808 }
7809 // `put_arg` rather than `set_arg`: the array is the last thing on the
7810 // stack and nothing keeps it. Named by hand because a name in the
7811 // parameter list resolves to the parameter binding, and this store has to
7812 // reach the *argument* — that is what the body reads.
7813 self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
7814 continue;
7815 }
7816 if let PatternKind::Assign { default, .. } = ¶m.kind {
7817 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7818 let has_value = self.new_label();
7819 self.emit(Opcode::Dup, &[]);
7820 self.emit(Opcode::IsUndefined, &[]);
7821 self.emit_jump(Opcode::IfFalse, has_value, &[]);
7822 self.emit(Opcode::Drop, &[]);
7823 self.expr(default)?;
7824 self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
7825 // The argument slot keeps the substituted value, because the *body* reads
7826 // the slot rather than the parameter binding — so this store is named
7827 // explicitly, like the rest parameter's.
7828 self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7829 self.place_label(has_value);
7830 if let Some(slot) = target {
7831 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7832 }
7833 continue;
7834 }
7835 if let Some(slot) = target {
7836 self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7837 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7838 }
7839 }
7840 // Copy the parameter scope into the body. A plain parameter needs nothing: the
7841 // body reads its argument slot, and the list kept the two in step. A name a
7842 // pattern bound has no argument slot of its own, so the body gets a `var` filled
7843 // from the parameter's copy — and *that* is why an assignment inside a default
7844 // does not reach the body.
7845 if has_param_scope {
7846 for (_, pattern) in &prologue {
7847 let mut names = Vec::new();
7848 pattern.bound_names(&mut names);
7849 for name in names {
7850 let Some(slot) = self.param_binding_slot(&name.name) else {
7851 continue;
7852 };
7853 let Some(body) = self.body_var_slot(&name.name) else {
7854 continue;
7855 };
7856 self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
7857 self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
7858 }
7859 }
7860 }
7861 // The parameter list is over; from here on a direct `eval` belongs to the body.
7862 self.state().in_params = false;
7863 // Entering the body's own scope comes *after* the parameter list: the body's
7864 // `let`s are not in existence while the defaults run, and the reference emits
7865 // their `set_loc_uninitialized` only once the parameters are bound.
7866 self.emit_scope_enter(body_key);
7867 // A generator starts suspended: `initial_yield` parks the body so that creating one
7868 // runs no body code until the first `next()`.
7869 //
7870 // It comes *after* the parameter unpacking, not before, because a parameter
7871 // initialiser is not body code — `function* g(a = sideEffect())` must run
7872 // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
7873 // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
7874 // until the first `next()` and 29 test262 cases that check for a synchronous throw
7875 // saw none at all.
7876 //
7877 // An async function does **not** get one. Its body runs synchronously up to the
7878 // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
7879 // before its caller's next statement — so an `initial_yield` here would park the
7880 // body before it started, which is not fixable at run time: the suspension looks
7881 // exactly like a real `await`.
7882 if self.cur().kind.is_generator() {
7883 self.emit(Opcode::InitialYield, &[]);
7884 }
7885 // Through `stmts`: the body is a block, and a `using` declaration in it is a
7886 // disposal region.
7887 self.stmts(body)?;
7888 // The implicit return only exists if control can actually get here: an
7889 // infinite loop never falls off the end.
7890 if self.end_is_reachable() {
7891 if self.cur().is_suspending() {
7892 // Falling off the end finishes the generator with `undefined`, and the
7893 // value is what tells the resume machinery "completed" rather than
7894 // "suspended".
7895 self.emit(Opcode::Undefined, &[]);
7896 self.emit(Opcode::ReturnAsync, &[]);
7897 } else {
7898 self.emit_class_constructor_tail();
7899 }
7900 }
7901 // Resolution runs while this function is still on the stack: capturing a
7902 // variable from an enclosing function means reaching into that
7903 // function's state, which requires the whole chain to be present.
7904 Ok(self.finish_current())
7905 }
7906
7907 /// Put every binding of a function that contains a direct `eval` into a cell.
7908 ///
7909 /// A direct eval can name any binding in scope, and any closure it creates has to
7910 /// keep sharing that binding after the function returns — `for (let i …)
7911 /// eval("push(() => i)")` collects one closure per iteration and each must read its
7912 /// own `i`. A copy in a side table would freeze the value, so the binding has to be
7913 /// a cell. Doing this unconditionally for such functions is the cheap, honest
7914 /// answer: the alternative is knowing at compile time which names a string will
7915 /// mention.
7916 fn capture_everything_for_eval(&mut self) {
7917 let current = self.stack.len() - 1;
7918 if !self.stack[current].has_direct_eval {
7919 return;
7920 }
7921 for arg in &mut self.stack[current].args {
7922 arg.is_captured = true;
7923 }
7924 for var in &mut self.stack[current].vars {
7925 var.is_captured = true;
7926 }
7927 }
7928
7929 /// Whether the current position in the instruction stream can be reached.
7930 ///
7931 /// A walk over the control-flow graph, using labels as instruction indices.
7932 /// The reference does the same thing to decide whether an implicit
7933 /// `return_undef` is needed.
7934 fn end_is_reachable(&self) -> bool {
7935 let state = self.cur();
7936 reachable_instructions(state, state.insns.len())[state.insns.len()]
7937 }
7938
7939 /// Resolve and assemble the function on top of the compiler stack, then pop
7940 /// it.
7941 fn finish_current(&mut self) -> CompiledFunction {
7942 self.provide_param_arguments();
7943 self.provide_arguments();
7944 self.provide_this_local();
7945 self.provide_new_target_local();
7946 self.provide_home_object_local();
7947 self.provide_active_func_local();
7948 self.provide_self_name();
7949 self.materialize_eval_sites();
7950 self.capture_everything_for_eval();
7951 let (mut resolved, resolved_pos) = resolve(&mut self.stack);
7952 // Captured bindings need a reference cell; the count goes in the header so
7953 // the runtime knows how many cells to allocate on entry.
7954 let current = self.stack.len() - 1;
7955 let captured = self.stack[current]
7956 .args
7957 .iter()
7958 .filter(|a| a.is_captured)
7959 .count()
7960 + self.stack[current]
7961 .vars
7962 .iter()
7963 .filter(|v| v.is_captured)
7964 .count();
7965 self.stack[current].var_ref_count = captured as u32;
7966 // The scope chain is only final now that every binding is known.
7967 rebuild_scope_chain(&mut self.stack[current]);
7968 let (code, stack_size, positions) =
7969 assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
7970 let _ = &mut resolved;
7971 let mut state = self.stack.pop().expect("a function is being compiled");
7972 CompiledFunction {
7973 name: state.name,
7974 kind: state.kind,
7975 strict: state.strict,
7976 is_derived_constructor: matches!(state.ctor_kind, CtorKind::Derived),
7977 is_arrow: state.is_arrow,
7978 has_parameter_expressions: state.has_parameter_expressions,
7979 simple_parameter_list: state.simple_parameter_list,
7980 body_start: state.body_start,
7981 args: state.args,
7982 defined_args: state.defined_args,
7983 vars: state.vars,
7984 closure_vars: state.closure_vars,
7985 cpool: state.cpool,
7986 atoms: state.atoms,
7987 code,
7988 stack_size,
7989 var_ref_count: state.var_ref_count,
7990 positions,
7991 source: self.function_source(state.span, state.line, state.column),
7992 line: state.line,
7993 column: state.column,
7994 filename: None,
7995 eval_sites: state.eval_sites,
7996 module: state.module.take().map(Box::new),
7997 }
7998 }
7999}
8000
8001/// Assign each binding a scope level and rebuild the scope chains.
8002///
8003/// Levels are numbered in the order the blocks appear, with 0 reserved for the
8004/// function scope where `var` and hoisted functions live. Every binding outside
8005/// level 0 gets a `scope_next` link to the next binding visible from the same
8006/// point, so walking a block's chain enumerates exactly the bindings live there.
8007///
8008/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
8009/// point at `b`, which is declared later in the source but earlier in the chain.
8010fn rebuild_scope_chain(state: &mut FnState) {
8011 // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
8012 // real block that happens to start at offset zero keeps its own level instead of
8013 // being merged into the function scope.
8014 let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
8015 for block in &state.blocks {
8016 if !levels.contains(&block.key) {
8017 levels.push(block.key);
8018 }
8019 }
8020 let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
8021 let parent_level = |level: usize| -> usize {
8022 if level == 0 {
8023 return 0;
8024 }
8025 let key = levels[level];
8026 let parent = state
8027 .blocks
8028 .iter()
8029 .find(|b| b.key == key)
8030 .map(|b| b.parent)
8031 .unwrap_or(FUNCTION_SCOPE);
8032 level_of(parent)
8033 };
8034
8035 // Own bindings per level, in declaration order.
8036 let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
8037 let keys: Vec<u64> = (0..state.vars.len())
8038 .map(|index| {
8039 state
8040 .var_block
8041 .get(index)
8042 .copied()
8043 .unwrap_or(FUNCTION_SCOPE)
8044 })
8045 .collect();
8046 for (index, key) in keys.into_iter().enumerate() {
8047 // The parameter scope is not a block: it is a level of its own with no parent,
8048 // assigned below. Letting it land in level 0 would chain the body's bindings onto
8049 // it, which the reference does not do — the two environments are siblings.
8050 if key == PARAM_SCOPE {
8051 continue;
8052 }
8053 let level = level_of(key);
8054 state.vars[index].scope_level = level as u32;
8055 // A `catch` parameter is part of the runtime scope chain even though it is
8056 // not lexical: the handler's own bindings chain on to it, which is why the
8057 // reference prints `let y [next:1]` with `e` at 1.
8058 if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
8059 {
8060 own[level].push(index);
8061 }
8062 }
8063
8064 // A scope's chain is its own bindings in reverse declaration order followed
8065 // by the enclosing scope's chain.
8066 let mut head = vec![-1i32; levels.len()];
8067 for level in 0..levels.len() {
8068 let inherited = if level == 0 {
8069 -1
8070 } else {
8071 head[parent_level(level)]
8072 };
8073 let chain: Vec<usize> = own[level].iter().rev().copied().collect();
8074 head[level] = chain.first().map_or(inherited, |first| *first as i32);
8075 for (position, &index) in chain.iter().enumerate() {
8076 let next = chain
8077 .get(position + 1)
8078 .map_or(inherited, |next| *next as i32);
8079 state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
8080 }
8081 }
8082 state.block_heads = head;
8083
8084 // The parameter list is a scope of its own, and it has no parent: the reference pops
8085 // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
8086 // the `-1` a block uses. A level past every real block keeps it out of the walk above
8087 // — nothing but the dump reads it — and the links run newest-to-oldest through the
8088 // bindings themselves, which is the order `set_loc_uninitialized` walks.
8089 let param_level = levels.len() as u32;
8090 let mut previous: Option<usize> = None;
8091 for index in 0..state.vars.len() {
8092 if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
8093 {
8094 continue;
8095 }
8096 state.vars[index].scope_level = param_level;
8097 state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
8098 previous = Some(index);
8099 }
8100}
8101
8102/// This is where names become slots and where the temporal dead zone shows up in
8103/// the instruction stream: a read of a `let`/`const` binding compiles to
8104/// `get_loc_check`, which throws if the binding is still uninitialised.
8105///
8106/// The peephole pass from the reference implementation is applied at the end,
8107/// for the same reason it is applied to resolved bytecode there: the patterns are
8108/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
8109/// resolution. Deleted instructions stay in the list as `None` so that label
8110/// indices remain valid; [`Assembler`] maps them to byte offsets.
8111/// A resolved instruction and the source position it came from.
8112type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
8113
8114/// A resolved instruction paired with its position, which is what `assemble` consumes.
8115type PositionedInsn = (Opcode, Vec<Op>);
8116
8117fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
8118 let current = stack.len() - 1;
8119 // Dead-code elimination, on the symbolic form where labels are still
8120 // instruction indices. A `break` inside a loop leaves the trailing `goto`
8121 // unreachable, and a `return` leaves everything after it unreachable; the
8122 // reference drops both. Doing it here means the emitter never has to think
8123 // about reachability.
8124 strip_empty_gosubs(stack, current);
8125 eliminate_dead_code(stack, current);
8126 let insns = std::mem::take(&mut stack[current].insns);
8127 // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
8128 // `insns`, and every arm below pushes exactly one instruction, so the positions
8129 // stay aligned with `out`.
8130 let positions = std::mem::take(&mut stack[current].insn_pos);
8131 let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
8132 let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
8133 for (index, insn) in insns.iter().enumerate() {
8134 let pos = positions.get(index).copied().flatten();
8135 out_pos.push(pos);
8136 match insn {
8137 Insn::Fixed { op, operands } => {
8138 let operands = operands
8139 .iter()
8140 .map(|operand| match operand {
8141 Op::Atom(atom) => {
8142 Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
8143 }
8144 other => other.clone(),
8145 })
8146 .collect();
8147 out.push(Some((*op, operands)));
8148 }
8149 Insn::Var {
8150 action,
8151 name,
8152 block,
8153 in_params,
8154 } => {
8155 // Both reads and writes in the parameter list address the parameter
8156 // scope. That is what puts the list in the temporal dead zone — a read of
8157 // a later parameter is `get_loc_check` on an uninitialised slot — and it
8158 // is also what keeps an assignment made inside a default away from the
8159 // body, which sees a separate environment.
8160 let slot = resolve_slot(stack, current, name, *block, *in_params);
8161 // A store to the name of a named function expression is special: the
8162 // reference drops it in sloppy mode and throws in strict mode, because
8163 // the binding is immutable but only *checked* when the body is strict.
8164 // The same rule applies when the name is reached through a closure:
8165 // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
8166 // the store in the arrow too, not just in the function that owns the
8167 // binding. Reaching the owner means walking the chain of closure
8168 // entries, which is what `self_name_binding` does.
8169 let self_name = matches!(action, VarAction::Put | VarAction::Set)
8170 .then(|| {
8171 // A local of this function is the common case and needs no
8172 // chain walk; only an access that resolves elsewhere can be
8173 // pointing at an enclosing function's name binding.
8174 if let Slot::Loc(index) = slot {
8175 stack[current]
8176 .vars
8177 .get(index as usize)
8178 .filter(|var| var.kind == VarKind::FunctionName)
8179 .map(|var| var.is_const)
8180 } else {
8181 self_name_binding(stack, current, name, *block)
8182 }
8183 })
8184 .flatten();
8185 if let Some(is_const) = self_name {
8186 out.push(Some(if is_const {
8187 (
8188 Opcode::ThrowError,
8189 vec![
8190 Op::AtomId(intern_atom(&mut stack[current], name)),
8191 Op::Int(0),
8192 ],
8193 )
8194 } else {
8195 (Opcode::Drop, Vec::new())
8196 }));
8197 continue;
8198 }
8199 out.push(Some(variable_instruction(stack, current, *action, slot)));
8200 }
8201 Insn::CloseCaptured { name, block } => {
8202 // The block matters: a loop variable is scoped to the `for` head's own
8203 // block, so resolving it against block 0 would miss it entirely and
8204 // silently emit nothing.
8205 let slot = resolve_slot(stack, current, name, *block, false);
8206 // Only a local with a reference cell has anything to close. A global
8207 // or a never-captured local resolves to no instruction at all, which
8208 // keeps the bytecode identical to the reference's.
8209 if let Slot::Loc(index) = slot
8210 && stack[current]
8211 .vars
8212 .get(index as usize)
8213 .is_some_and(|v| v.is_captured)
8214 {
8215 out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
8216 } else {
8217 out.push(None);
8218 }
8219 }
8220 Insn::DeleteVar { name } => {
8221 // A binding — a local, an argument, or a declared global — cannot be
8222 // deleted, and the reference encodes that as a constant `push_false`.
8223 // Only an implicit global needs the runtime lookup.
8224 if matches!(
8225 resolve_slot(stack, current, name, 0, false),
8226 Slot::Global(_)
8227 ) {
8228 let atom = intern_atom(&mut stack[current], name);
8229 out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
8230 } else {
8231 out.push(Some((Opcode::PushFalse, Vec::new())));
8232 }
8233 }
8234 Insn::Dead => out.push(None),
8235 }
8236 }
8237 // Which label (if any) sits on each instruction, so the jump patterns can
8238 // tell whether they would cross a jump target.
8239 let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
8240 for (id, placed) in stack[current].labels.iter().enumerate() {
8241 if let Some(index) = *placed
8242 && index < label_at.len()
8243 && label_at[index].is_none()
8244 {
8245 label_at[index] = Some(id as u32);
8246 }
8247 }
8248 if std::env::var_os("QJS_DEBUG").is_some() {
8249 eprintln!("--- peephole entry ---");
8250 for (i, e) in out.iter().enumerate() {
8251 eprintln!("{i}: {e:?}");
8252 }
8253 eprintln!("label_at: {label_at:?}");
8254 }
8255 peephole(&mut out, &label_at, &stack[current].labels);
8256 (out, out_pos)
8257}
8258
8259/// Find where `name` lives, capturing it in an enclosing function when needed.
8260///
8261/// The search runs outward through the enclosing functions' states, which are
8262/// still on the compiler stack while a nested function is resolved. Finding the
8263/// name in an enclosing function is what creates a closure reference, and every
8264/// function in between has to forward it — a function can only reach its own
8265/// parent's frame.
8266///
8267/// A name declared nowhere is a global. The reference does *not* look it up by
8268/// name from the inner function: the top-level function gets one `[global]`
8269/// entry and every nested function gets a `[global_ref<n>]` pointing at its
8270/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
8271/// rather than `[global]`.
8272/// The lexical blocks enclosing `block`, innermost first.
8273fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
8274 let mut chain = Vec::new();
8275 let mut current = Some(block);
8276 while let Some(key) = current {
8277 // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
8278 // explicitly (rather than on "no block with this key") is what keeps a block
8279 // that happens to sit at offset zero from being mistaken for the terminator.
8280 if key == NO_PARENT || chain.contains(&key) {
8281 break;
8282 }
8283 chain.push(key);
8284 current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
8285 }
8286 chain
8287}
8288
8289/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
8290///
8291/// The binding may be several functions away: an arrow nested in `function myfunc`
8292/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
8293/// means following `Ref` entries down and then reading the owning function's var table.
8294fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
8295 let state = stack.get(current)?;
8296 // A parameter shadows everything and is never a function-expression name.
8297 if state.args.iter().any(|arg| arg.name == name) {
8298 return None;
8299 }
8300 // A local of this very function: the answer is in its var table.
8301 if let Some(index) = local_slot_index(state, name, block) {
8302 let var = state.vars.get(index)?;
8303 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
8304 }
8305 // Otherwise the name lives further out, and the closure entry says how to get
8306 // there. `Local` names the owner's slot directly; `Ref` names the next level's
8307 // closure entry, so the walk continues downwards.
8308 let mut level = current;
8309 let mut index = state
8310 .closure_vars
8311 .iter()
8312 .position(|closure| closure.name == name)?;
8313 loop {
8314 let state = stack.get(level)?;
8315 let closure = state.closure_vars.get(index)?;
8316 match closure.closure_type {
8317 ClosureType::Local => {
8318 let owner = stack.get(level.checked_sub(1)?)?;
8319 let var = owner.vars.get(closure.var_idx as usize)?;
8320 return (var.kind == VarKind::FunctionName).then_some(var.is_const);
8321 }
8322 ClosureType::Arg => return None,
8323 ClosureType::Ref => {
8324 level -= 1;
8325 index = closure.var_idx as usize;
8326 }
8327 // A global is never a function-expression name.
8328 ClosureType::Global
8329 | ClosureType::GlobalDecl
8330 | ClosureType::GlobalRef
8331 | ClosureType::ModuleDecl
8332 | ClosureType::ModuleImport => return None,
8333 }
8334 }
8335}
8336
8337/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
8338fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
8339 block_chain(state, block).into_iter().find_map(|scope| {
8340 state.vars.iter().enumerate().find_map(|(index, var)| {
8341 (var.name == name && state.var_block.get(index).copied() == Some(scope))
8342 .then_some(index)
8343 })
8344 })
8345}
8346
8347/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
8348fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
8349 if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
8350 var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
8351 }) {
8352 return index as u32;
8353 }
8354 state.var_block.push(PARAM_SCOPE);
8355 state.vars.push(VarDef::var(name));
8356 state.vars.len() as u32 - 1
8357}
8358
8359/// The name a parameter binds straight from its argument slot, if it has one.
8360///
8361/// A plain name does — with or without a default, and with or without `...`. Everything
8362/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
8363/// reference names the argument in the first case and leaves it `<null>` in the second,
8364/// so both the dump and the closures that capture the argument depend on this.
8365fn simple_parameter(param: &Pattern) -> Option<&Ident> {
8366 match ¶m.kind {
8367 PatternKind::Ident(name) => Some(name),
8368 PatternKind::Assign { target, .. } => match &target.kind {
8369 PatternKind::Ident(name) => Some(name),
8370 _ => None,
8371 },
8372 PatternKind::Rest(inner) => match &inner.kind {
8373 PatternKind::Ident(name) => Some(name),
8374 _ => None,
8375 },
8376 _ => None,
8377 }
8378}
8379
8380/// The pattern a parameter list has to unpick, if `index` is one of them.
8381fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
8382 prologue
8383 .iter()
8384 .find(|(at, _)| *at == index)
8385 .map(|(_, pattern)| pattern)
8386}
8387
8388fn pattern_has_default(pattern: &Pattern) -> bool {
8389 match &pattern.kind {
8390 PatternKind::Assign { .. } => true,
8391 PatternKind::Rest(inner) => pattern_has_default(inner),
8392 PatternKind::Array { elements, rest } => {
8393 elements.iter().flatten().any(element_has_default)
8394 || rest.as_deref().is_some_and(rest_has_default)
8395 }
8396 PatternKind::Object { properties, rest } => {
8397 properties.iter().flatten().any(element_has_default)
8398 || rest.as_deref().is_some_and(rest_has_default)
8399 }
8400 _ => false,
8401 }
8402}
8403
8404fn element_has_default(element: &PatternElement) -> bool {
8405 match element {
8406 PatternElement::Pattern(pattern) => pattern_has_default(pattern),
8407 PatternElement::Property { value, .. } => pattern_has_default(value),
8408 }
8409}
8410
8411fn rest_has_default(rest: &RestElement) -> bool {
8412 match rest {
8413 RestElement::Pattern(pattern) => pattern_has_default(pattern),
8414 RestElement::Member(_) => false,
8415 }
8416}
8417
8418/// Whether a function-scope binding is visible to the parameter list.
8419///
8420/// The parameter list runs before the body, so the body's `var`s and function
8421/// declarations do not exist yet — a name that only the body declares has to resolve
8422/// outward instead. What *does* exist by then is the compiler's own prologue: the
8423/// self-name of a named function expression (bound by `special_object 2` before anything
8424/// else), `this` and `new.target`. Those stay visible, which is what makes
8425/// `function f(a = this)` and `var f = function f(a = f)` work.
8426///
8427/// `arguments` is handled separately, as a binding of the parameter scope itself: with
8428/// parameter expressions the reference creates two of them, and the one the parameter
8429/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
8430fn visible_in_params(var: &VarDef) -> bool {
8431 var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
8432}
8433
8434fn resolve_slot(
8435 stack: &mut [FnState],
8436 current: usize,
8437 name: &str,
8438 block: u64,
8439 in_params: bool,
8440) -> Slot {
8441 // The parameter list's own bindings. They are consulted first because they shadow
8442 // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
8443 // `a` in the parameter scope, so a closure made there reads the parameter even after
8444 // the body assigns to its own `a`.
8445 if in_params
8446 && let Some(index) = stack[current]
8447 .vars
8448 .iter()
8449 .enumerate()
8450 .position(|(index, var)| {
8451 var.name == name
8452 && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
8453 })
8454 {
8455 return Slot::Loc(index as u32);
8456 }
8457 // A name can be bound more than once: two `catch` parameters in nested
8458 // handlers are two slots. The binding that wins is the one whose scope encloses
8459 // the access, and among those the innermost — so the blocks are walked outward
8460 // and the first binding found on the way is the one that counts. A binding in
8461 // no block (`var`) is reachable from anywhere, which is why the function scope
8462 // is the end of the walk.
8463 //
8464 // The block walk comes *before* the argument slots, because a block may shadow a
8465 // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
8466 // slot is only the answer once nothing nearer claims the name.
8467 let chain = block_chain(&stack[current], block);
8468 for scope in &chain {
8469 let found = stack[current]
8470 .vars
8471 .iter()
8472 .enumerate()
8473 .find(|(index, var)| {
8474 var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
8475 })
8476 .map(|(index, _)| index);
8477 if let Some(index) = found {
8478 return Slot::Loc(index as u32);
8479 }
8480 }
8481 // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
8482 // its own slot, and `var` of the same name in the body is the same binding.
8483 if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
8484 return Slot::Arg(index as u32);
8485 }
8486 // Function-scope bindings — `var` and function declarations — are recorded with
8487 // the sentinel block `0`, which no real scope uses, so the walk above cannot see
8488 // them. They are reachable from anywhere in the function, which is exactly what
8489 // the sentinel means.
8490 //
8491 // This pass is *only* for those. A lexical binding has to be found through the
8492 // chain or not at all, and looking a name up without its block is precisely how
8493 // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
8494 // block leaked out of it.
8495 let function_scoped = stack[current]
8496 .vars
8497 .iter()
8498 .enumerate()
8499 .find(|(index, var)| {
8500 var.name == name
8501 && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
8502 && (!in_params || visible_in_params(var))
8503 })
8504 .map(|(index, _)| index);
8505 if let Some(index) = function_scoped {
8506 return Slot::Loc(index as u32);
8507 }
8508 if let Some(index) = stack[current]
8509 .closure_vars
8510 .iter()
8511 .position(|c| c.name == name)
8512 {
8513 return slot_for_closure(&stack[current].closure_vars[index], index as u32);
8514 }
8515
8516 for owner in (0..current).rev() {
8517 // The nested function was created inside one of this frame's blocks, and the
8518 // outermost visible binding is the innermost block on that chain — not whatever
8519 // comes first in the variable table. `function f(){ class S{} }` has two `S`
8520 // bindings: the `let S` inside `f` and the `const S` inside the class body, and
8521 // the class body is the one a method may see.
8522 let entry = stack
8523 .get(owner + 1)
8524 .map(|s| s.created_in_block)
8525 .unwrap_or(0);
8526 let lexical = block_chain(&stack[owner], entry)
8527 .into_iter()
8528 .find_map(|scope| {
8529 stack[owner]
8530 .vars
8531 .iter()
8532 .enumerate()
8533 .find(|(index, var)| {
8534 var.name == name
8535 && stack[owner].var_block.get(*index).copied() == Some(scope)
8536 })
8537 .map(|(index, _)| index)
8538 });
8539 // A function born in a parameter list sees that list's bindings, not the body's:
8540 // the parameter scope is the environment it was created in.
8541 let in_param_scope = stack
8542 .get(owner + 1)
8543 .is_some_and(|child| child.created_in_params)
8544 .then(|| {
8545 stack[owner]
8546 .vars
8547 .iter()
8548 .enumerate()
8549 .position(|(index, var)| {
8550 var.name == name
8551 && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
8552 })
8553 })
8554 .flatten();
8555 let found = if let Some(index) = in_param_scope {
8556 let var = &stack[owner].vars[index];
8557 Some(Found::Local(
8558 ClosureType::Local,
8559 index as u32,
8560 var.is_const,
8561 var.needs_check(),
8562 ))
8563 } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
8564 Some(Found::Local(ClosureType::Arg, index as u32, false, false))
8565 } else if let Some(index) = lexical {
8566 let var = &stack[owner].vars[index];
8567 Some(Found::Local(
8568 ClosureType::Local,
8569 index as u32,
8570 var.is_const,
8571 var.needs_check(),
8572 ))
8573 } else if let Some(index) = stack[owner]
8574 .vars
8575 .iter()
8576 .enumerate()
8577 .find_map(|(index, var)| {
8578 // A function created inside a parameter list must not see the body of the
8579 // function it was born in; see [`FnState::created_in_params`].
8580 let hidden = stack
8581 .get(owner + 1)
8582 .is_some_and(|child| child.created_in_params);
8583 (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
8584 })
8585 {
8586 let var = &stack[owner].vars[index];
8587 Some(Found::Local(
8588 ClosureType::Local,
8589 index as u32,
8590 var.is_const,
8591 var.needs_check(),
8592 ))
8593 } else if stack[owner].self_name.as_deref() == Some(name) {
8594 // A named function expression's own name. The reference declares it here,
8595 // on the first lookup that fails, rather than up front — and that is what
8596 // makes it reachable from a *nested* function: the nested lookup is what
8597 // walks out and creates the binding. A direct reference in the body is
8598 // caught the same way, which is why `provide_self_name` only has to add
8599 // the prologue.
8600 let strict = stack[owner].strict;
8601 stack[owner].var_block.push(FUNCTION_SCOPE);
8602 stack[owner].vars.push(VarDef {
8603 kind: VarKind::FunctionName,
8604 // In strict mode the name is immutable, so a store raises; sloppy
8605 // mode drops the store instead (see `variable_instruction`).
8606 is_const: strict,
8607 ..VarDef::var(name)
8608 });
8609 let index = stack[owner].vars.len() as u32 - 1;
8610 Some(Found::Local(ClosureType::Local, index, strict, false))
8611 } else if let Some(index) = stack[owner]
8612 .closure_vars
8613 .iter()
8614 .position(|c| c.name == name)
8615 {
8616 let closure = &stack[owner].closure_vars[index];
8617 Some(match closure.closure_type {
8618 // `GlobalRef` belongs here too: it is a *global* reached through this
8619 // frame's reference table, so treating it as a `Ref` to a local cell makes
8620 // the reader look for a cell no frame ever fills. That is how a second
8621 // function using `eval` in its parameter list read `undefined` after a
8622 // sibling had already made `eval` a closure entry.
8623 ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
8624 Found::Global(index as u32)
8625 }
8626 // A module variable is a cell in the *module's* environment, which is
8627 // the module body's parent as far as a nested function is concerned — so
8628 // it is captured as a plain reference, not looked up as a global.
8629 ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
8630 ClosureType::Ref,
8631 index as u32,
8632 closure.is_const,
8633 closure.is_lexical,
8634 ),
8635 _ => Found::Local(
8636 ClosureType::Ref,
8637 index as u32,
8638 closure.is_const,
8639 closure.is_lexical,
8640 ),
8641 })
8642 } else {
8643 None
8644 };
8645 let Some(found) = found else { continue };
8646
8647 let (is_const, is_lexical) = match found {
8648 Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
8649 Found::Global(_) => (false, false),
8650 };
8651 // Mark the owner's binding as captured so it moves into a reference cell.
8652 if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
8653 let slot = match found {
8654 Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
8655 _ => &mut stack[owner].vars[index as usize],
8656 };
8657 slot.is_captured = true;
8658 }
8659 // Forward the reference through every function in between.
8660 let mut previous = match found {
8661 Found::Local(kind, index, _, _) => (kind, index),
8662 Found::Global(index) => (ClosureType::Global, index),
8663 };
8664 for level in owner + 1..=current {
8665 let kind = match (previous.0, level) {
8666 // A global stays a global at *every* level. Without `GlobalRef` in
8667 // this arm the second nested function over the same global got a
8668 // `Ref` to a cell no frame ever held, so the innermost closure read
8669 // `undefined` — which is how a two-deep getter lost its outer
8670 // variable.
8671 (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
8672 ClosureType::GlobalRef
8673 }
8674 (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
8675 _ => ClosureType::Ref,
8676 };
8677 let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
8678 previous = (kind, index);
8679 }
8680 let index = previous.1;
8681 return slot_for_closure(&stack[current].closure_vars[index as usize], index);
8682 }
8683
8684 // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
8685 // creating a property. The top-level function holds the entry.
8686 let mut previous = (
8687 ClosureType::Global,
8688 ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
8689 );
8690 for level in 1..=current {
8691 let index = ensure_closure(
8692 stack,
8693 level,
8694 name,
8695 false,
8696 false,
8697 ClosureType::GlobalRef,
8698 previous.1,
8699 );
8700 previous = (ClosureType::GlobalRef, index);
8701 }
8702 Slot::Global(previous.1)
8703}
8704
8705/// What an outward search turned up.
8706#[derive(Debug, Clone, Copy)]
8707enum Found {
8708 /// A binding in an enclosing function, reachable through a closure of this
8709 /// type, with its const/lexical flags.
8710 Local(ClosureType, u32, bool, bool),
8711 /// A global, reached through the enclosing function's closure entry.
8712 Global(u32),
8713}
8714
8715/// Add a closure entry to `level` if it is not there yet.
8716fn ensure_closure(
8717 stack: &mut [FnState],
8718 level: usize,
8719 name: &str,
8720 is_const: bool,
8721 is_lexical: bool,
8722 closure_type: ClosureType,
8723 var_idx: u32,
8724) -> u32 {
8725 if let Some(index) = stack[level]
8726 .closure_vars
8727 .iter()
8728 .position(|c| c.name == name)
8729 {
8730 return index as u32;
8731 }
8732 stack[level].closure_vars.push(ClosureVar {
8733 name: name.to_string(),
8734 is_const,
8735 is_lexical,
8736 closure_type,
8737 var_idx: var_idx as u16,
8738 });
8739 stack[level].closure_vars.len() as u32 - 1
8740}
8741
8742fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
8743 match closure.closure_type {
8744 // A `global_ref` only says *how* the binding is found (through the
8745 // parent's closure table); the access itself is an ordinary global one.
8746 ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
8747 ClosureType::GlobalDecl => Slot::GlobalDecl(index),
8748 // A module variable is a real cell in the module's environment, so it is reached
8749 // exactly like a captured local — the host, not the global object, is what fills
8750 // the slot.
8751 ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
8752 _ => Slot::VarRef(index),
8753 }
8754}
8755
8756/// Pick the opcode for one variable access.
8757///
8758/// The `_check` variants are what enforce the temporal dead zone. They are used
8759/// for every access to a `let`/`const` binding except its own initialisation —
8760/// which is exactly the operation that takes the binding out of the dead zone.
8761fn variable_instruction(
8762 stack: &[FnState],
8763 current: usize,
8764 action: VarAction,
8765 slot: Slot,
8766) -> (Opcode, Vec<Op>) {
8767 let lexical = match slot {
8768 Slot::Loc(index) => stack[current]
8769 .vars
8770 .get(index as usize)
8771 .is_some_and(|v| v.needs_check()),
8772 Slot::VarRef(index) => stack[current]
8773 .closure_vars
8774 .get(index as usize)
8775 .is_some_and(|c| c.is_lexical),
8776 _ => false,
8777 };
8778 let operand = vec![Op::Slot(slot)];
8779 match (action, slot) {
8780 (VarAction::Get, Slot::Loc(index)) => (
8781 if lexical {
8782 Opcode::GetLocCheck
8783 } else {
8784 Opcode::GetLoc
8785 },
8786 vec![Op::Slot(Slot::Loc(index))],
8787 ),
8788 (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
8789 (VarAction::Get, Slot::VarRef(index)) => (
8790 if lexical {
8791 Opcode::GetVarRefCheck
8792 } else {
8793 Opcode::GetVarRef
8794 },
8795 vec![Op::Slot(Slot::VarRef(index))],
8796 ),
8797 (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
8798 (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
8799 // `typeof x` is a *reading* of `x` (§13.5.3 evaluates the operand as a Reference and
8800 // then `GetValue`s it), so a lexical binding still has its dead zone checked. Only
8801 // the *unresolvable* case is different: `typeof undeclared` answers `"undefined"`
8802 // instead of throwing, and that is what `GetVarUndef` is for. Skipping the check for
8803 // every slot made `typeof x; let x;` print `"undefined"` where the spec requires a
8804 // `ReferenceError`.
8805 (VarAction::GetUndef, Slot::Loc(index)) => (
8806 if lexical {
8807 Opcode::GetLocCheck
8808 } else {
8809 Opcode::GetLoc
8810 },
8811 vec![Op::Slot(Slot::Loc(index))],
8812 ),
8813 (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
8814 (VarAction::GetUndef, Slot::VarRef(index)) => (
8815 if lexical {
8816 Opcode::GetVarRefCheck
8817 } else {
8818 Opcode::GetVarRef
8819 },
8820 vec![Op::Slot(Slot::VarRef(index))],
8821 ),
8822 (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8823 (Opcode::GetVarUndef, operand)
8824 }
8825
8826 (VarAction::Put, Slot::Loc(_)) => (
8827 if lexical {
8828 Opcode::PutLocCheck
8829 } else {
8830 Opcode::PutLoc
8831 },
8832 operand,
8833 ),
8834 (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
8835 (VarAction::Put, Slot::VarRef(_)) => (
8836 if lexical {
8837 Opcode::PutVarRefCheck
8838 } else {
8839 Opcode::PutVarRef
8840 },
8841 operand,
8842 ),
8843 (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
8844 (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8845 // Initialisation is what ends the dead zone, so it never checks.
8846 (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8847 (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
8848 // `this` in a derived constructor is always a local, so these cannot happen;
8849 // routing them to the ordinary forms keeps the match total without inventing
8850 // opcodes the reference does not have.
8851 (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
8852 (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8853 (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8854 (Opcode::PutVarInit, operand)
8855 }
8856 (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
8857 (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8858 (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8859 (Opcode::PutVarInit, operand)
8860 }
8861 (VarAction::Set, Slot::Loc(_)) => (
8862 if lexical {
8863 Opcode::SetLocCheck
8864 } else {
8865 Opcode::SetLoc
8866 },
8867 operand,
8868 ),
8869 (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
8870 (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
8871 (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8872 (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8873 (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
8874 (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8875 (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
8876 (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
8877 (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8878 (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
8879 (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8880 (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
8881 }
8882}
8883
8884/// The instruction-rewriting pass.
8885///
8886/// These are the reference implementation's patterns, restricted to the ones the
8887/// constructs this compiler supports can produce. Each entry is a comment on the
8888/// bytecode it removes, because the whole point is that the result is one
8889/// instruction shorter than the literal translation of the AST.
8890fn peephole(
8891 insns: &mut [Option<(Opcode, Vec<Op>)>],
8892 label_at: &[Option<u32>],
8893 placed: &[Option<usize>],
8894) {
8895 fold_dup_patterns(insns, label_at);
8896
8897 // `drop` before `return_undef` is dead: the return discards the whole frame
8898 // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
8899 // consumes its own `drop`; removing the drop first would leave the `dup` and
8900 // produce a `set_` where the reference has a `put_`.
8901 for index in 0..insns.len() {
8902 if opcode_at(insns, index) != Some(Opcode::Drop) {
8903 continue;
8904 }
8905 // Skip over a run of drops, but stop at a jump target: removing code on
8906 // one side of a label would silently retarget the jump.
8907 let mut next = index + 1;
8908 while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
8909 next += 1;
8910 }
8911 if is_label_at(label_at, next) {
8912 continue;
8913 }
8914 if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
8915 for entry in &mut insns[index..next] {
8916 *entry = None;
8917 }
8918 }
8919 }
8920
8921 // The rewrites below all decide against one fixed snapshot, which is what the
8922 // reference sees: `code_match` reads the bytecode buffer as it was on entry to
8923 // the pass, so a rule never observes what an earlier rule removed. Gathering
8924 // every deletion first and applying them together reproduces that.
8925 let snapshot: Vec<Option<Opcode>> = insns
8926 .iter()
8927 .map(|entry| entry.as_ref().map(|(op, _)| *op))
8928 .collect();
8929 // The next instruction that is still there. Holes left by dead-code
8930 // elimination are not instructions, so a rule looks past them.
8931 let next_op = |index: usize| -> Option<usize> {
8932 (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
8933 };
8934
8935 let mut doomed = vec![false; insns.len()];
8936 for index in 0..insns.len() {
8937 // A constant pushed only to be dropped does nothing at all. This is what a
8938 // comma expression with a literal left operand compiles to — `(0, f)()` — and
8939 // the reference removes the pair rather than making the reader step over it.
8940 let constant = matches!(
8941 snapshot[index],
8942 Some(
8943 Opcode::Undefined
8944 | Opcode::Null
8945 | Opcode::PushMinus1
8946 | Opcode::Push0
8947 | Opcode::Push1
8948 | Opcode::Push2
8949 | Opcode::Push3
8950 | Opcode::Push4
8951 | Opcode::Push5
8952 | Opcode::Push6
8953 | Opcode::Push7
8954 | Opcode::PushTrue
8955 | Opcode::PushFalse
8956 | Opcode::PushI32
8957 )
8958 );
8959 if constant
8960 && let Some(next) = next_op(index)
8961 && snapshot[next] == Some(Opcode::Drop)
8962 {
8963 doomed[index] = true;
8964 doomed[next] = true;
8965 }
8966 }
8967 for (index, entry) in insns.iter_mut().enumerate() {
8968 if doomed[index] {
8969 *entry = None;
8970 }
8971 }
8972
8973 // A conditional whose destination is the very next instruction just pops its
8974 // condition, so it becomes a plain `drop`. This is what an empty `case` clause
8975 // compiles to.
8976 //
8977 // Order matters, and it is the reference's order: this runs *before* the
8978 // folding below, on the instruction the conditional originally had. Folding
8979 // moves a conditional's destination, and the reference never re-examines it
8980 // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
8981 // a conditional even though folding leaves it pointing at the next
8982 // instruction.
8983 for (index, entry) in insns.iter_mut().enumerate() {
8984 let Some((op, operands)) = entry.clone() else {
8985 continue;
8986 };
8987 if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
8988 continue;
8989 }
8990 let Some(id) = label_id(&operands) else {
8991 continue;
8992 };
8993 if placed.get(id as usize).copied().flatten() == Some(index + 1) {
8994 *entry = Some((Opcode::Drop, Vec::new()));
8995 }
8996 }
8997
8998 // A constant condition is decided here rather than at run time.
8999 fold_constant_conditions(insns);
9000 // The conditional folding below is about pairs of *real* branches, so it runs
9001 // before a jump to the next instruction is dropped: `do { … if (c) continue }
9002 // while (t)` puts `continue` exactly on the condition, and the reference inverts
9003 // the branch first and only then notices the jump goes nowhere.
9004 fold_conditional_jumps(insns, label_at, placed);
9005
9006 // A jump whose destination is the very next instruction does nothing, which is
9007 // what constant folding leaves behind for `while (1) { … }`.
9008 remove_jump_to_next(insns, placed);
9009
9010 // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
9011 // a use of the same variable boils down to.
9012 for index in 0..insns.len() {
9013 let Some((put_op, _)) = insns[index].clone() else {
9014 continue;
9015 };
9016 if !is_foldable_put(put_op) {
9017 continue;
9018 }
9019 if is_label_at(label_at, index + 1) {
9020 continue;
9021 }
9022 let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
9023 continue;
9024 };
9025 if get_op != get_form_of(put_op) {
9026 continue;
9027 }
9028 let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
9029 if put_slot.is_none() || put_slot != get_operands.first().cloned() {
9030 continue;
9031 }
9032 insns[index] = Some((set_form_of(put_op), get_operands));
9033 insns[index + 1] = None;
9034 }
9035}
9036
9037/// Drop `gosub`s that call an empty subroutine.
9038///
9039/// A `gosub` whose target starts with `ret` returns immediately, so the reference
9040/// drops the call. This is how `try`/`catch` without a `finally` loses its
9041/// finalizer plumbing: the finalizer block is empty, its first instruction is
9042/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
9043/// [`eliminate_dead_code`] then removes.
9044fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
9045 let state = &stack[current];
9046 let mut targets = Vec::new();
9047 for insn in &state.insns {
9048 if let Insn::Fixed { op, operands } = insn
9049 && *op == Opcode::Gosub
9050 && let Some(id) = label_id(operands)
9051 && let Some(target) = state.labels.get(id as usize).copied().flatten()
9052 {
9053 targets.push(target);
9054 }
9055 }
9056 let empty: Vec<usize> = targets
9057 .into_iter()
9058 .filter(|target| {
9059 stack[current]
9060 .insns
9061 .get(*target)
9062 .map(|insn| {
9063 matches!(
9064 insn,
9065 Insn::Fixed {
9066 op: Opcode::Ret,
9067 ..
9068 }
9069 )
9070 })
9071 .unwrap_or(false)
9072 })
9073 .collect();
9074 if empty.is_empty() {
9075 return;
9076 }
9077 for insn in stack[current].insns.iter_mut() {
9078 if let Insn::Fixed { op, operands } = insn
9079 && *op == Opcode::Gosub
9080 && let Some(id) = label_id(operands)
9081 && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
9082 && empty.contains(&target)
9083 {
9084 *insn = Insn::Dead;
9085 }
9086 }
9087}
9088
9089/// Replace unreachable instructions with [`Insn::Dead`].
9090fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
9091 let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
9092 for (index, insn) in stack[current].insns.iter_mut().enumerate() {
9093 if !reachable[index] {
9094 *insn = Insn::Dead;
9095 }
9096 }
9097}
9098
9099/// Mark every instruction index reachable from the entry, plus the index one past
9100/// the last instruction.
9101///
9102/// `seen[len]` answers "can control reach the end of this function", and the
9103/// entries before it identify dead code. Both DCE and the implicit-return decision
9104/// read the same result, which keeps them from disagreeing.
9105fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
9106 let mut seen = vec![false; count + 1];
9107 let mut worklist = vec![0usize];
9108 while let Some(index) = worklist.pop() {
9109 if index > count || seen[index] {
9110 continue;
9111 }
9112 seen[index] = true;
9113 if index == count {
9114 continue;
9115 }
9116 let (op, operands) = match &state.insns[index] {
9117 Insn::Fixed { op, operands } => (*op, operands.as_slice()),
9118 // A variable access never transfers control, and a removed
9119 // instruction is only reachable if it is already marked.
9120 Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
9121 worklist.push(index + 1);
9122 continue;
9123 }
9124 };
9125 match op {
9126 // A return, a throw and a `ret` all leave this instruction stream: the
9127 // first two give control to the caller or the handler, and `ret`
9128 // returns to a `gosub` elsewhere.
9129 // A tail call leaves the function too: the callee's result becomes this
9130 // function's result, so nothing after it runs.
9131 Opcode::Return
9132 | Opcode::ReturnUndef
9133 | Opcode::ReturnAsync
9134 | Opcode::TailCall
9135 | Opcode::TailCallMethod
9136 | Opcode::Throw
9137 | Opcode::ThrowError
9138 | Opcode::Ret => {}
9139 // A `catch` records where exceptions from the code that follows go.
9140 // That code is not reachable through normal control flow, but it is
9141 // reachable — through the exception edge — so the walk has to follow
9142 // it, or dead-code elimination would delete every handler.
9143 Opcode::Catch => {
9144 if let Some(target) = placed_label(state, operands) {
9145 worklist.push(target);
9146 }
9147 worklist.push(index + 1);
9148 }
9149 // A `gosub` calls a subroutine and then continues, so both edges count.
9150 Opcode::Gosub => {
9151 if let Some(target) = placed_label(state, operands) {
9152 worklist.push(target);
9153 }
9154 worklist.push(index + 1);
9155 }
9156 Opcode::Goto => {
9157 if let Some(target) = placed_label(state, operands) {
9158 worklist.push(target);
9159 }
9160 }
9161 Opcode::IfTrue | Opcode::IfFalse => {
9162 if let Some(target) = placed_label(state, operands) {
9163 worklist.push(target);
9164 }
9165 worklist.push(index + 1);
9166 }
9167 _ => worklist.push(index + 1),
9168 }
9169 }
9170 seen
9171}
9172
9173/// The instruction index a jump operand points at, resolved through the label
9174/// placement table.
9175fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
9176 let id = label_id(operands)?;
9177 state.labels.get(id as usize).copied().flatten()
9178}
9179
9180/// The label an instruction refers to.
9181fn label_id(operands: &[Op]) -> Option<u32> {
9182 operands.iter().find_map(|operand| match operand {
9183 Op::Label(label) => Some(label.0),
9184 _ => None,
9185 })
9186}
9187
9188/// Turn `if_false L; goto M; L:` into `if_true M`.
9189///
9190/// A conditional whose alternate branch is an unconditional jump needs one jump,
9191/// not two. This is the shape `if (c) break;` produces, so folding it removes an
9192/// instruction and a label from every conditional `break`.
9193/// The boolean a constant-push instruction produces, or `None` if it is not one.
9194///
9195/// Only the operators whose truthiness is decided by the opcode are covered; a
9196/// constant that needs the constant pool (a string) is left alone, because reading it
9197/// would mean threading the pool through the peephole for a case the reference also
9198/// skips.
9199fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
9200 match op {
9201 // `push_0` returns -1 for zero, `push_1` 1, and so on.
9202 Opcode::PushMinus1 => Some(true),
9203 Opcode::Push0 => Some(false),
9204 Opcode::Push1
9205 | Opcode::Push2
9206 | Opcode::Push3
9207 | Opcode::Push4
9208 | Opcode::Push5
9209 | Opcode::Push6
9210 | Opcode::Push7 => Some(true),
9211 Opcode::PushTrue => Some(true),
9212 Opcode::PushFalse => Some(false),
9213 Opcode::Undefined | Opcode::Null => Some(false),
9214 Opcode::PushI32 => match operands.first() {
9215 Some(Op::Int(value)) => Some(*value != 0),
9216 _ => None,
9217 },
9218 _ => None,
9219 }
9220}
9221
9222/// Fold a branch on a constant condition.
9223///
9224/// `if (0) a() else b()` must not test anything at run time, and the reference
9225/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
9226/// which is why the bytecode for a `while (1)` loop has no condition at all.
9227///
9228/// Two instructions become one, so the slot the test occupied is left empty rather
9229/// than shifting everything after it: labels have already been resolved to indices.
9230fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>]) {
9231 for index in 0..insns.len() {
9232 let Some((push_op, push_operands)) = insns[index].clone() else {
9233 continue;
9234 };
9235 let Some(truth) = constant_truth(push_op, &push_operands) else {
9236 continue;
9237 };
9238 let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
9239 continue;
9240 };
9241 let (destination, taken) = match branch_op {
9242 Opcode::IfTrue => (branch_operands.first().cloned(), truth),
9243 Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
9244 _ => continue,
9245 };
9246 let Some(destination) = destination else {
9247 continue;
9248 };
9249 insns[index] = if taken {
9250 // The branch is always taken, so it becomes an unconditional jump.
9251 Some((Opcode::Goto, vec![destination]))
9252 } else {
9253 // The branch never runs: both instructions disappear and control falls
9254 // through to what came after.
9255 None
9256 };
9257 insns[index + 1] = None;
9258 }
9259}
9260
9261/// Remove a jump whose destination is the instruction right after it.
9262///
9263/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
9264/// its test into nothing, and the loop-end jump then points at the following
9265/// instruction. The reference drops them, so `stack_size` and the listing agree.
9266fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
9267 for index in 0..insns.len() {
9268 let Some((op, operands)) = insns[index].clone() else {
9269 continue;
9270 };
9271 if !is_goto(op) {
9272 continue;
9273 }
9274 let Some(id) = label_id(&operands) else {
9275 continue;
9276 };
9277 // The next instruction that still exists, which is what "the instruction
9278 // after this jump" means once earlier folds have punched holes.
9279 let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
9280 if placed.get(id as usize).copied().flatten() == next {
9281 insns[index] = None;
9282 }
9283 }
9284}
9285
9286fn fold_conditional_jumps(
9287 insns: &mut [Option<(Opcode, Vec<Op>)>],
9288 label_at: &[Option<u32>],
9289 placed: &[Option<usize>],
9290) {
9291 for index in 0..insns.len() {
9292 let Some((op, operands)) = insns[index].clone() else {
9293 continue;
9294 };
9295 let inverted = match op {
9296 Opcode::IfFalse => Opcode::IfTrue,
9297 Opcode::IfTrue => Opcode::IfFalse,
9298 _ => continue,
9299 };
9300 // Next must be an unconditional jump that is not itself a target, and the
9301 // instruction after it must be exactly where the conditional goes.
9302 let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
9303 continue;
9304 };
9305 if !is_goto(next_op) || is_label_at(label_at, index + 1) {
9306 continue;
9307 }
9308 // The conditional must land on the instruction *after* the jump. Several
9309 // labels can share a position, so this asks where *this* label was put
9310 // rather than what label happens to sit there.
9311 let Some(taken) = label_id(&operands) else {
9312 continue;
9313 };
9314 if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
9315 continue;
9316 }
9317 let Some(destination) = next_operands.first().cloned() else {
9318 continue;
9319 };
9320 insns[index] = Some((inverted, vec![destination]));
9321 insns[index + 1] = None;
9322 }
9323}
9324
9325/// Whether a jump target is placed at this instruction index.
9326fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
9327 label_at.get(index).copied().flatten().is_some()
9328}
9329
9330fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
9331 // `dup put_x(n)` -> `set_x(n)`
9332 // `dup put_x(n) drop` -> `put_x(n)`
9333 // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
9334 for index in 0..insns.len() {
9335 if opcode_at(insns, index) != Some(Opcode::Dup) {
9336 continue;
9337 }
9338 if is_label_at(label_at, index + 1) {
9339 continue;
9340 }
9341 let Some((put_op, put_operands)) = insns[index + 1].clone() else {
9342 continue;
9343 };
9344 if !is_foldable_put(put_op) {
9345 continue;
9346 }
9347 let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
9348 continue;
9349 };
9350 let mut new_op = set_form_of(put_op);
9351 let mut end = index + 2;
9352 if is_label_at(label_at, end) {
9353 // The `put` has to stay as it is; only the `dup` can be folded.
9354 insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
9355 insns[index + 1] = None;
9356 continue;
9357 }
9358 // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
9359 // Deleting it moves the label's target onto whatever follows, and the code that
9360 // jumps there arrives with a different stack than the fall-through path: that is
9361 // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
9362 // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
9363 // an empty stack. The store had already consumed the value it was supposed to
9364 // leave behind.
9365 if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
9366 new_op = put_op;
9367 end += 1;
9368 if opcode_at(insns, end) == Some(get_form_of(put_op))
9369 && !is_label_at(label_at, end)
9370 && insns[end]
9371 .as_ref()
9372 .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
9373 {
9374 new_op = set_form_of(put_op);
9375 end += 1;
9376 }
9377 }
9378 insns[index] = Some((new_op, vec![Op::Slot(slot)]));
9379 for entry in &mut insns[index + 1..end] {
9380 *entry = None;
9381 }
9382 }
9383}
9384
9385fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
9386 insns
9387 .get(index)
9388 .and_then(|entry| entry.as_ref())
9389 .map(|(op, _)| *op)
9390}
9391
9392/// The four `put_` families that have a `set_` twin. Deliberately not including
9393/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
9394/// these, and folding the others would produce instructions that do not exist.
9395fn is_foldable_put(op: Opcode) -> bool {
9396 matches!(
9397 op,
9398 Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
9399 )
9400}
9401
9402fn set_form_of(op: Opcode) -> Opcode {
9403 match op {
9404 Opcode::PutLoc => Opcode::SetLoc,
9405 Opcode::PutLocCheck => Opcode::SetLocCheck,
9406 Opcode::PutArg => Opcode::SetArg,
9407 Opcode::PutVarRef => Opcode::SetVarRef,
9408 other => other,
9409 }
9410}
9411
9412fn get_form_of(op: Opcode) -> Opcode {
9413 match op {
9414 Opcode::PutLoc => Opcode::GetLoc,
9415 Opcode::PutLocCheck => Opcode::GetLocCheck,
9416 Opcode::PutArg => Opcode::GetArg,
9417 Opcode::PutVarRef => Opcode::GetVarRef,
9418 other => other,
9419 }
9420}
9421
9422/// Atom interning, per function.
9423///
9424/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
9425/// identifiers, so the array-index rule applies here rather than at the handful of
9426/// call sites that build property keys.
9427fn intern_atom(state: &mut FnState, name: &str) -> u32 {
9428 intern_atom_value(state, Atom::from_text(name))
9429}
9430
9431/// [`intern_atom`] for an operand that is already an [`Atom`].
9432///
9433/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
9434/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
9435/// would have looked up.
9436fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
9437 if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
9438 return index as u32;
9439 }
9440 state.atoms.push(atom);
9441 state.atoms.len() as u32 - 1
9442}
9443
9444fn binary_opcode(op: BinaryOp) -> Opcode {
9445 match op {
9446 BinaryOp::Add => Opcode::Add,
9447 BinaryOp::Sub => Opcode::Sub,
9448 BinaryOp::Mul => Opcode::Mul,
9449 BinaryOp::Div => Opcode::Div,
9450 BinaryOp::Mod => Opcode::Mod,
9451 BinaryOp::Pow => Opcode::Pow,
9452 BinaryOp::BitOr => Opcode::Or,
9453 BinaryOp::BitXor => Opcode::Xor,
9454 BinaryOp::BitAnd => Opcode::And,
9455 BinaryOp::Shl => Opcode::Shl,
9456 BinaryOp::Shr => Opcode::Sar,
9457 BinaryOp::UShr => Opcode::Shr,
9458 BinaryOp::Lt => Opcode::Lt,
9459 BinaryOp::LtEq => Opcode::Lte,
9460 BinaryOp::Gt => Opcode::Gt,
9461 BinaryOp::GtEq => Opcode::Gte,
9462 BinaryOp::Eq => Opcode::Eq,
9463 BinaryOp::NotEq => Opcode::Neq,
9464 BinaryOp::StrictEq => Opcode::StrictEq,
9465 BinaryOp::StrictNotEq => Opcode::StrictNeq,
9466 BinaryOp::In => Opcode::In,
9467 BinaryOp::Instanceof => Opcode::Instanceof,
9468 }
9469}
9470
9471fn compound_opcode(op: AssignOp) -> Opcode {
9472 match op {
9473 AssignOp::Add => Opcode::Add,
9474 AssignOp::Sub => Opcode::Sub,
9475 AssignOp::Mul => Opcode::Mul,
9476 AssignOp::Div => Opcode::Div,
9477 AssignOp::Mod => Opcode::Mod,
9478 AssignOp::Pow => Opcode::Pow,
9479 AssignOp::Shl => Opcode::Shl,
9480 AssignOp::Shr => Opcode::Sar,
9481 AssignOp::UShr => Opcode::Shr,
9482 AssignOp::BitOr => Opcode::Or,
9483 AssignOp::BitXor => Opcode::Xor,
9484 AssignOp::BitAnd => Opcode::And,
9485 AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
9486 }
9487}
9488
9489/// Encode the resolved instruction stream, choosing short forms where possible.
9490///
9491/// The peephole pass leaves holes in the instruction list so that label indices
9492/// stay valid. A label names an *instruction index*, and an index that was
9493/// deleted has to resolve to the next surviving instruction, which is what
9494/// [`resolve_label`] does before the byte offsets are known.
9495fn assemble(
9496 insns: &mut [Option<(Opcode, Vec<Op>)>],
9497 insn_pos: &[Option<Position>],
9498 state: &mut FnState,
9499) -> (Vec<u8>, u32, Vec<LineCol>) {
9500 // Compaction: surviving instructions in order, plus the index mapping.
9501 //
9502 // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
9503 // point below where instructions are removed — otherwise a stack trace would point
9504 // at the wrong source line as soon as dead-code elimination kicked in.
9505 let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
9506 let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
9507 let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
9508 for (original, entry) in insns.iter_mut().enumerate() {
9509 if let Some((op, operands)) = entry.take() {
9510 original_to_kept[original] = Some(kept.len());
9511 kept.push((op, operands));
9512 spans.push(insn_pos.get(original).copied().flatten());
9513 }
9514 }
9515
9516 if std::env::var_os("QJS_DEBUG").is_some() {
9517 eprintln!("--- assemble entry --- {kept:?}");
9518 }
9519 // How many labels are real, as opposed to the per-instruction ones allocated
9520 // just below. Only a real label marks a spot in the source program.
9521 let real_labels = state.labels.len();
9522
9523 // Give every surviving instruction a label of its own. Jump cleanup below
9524 // redirects jumps to arbitrary instructions, and a jump target has to be a
9525 // label; pre-allocating one per index means a redirect never has to invent
9526 // anything.
9527 let existing = state.labels.len();
9528 let base = kept.len();
9529 let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
9530 for offset in 0..=kept.len() {
9531 state.labels.push(Some(0));
9532 index_label.push(Label((existing + offset) as u32));
9533 }
9534 // Point each pre-allocated label at its instruction, reusing the count from
9535 // `original_to_kept` so the mapping survives compaction.
9536 let place_index_labels = |state: &mut FnState,
9537 original_to_kept: &[Option<usize>],
9538 kept_len: usize,
9539 index_label: &[Label]| {
9540 for (original, mapped) in original_to_kept.iter().enumerate() {
9541 if let Some(kept_index) = mapped {
9542 let label = index_label[*kept_index].0 as usize;
9543 state.labels[label] = Some(original);
9544 }
9545 }
9546 state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
9547 };
9548 place_index_labels(state, &original_to_kept, base, &index_label);
9549
9550 // Resolve every label to a kept index once; the placement table maps labels
9551 // to original indices, so a second hop lands in kept space.
9552 let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
9553 for (id, placed) in state.labels.iter().enumerate() {
9554 let Some(original) = placed else { continue };
9555 label_kept[id] = if *original == usize::MAX {
9556 Some(base)
9557 } else {
9558 (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
9559 };
9560 }
9561
9562 // Code after an unconditional transfer is unreachable, and the reference drops it
9563 // as it walks past the transfer — the `skip_dead_code` in its first pass. It
9564 // scans forward until it finds a label something still jumps to, so a run of
9565 // dead instructions between a `throw` and the next live target disappears.
9566 //
9567 // The scan repeats because dropping a jump lowers the reference count of the
9568 // label it pointed at, which can strand what follows. Only a real label keeps an
9569 // instruction alive here; the per-instruction labels allocated above belong to
9570 // this pass, not to the program.
9571 loop {
9572 let mut references = vec![false; kept.len() + 1];
9573 for (_, operands) in &kept {
9574 if let Some(target) = target_kept_index(operands, &label_kept)
9575 && target < references.len()
9576 {
9577 references[target] = true;
9578 }
9579 }
9580 let mut doomed = vec![false; kept.len()];
9581 let mut any = false;
9582 for (index, (op, _)) in kept.iter().enumerate() {
9583 if !is_transfer(*op) {
9584 continue;
9585 }
9586 for next in index + 1..kept.len() {
9587 if references[next] {
9588 break;
9589 }
9590 doomed[next] = true;
9591 any = true;
9592 }
9593 }
9594 if !any {
9595 break;
9596 }
9597 (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
9598 }
9599
9600 // A label that lands on an unconditional jump stands for wherever that jump
9601 // goes, so retarget it once and every jump to the label follows for free.
9602 // This is what makes `continue` in a `for` head reach the loop top instead of
9603 // stopping at the update's trailing jump.
9604 let folded: Vec<Option<usize>> = label_kept
9605 .iter()
9606 .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
9607 .collect();
9608 label_kept = folded;
9609
9610 // Jump cleanup, in compacted index space. Two rewrites the reference also
9611 // applies while it resolves labels:
9612 // * a jump whose destination is the very next instruction does nothing;
9613 // * a jump to a jump is redirected to its final destination.
9614 // The second can expose the first, so this repeats until it settles.
9615 loop {
9616 let mut delete = vec![false; kept.len()];
9617 let mut changed = false;
9618 for index in 0..kept.len() {
9619 let (op, operands) = &kept[index];
9620 if !is_goto(*op) {
9621 continue;
9622 }
9623 let Some(immediate) = target_kept_index(operands, &label_kept) else {
9624 continue;
9625 };
9626 let target = follow_jump_chain(&kept, &label_kept, immediate);
9627 if target == index + 1 {
9628 delete[index] = true;
9629 changed = true;
9630 } else if matches!(
9631 kept.get(target).map(|(op, _)| *op),
9632 Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
9633 ) {
9634 // Jumping straight to a return or throw is the same as doing it
9635 // here, so the jump becomes that instruction.
9636 kept[index] = (kept[target].0, Vec::new());
9637 changed = true;
9638 } else if target != immediate {
9639 // Redirect to the end of the chain.
9640 let label = index_label[target];
9641 kept[index].1 = vec![Op::Label(label)];
9642 changed = true;
9643 }
9644 }
9645 if !changed {
9646 break;
9647 }
9648 if !delete.iter().any(|deleted| *deleted) {
9649 break;
9650 }
9651 // Drop the deleted instructions and renumber everything.
9652 let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9653 let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9654 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9655 for (old, entry) in kept.into_iter().enumerate() {
9656 if delete[old] {
9657 continue;
9658 }
9659 moved[old] = Some(next.len());
9660 next.push(entry);
9661 next_spans.push(spans[old]);
9662 }
9663 for (id, slot) in label_kept.iter_mut().enumerate() {
9664 let Some(old) = *slot else { continue };
9665 *slot = match moved.get(old).copied().flatten() {
9666 Some(new) => Some(new),
9667 // The target was deleted: the jump now lands on whatever follows.
9668 None => (old..moved.len())
9669 .find_map(|i| moved[i])
9670 .or(Some(next.len())),
9671 };
9672 let _ = id;
9673 }
9674 kept = next;
9675 spans = next_spans;
9676 }
9677
9678 // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
9679 // jump to the next instruction and is deleted, leaving the label at the end with
9680 // nothing pointing at it. If that also strands the last instruction, it goes
9681 // too — which is how a `try` whose body always returns ends on its `ret` rather
9682 // than an implicit `return_undef`.
9683 // Which instructions something still jumps to. Reading the surviving jumps is
9684 // what the reference's reference counts amount to: once a jump has been folded
9685 // away the label it named is unreferenced, even though the program still has a
9686 // label there.
9687 let mut references = vec![false; kept.len() + 1];
9688 let _ = real_labels;
9689 for (_, operands) in &kept {
9690 if let Some(target) = target_kept_index(operands, &label_kept)
9691 && target < references.len()
9692 {
9693 references[target] = true;
9694 }
9695 }
9696 let mut end = kept.len();
9697 while end > 0 {
9698 let last = end - 1;
9699 let reachable = references[last] || end < kept.len();
9700 if reachable {
9701 break;
9702 }
9703 let after_transfer = last
9704 .checked_sub(1)
9705 .map(|previous| {
9706 matches!(
9707 kept[previous].0,
9708 Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
9709 )
9710 })
9711 .unwrap_or(false);
9712 if !after_transfer {
9713 break;
9714 }
9715 end = last;
9716 }
9717 kept.truncate(end);
9718 spans.truncate(end);
9719
9720 // Choose an opcode for each instruction and its size, so label offsets can be
9721 // computed.
9722 let chosen = choose_opcodes(&kept, &label_kept);
9723 let offsets = instruction_offsets(&chosen);
9724 let offset = *offsets.last().unwrap_or(&0);
9725
9726 let mut code = Vec::with_capacity(offset);
9727 for (position, (_, operands)) in kept.iter().enumerate() {
9728 let op = chosen[position];
9729 code.push(op as u8);
9730 let operands = retarget_labels(operands, &label_kept, kept.len());
9731 encode_operands(&mut code, op, &operands, offsets[position], &offsets);
9732 }
9733 let stack_size = compute_stack_size(&code);
9734 // Keep only the offsets where the position actually changes: a run of
9735 // instructions on one line is one table entry, and the runtime binary searches
9736 // the table for the frame's pc.
9737 //
9738 // The table always starts at pc 0 with the *function's own* position, because the
9739 // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
9740 // last_line_num)` from `fd->source_pos`, the token the function definition starts at
9741 // (`function`, `async`, a method's property name). An instruction before the first
9742 // recorded operator therefore reports the function's own start, which is what makes a
9743 // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
9744 let mut positions: Vec<LineCol> = vec![LineCol {
9745 pc: 0,
9746 line: state.line,
9747 column: state.column,
9748 }];
9749 let mut last: Option<Position> = None;
9750 for (index, span) in spans.iter().enumerate() {
9751 let Some(pos) = *span else { continue };
9752 if last == Some(pos) {
9753 continue;
9754 }
9755 last = Some(pos);
9756 if pos.line == state.line && pos.column == state.column {
9757 // Already the seed entry above.
9758 continue;
9759 }
9760 positions.push(LineCol {
9761 pc: offsets[index] as u32,
9762 line: pos.line,
9763 column: pos.column,
9764 });
9765 }
9766 (code, stack_size, positions)
9767}
9768
9769/// Whether an instruction always transfers control away, so anything after it in the
9770/// same stream is unreachable.
9771fn is_transfer(op: Opcode) -> bool {
9772 matches!(
9773 op,
9774 Opcode::Goto
9775 | Opcode::Goto8
9776 | Opcode::Goto16
9777 | Opcode::Return
9778 | Opcode::ReturnUndef
9779 | Opcode::Throw
9780 | Opcode::ThrowError
9781 | Opcode::Ret
9782 )
9783}
9784
9785/// Remove the marked instructions and renumber the label table so it keeps pointing
9786/// at the same instructions. A label whose instruction went away moves to whatever
9787/// follows it, since a jump is never left with nowhere to land.
9788fn drop_instructions(
9789 kept: Vec<(Opcode, Vec<Op>)>,
9790 spans: Vec<Option<Position>>,
9791 label_kept: &mut [Option<usize>],
9792 doomed: &[bool],
9793) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
9794 let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9795 let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9796 let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9797 for (old, entry) in kept.into_iter().enumerate() {
9798 if doomed.get(old).copied().unwrap_or(false) {
9799 continue;
9800 }
9801 moved[old] = Some(result.len());
9802 result.push(entry);
9803 result_spans.push(spans[old]);
9804 }
9805 for slot in label_kept.iter_mut() {
9806 let Some(old) = *slot else { continue };
9807 *slot = match moved.get(old).copied().flatten() {
9808 Some(new) => Some(new),
9809 None => (old..moved.len())
9810 .find_map(|i| moved[i])
9811 .or(Some(result.len())),
9812 };
9813 }
9814 (result, result_spans)
9815}
9816
9817fn is_goto(op: Opcode) -> bool {
9818 matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
9819}
9820
9821/// The kept index a jump operand points at.
9822fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
9823 let id = label_id(operands)?;
9824 label_kept.get(id as usize).copied().flatten()
9825}
9826
9827/// Follow a chain of unconditional jumps to its first real destination.
9828fn follow_jump_chain(
9829 kept: &[(Opcode, Vec<Op>)],
9830 label_kept: &[Option<usize>],
9831 start: usize,
9832) -> usize {
9833 let mut current = start;
9834 // `for(;;)` jumps to itself, so the walk has to be bounded.
9835 for _ in 0..kept.len() {
9836 let Some((op, operands)) = kept.get(current) else {
9837 return current;
9838 };
9839 if !is_goto(*op) {
9840 return current;
9841 }
9842 let Some(next) = target_kept_index(operands, label_kept) else {
9843 return current;
9844 };
9845 if next == current {
9846 return current;
9847 }
9848 current = next;
9849 }
9850 current
9851}
9852
9853/// Rewrite label operands from label ids to kept instruction indices.
9854fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
9855 operands
9856 .iter()
9857 .map(|operand| match operand {
9858 Op::Label(label) => {
9859 let target = label_kept
9860 .get(label.0 as usize)
9861 .copied()
9862 .flatten()
9863 .unwrap_or(kept_len);
9864 Op::Label(Label(target as u32))
9865 }
9866 other => other.clone(),
9867 })
9868 .collect()
9869}
9870
9871/// Encode the resolved instruction stream, choosing short forms where possible.
9872///
9873/// Compute the maximum value-stack depth by exploring the control-flow graph.
9874///
9875/// This is a breadth-first walk from the first instruction, tracking the stack
9876/// depth on entry to each instruction. Every instruction has at most two
9877/// successors (fall through, and a jump target), so a worklist over byte offsets
9878/// is enough. The reference does the same thing in `compute_stack_size`, which is
9879/// why the resulting numbers match exactly.
9880///
9881/// Instructions that pop a variable number of values (`call`, `array_from`, …)
9882/// encode that count in their operand, which is added to the static `n_pop`.
9883fn compute_stack_size(code: &[u8]) -> u32 {
9884 let mut depth_at = vec![u16::MAX; code.len()];
9885 // Each entry carries the enclosing `catch` levels, innermost last, because
9886 // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
9887 // offset and forgets that level.
9888 let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
9889 let mut max_depth = 0u32;
9890
9891 while let Some((pc, depth, catch_levels)) = worklist.pop() {
9892 if pc >= code.len() {
9893 continue;
9894 }
9895 if depth_at[pc] != u16::MAX {
9896 continue;
9897 }
9898 force_depth(&mut depth_at, pc, depth);
9899
9900 let Some(op) = Opcode::from_u8(code[pc]) else {
9901 break;
9902 };
9903 let info = op.info();
9904 let next = pc + info.size as usize;
9905 if next > code.len() {
9906 break;
9907 }
9908 let mut n_pop = info.n_pop as u32;
9909 let mut n_push = info.n_push as u32;
9910 // Variable-length forms carry their count in the operand.
9911 match info.format {
9912 crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
9913 n_pop += read_u16(code, pc + 1) as u32;
9914 }
9915 crate::opcode::OpFormat::Npopx => {
9916 n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
9917 }
9918 _ => {}
9919 }
9920 // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
9921 // are the `set_` variant; the table already records that, so nothing to
9922 // adjust here.
9923 let _ = &mut n_push;
9924
9925 // The depth before this instruction's own push, which is what a `catch`
9926 // records as its level.
9927 let depth_before = depth;
9928 let mut depth = depth.saturating_sub(n_pop) + n_push;
9929 let mut catch_levels = catch_levels;
9930 if op == Opcode::NipCatch {
9931 // Discard everything above the innermost catch offset, keeping the value
9932 // on top: the frame the code after this sees is the same shape it would
9933 // have had if the `try` were not there.
9934 if let Some(base) = catch_levels.pop() {
9935 depth = base + 1;
9936 }
9937 }
9938 max_depth = max_depth.max(depth);
9939
9940 // Successors.
9941 let target = jump_target_of(code, pc, op);
9942 match op {
9943 Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9944 if let Some(target) = target {
9945 worklist.push((target, depth, catch_levels));
9946 }
9947 }
9948 Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
9949 if let Some(target) = target {
9950 worklist.push((target, depth, catch_levels.clone()));
9951 }
9952 worklist.push((next, depth, catch_levels));
9953 }
9954 // A `catch` records an exception edge to the handler. The handler is
9955 // entered with the thrown value on top of the stack, in the slot the
9956 // catch offset occupies on the normal path — which is why the handler's
9957 // first instruction can `put_loc` the exception away, and why the depth
9958 // is the same on both paths.
9959 Opcode::Catch => {
9960 if let Some(target) = target {
9961 // The handler is protected by the *enclosing* catch, not by this
9962 // one: an error raised inside it is what the handler's own
9963 // `catch` catches.
9964 worklist.push((target, depth, catch_levels.clone()));
9965 }
9966 catch_levels.push(depth_before);
9967 worklist.push((next, depth, catch_levels));
9968 }
9969 // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
9970 // rewind past it too. Its level sits one slot higher than a `catch`'s:
9971 // the iterator and next-method slots occupy the offset's place.
9972 Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
9973 if let Some(target) = target {
9974 worklist.push((target, depth, catch_levels.clone()));
9975 }
9976 catch_levels.push(depth_before + 1);
9977 worklist.push((next, depth, catch_levels));
9978 }
9979 // `gosub` calls a subroutine with the return address on top. The opcode
9980 // table records no push for it — `ret` is what pops the slot — so the
9981 // extra one is added here, where the depth of the subroutine's first
9982 // instruction is being computed.
9983 Opcode::Gosub => {
9984 if let Some(target) = target {
9985 worklist.push((target, depth + 1, catch_levels.clone()));
9986 }
9987 worklist.push((next, depth, catch_levels));
9988 }
9989 // `ret` goes back to a `gosub`; nothing here follows it.
9990 Opcode::Ret
9991 | Opcode::Return
9992 | Opcode::ReturnUndef
9993 | Opcode::Throw
9994 | Opcode::ThrowError => {}
9995 _ => worklist.push((next, depth, catch_levels)),
9996 }
9997 }
9998 max_depth
9999}
10000
10001/// Record the stack depth on entry to `pc`, keeping the deeper value if the
10002/// instruction is reachable more than once.
10003fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
10004 let clamped = depth.min(u16::MAX as u32 - 1) as u16;
10005 if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
10006 depth_at[pc] = clamped;
10007 }
10008}
10009
10010fn read_u16(code: &[u8], at: usize) -> u16 {
10011 let mut value = 0u16;
10012 for i in 0..2 {
10013 value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
10014 }
10015 value
10016}
10017
10018/// The absolute target of a jump instruction, if it has one.
10019fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
10020 let info = op.info();
10021 let position = pc + 1;
10022 match info.format {
10023 crate::opcode::OpFormat::Label8 => {
10024 let offset = *code.get(position)? as i8 as i64;
10025 Some((position as i64 + offset) as usize)
10026 }
10027 crate::opcode::OpFormat::Label16 => {
10028 let offset = read_u16(code, position) as i16 as i64;
10029 Some((position as i64 + offset) as usize)
10030 }
10031 crate::opcode::OpFormat::Label => {
10032 let mut offset = 0i32;
10033 for i in 0..4 {
10034 offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
10035 }
10036 Some((position as i64 + offset as i64) as usize)
10037 }
10038 _ => None,
10039 }
10040}
10041
10042fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
10043 use Opcode::*;
10044 match (op, operands.first()) {
10045 (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
10046 op.short_form(*value as u32).unwrap_or(op)
10047 }
10048 (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
10049 (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
10050 (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
10051 | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
10052 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
10053 // A declared global is reached through its reference cell, so it shares
10054 // the `var_ref` encodings, short forms included.
10055 | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
10056 op.short_form(*index).unwrap_or(op)
10057 }
10058 (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
10059 op.short_form(*count as u32).unwrap_or(op)
10060 }
10061 _ => op,
10062 }
10063}
10064
10065/// The byte offset each instruction will start at, plus the total code size.
10066fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
10067 let mut offsets = Vec::with_capacity(chosen.len() + 1);
10068 let mut offset = 0usize;
10069 for op in chosen {
10070 offsets.push(offset);
10071 offset += op.size() as usize;
10072 }
10073 offsets.push(offset);
10074 offsets
10075}
10076
10077/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
10078/// the offset actually fits.
10079///
10080/// The choice is circular: an instruction's size decides the offsets of everything after
10081/// it, and the offsets decide whether a jump may be short. So this starts with every jump
10082/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
10083/// Shrinking only ever *shortens* distances, so the loop converges.
10084///
10085/// Doing it in one pass instead — which is what this used to do — silently truncated any
10086/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
10087/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
10088/// with four closures in its body simply stopped, with no error and no output past the
10089/// first iteration.
10090fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
10091 let mut chosen: Vec<Opcode> = kept
10092 .iter()
10093 .map(|(op, operands)| choose_short_form(*op, operands))
10094 .collect();
10095 // A jump the compiler emitted in its widest form, and the forms it may shrink to.
10096 let candidates = |op: Opcode| match op {
10097 Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
10098 Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
10099 Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
10100 _ => None,
10101 };
10102 loop {
10103 let offsets = instruction_offsets(&chosen);
10104 let mut changed = false;
10105 for index in 0..kept.len() {
10106 let (op, operands) = &kept[index];
10107 let Some((short, medium, has_medium)) = candidates(*op) else {
10108 continue;
10109 };
10110 if chosen[index] == short {
10111 continue;
10112 }
10113 let Some(target) = target_kept_index(operands, label_kept) else {
10114 continue;
10115 };
10116 let Some(&target_offset) = offsets.get(target) else {
10117 continue;
10118 };
10119 // A jump is relative to the byte after its opcode, which is the convention
10120 // `jump_target_of` decodes with.
10121 let relative = target_offset as i64 - (offsets[index] as i64 + 1);
10122 if (-128..=127).contains(&relative) {
10123 chosen[index] = short;
10124 changed = true;
10125 } else if has_medium
10126 && chosen[index] == Opcode::Goto
10127 && (-32_768..=32_767).contains(&relative)
10128 {
10129 // Too far for 8 bits and close enough for 16. Only `goto` has a medium
10130 // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
10131 // the reference encodes them.
10132 chosen[index] = medium;
10133 changed = true;
10134 }
10135 }
10136 if !changed {
10137 return chosen;
10138 }
10139 }
10140}
10141
10142fn encode_operands(
10143 code: &mut Vec<u8>,
10144 op: Opcode,
10145 operands: &[Op],
10146 position: usize,
10147 offsets: &[usize],
10148) {
10149 use crate::opcode::OpFormat::*;
10150 let info = op.info();
10151 let write_slot = |code: &mut Vec<u8>, slot: Slot| {
10152 let index = match slot {
10153 Slot::Arg(i)
10154 | Slot::Loc(i)
10155 | Slot::VarRef(i)
10156 | Slot::Global(i)
10157 | Slot::GlobalDecl(i) => i,
10158 };
10159 code.extend_from_slice(&(index as u16).to_be_bytes());
10160 };
10161 match info.format {
10162 None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
10163 U8 | Const8 => {
10164 if let Some(value) = operands.first().and_then(operand_uint) {
10165 code.push(value as u8);
10166 }
10167 }
10168 // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
10169 // like their wide counterparts, only one byte wide.
10170 Loc8 => {
10171 if let Some(Op::Slot(slot)) = operands.first() {
10172 let index = match slot {
10173 Slot::Arg(i)
10174 | Slot::Loc(i)
10175 | Slot::VarRef(i)
10176 | Slot::Global(i)
10177 | Slot::GlobalDecl(i) => *i,
10178 };
10179 code.push(index as u8);
10180 }
10181 }
10182 I8 => {
10183 if let Some(value) = operands.first().and_then(operand_int) {
10184 code.push(value as i8 as u8);
10185 }
10186 }
10187 U16 | Npop => {
10188 if let Some(value) = operands.first().and_then(operand_int) {
10189 code.extend_from_slice(&(value as u16).to_be_bytes());
10190 }
10191 }
10192 I16 => {
10193 if let Some(value) = operands.first().and_then(operand_int) {
10194 code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
10195 }
10196 }
10197 I32 => {
10198 if let Some(value) = operands.first().and_then(operand_int) {
10199 code.extend_from_slice(&value.to_be_bytes());
10200 }
10201 }
10202 U32 | Const => {
10203 if let Some(value) = operands.first().and_then(operand_uint) {
10204 code.extend_from_slice(&value.to_be_bytes());
10205 }
10206 }
10207 Loc | Arg | VarRef => {
10208 if let Some(Op::Slot(slot)) = operands.first() {
10209 write_slot(code, *slot);
10210 }
10211 }
10212 Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
10213 if let Some(Op::AtomId(index)) = operands.first() {
10214 code.extend_from_slice(&index.to_be_bytes());
10215 }
10216 // The trailing immediate means different things per format, and the
10217 // atom forms that carry a *label* have to resolve it like any other
10218 // jump, so they cannot share the `U8`/`U16` arms above.
10219 match info.format {
10220 AtomU8 | AtomLabelU8 => {
10221 if let Some(value) = operands.get(1).and_then(operand_uint) {
10222 code.push(value as u8);
10223 }
10224 }
10225 AtomU16 | AtomLabelU16 => {
10226 if let Some(value) = operands.get(1).and_then(operand_uint) {
10227 code.extend_from_slice(&(value as u16).to_be_bytes());
10228 }
10229 }
10230 _ => {}
10231 }
10232 }
10233 NpopU16 => {
10234 for operand in operands.iter().take(2) {
10235 if let Some(value) = operand_uint(operand) {
10236 code.extend_from_slice(&(value as u16).to_be_bytes());
10237 }
10238 }
10239 }
10240 Label | Label8 | Label16 | LabelU16 => {
10241 if let Some(Op::Label(label)) = operands.first() {
10242 // Labels were already remapped to kept-instruction indices.
10243 let Some(&target) = offsets.get(label.0 as usize) else {
10244 debug_assert!(false, "label {} is past the end", label.0);
10245 return;
10246 };
10247 let relative = target as i64 - (position as i64 + 1);
10248 match info.format {
10249 Label8 => code.push(relative as i8 as u8),
10250 Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
10251 // `label_u16` stores the target followed by an unrelated u16.
10252 LabelU16 => {
10253 code.extend_from_slice(&(relative as i32).to_be_bytes());
10254 if let Some(value) = operands.get(1).and_then(operand_uint) {
10255 code.extend_from_slice(&(value as u16).to_be_bytes());
10256 }
10257 }
10258 _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
10259 }
10260 }
10261 }
10262 }
10263}
10264
10265fn operand_int(op: &Op) -> Option<i32> {
10266 match op {
10267 Op::Int(value) => Some(*value),
10268 _ => None,
10269 }
10270}
10271
10272fn operand_uint(op: &Op) -> Option<u32> {
10273 match op {
10274 Op::Const(value) | Op::AtomId(value) => Some(*value),
10275 Op::Int(value) => Some(*value as u32),
10276 _ => None,
10277 }
10278}
10279
10280/// Disassemble a compiled function.
10281pub fn disassemble(function: &CompiledFunction) -> String {
10282 disasm::disassemble_program(function)
10283}
10284
10285/// How many of an object pattern's keys are computed.
10286///
10287/// Only the count matters: a rest element needs a run-time key log exactly when at least one
10288/// key is not a literal, and the log is sized by walking the pattern anyway.
10289fn computed_key_count(properties: &[Option<PatternElement>]) -> usize {
10290 properties
10291 .iter()
10292 .flatten()
10293 .filter(|element| {
10294 matches!(
10295 element,
10296 PatternElement::Property {
10297 key: PropName::Computed(_),
10298 ..
10299 }
10300 )
10301 })
10302 .count()
10303}