Skip to main content

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, EvalSite, EvalVisible, ExportEntry,
27    Function as CompiledFunction, FunctionKind, ImportEntry, ModuleMeta, ModuleRequest, VarDef,
28    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    name: String,
467    kind: FunctionKind,
468    strict: bool,
469    args: Vec<VarDef>,
470    vars: Vec<VarDef>,
471    closure_vars: Vec<ClosureVar>,
472    cpool: Vec<Constant>,
473    atoms: Vec<Atom>,
474    /// Every lexical scope, in creation order.
475    blocks: Vec<Block>,
476    /// The block currently being parsed or compiled.
477    current_block: u64,
478    /// The block a *nested* function was created in, so a capture made from here can be
479    /// resolved against the enclosing function's lexical scopes rather than against a
480    /// flat name table. Without it, `function f(){ class S{} }` capturing `S` found the
481    /// function's own `let S` instead of the class body's `const S`.
482    created_in_block: u64,
483    /// The block each local was declared in, parallel to `vars`. `0` means the
484    /// function scope, where `var` bindings live.
485    var_block: Vec<u64>,
486    /// Set when the expression just compiled left no value on the stack.
487    ///
488    /// Only a store can do that: `put_field` consumes the object and the value, so
489    /// an assignment whose result is unused emits nothing extra. The expression
490    /// statement then has nothing to drop.
491    no_value: bool,
492    /// Whether a label was placed since the last instruction was emitted.
493    ///
494    /// The `put`/`get` fold is only valid when the two are adjacent in the final
495    /// stream; a label in between means a jump can land on the read, so the store has
496    /// to keep consuming its value. A flag is enough and avoids having to reason about
497    /// which index a label recorded.
498    label_since_insn: bool,
499    /// Whether the value of the expression being compiled is thrown away.
500    ///
501    /// Only an expression *statement* discards its value, and only the outermost
502    /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
503    /// still has to produce a value. Consumed by [`Compiler::assign`], which is
504    /// the one construct whose bytecode depends on it.
505    discard_value: bool,
506    /// The block that holds the function body.
507    body_block: u64,
508    /// Head of each scope's binding chain, indexed by level. Filled in by
509    /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
510    block_heads: Vec<i32>,
511    /// Enclosing `break`/`continue` targets, innermost last.
512    jump_targets: Vec<JumpTarget>,
513    insns: Vec<Insn>,
514    labels: Vec<Option<usize>>,
515    /// Captured locals, which need a reference cell.
516    var_ref_count: u32,
517    line: u32,
518    column: u32,
519    /// Whether this is a script body. A script's top-level declarations create
520    /// global properties rather than locals, which is why they show up as
521    /// closure variables with `[global_decl]`.
522    is_script: bool,
523    /// Whether this is a module body.
524    ///
525    /// A module body is a script in every respect that matters here — no `arguments`,
526    /// no `this` of its own — but its top-level declarations are *module*-scoped
527    /// instead of global, which is what this flag changes.
528    is_module: bool,
529    /// Whether the function is an arrow, which never gets its own `arguments`.
530    is_arrow: bool,
531    /// The name a *named function expression* binds inside its own body.
532    /// How many parameters count towards `.length`.
533    defined_args: u32,
534    /// Parameters that are not a plain name, with the argument slot each came from.
535    param_prologue: Vec<(usize, Pattern)>,
536    /// What kind of class constructor this function is, if any.
537    ctor_kind: CtorKind,
538    /// Whether the class has instance fields, so the constructor has to run their
539    /// initialiser before it returns.
540    /// What the nested function about to be compiled should be told about its class.
541    class_ctor_pending: Option<CtorKind>,
542    /// Whether this function needs the hidden `this` local, because an arrow inside it
543    /// refers to `this`.
544    ///
545    /// An arrow has no `this` of its own, so the reference materialises the enclosing
546    /// function's receiver into a local and lets the arrow capture it as an ordinary
547    /// closure variable. Declaring the local is not enough on its own: the store that
548    /// fills it has to be prepended to the body, which is what this flag arranges.
549    needs_this_local: bool,
550    /// The same, for `arguments`.
551    needs_arguments_local: bool,
552    /// The same, for `new.target`.
553    needs_new_target_local: bool,
554    /// Whether the body already opens by filling a `this` local, which
555    /// [`Compiler::begin_this_local`] does for a constructor and a field initialiser.
556    has_this_prologue: bool,
557    /// The same, for `<home_object>`: the object `super` resolves against.
558    ///
559    /// An arrow and a static block have no home object of their own — only the method or
560    /// initialiser they were written in does — so `super.x` inside one is a read of the
561    /// enclosing function's `[[HomeObject]]`. The value is materialised into a local there
562    /// by `special_object 4`, the same way `this` is.
563    needs_home_object_local: bool,
564    /// The same, for `this.active_func`: the function `super()` constructs from.
565    ///
566    /// An arrow has no `super` of its own, so it reads the enclosing function's — and that
567    /// is a *lexical* relationship, not a stack one. The reference keeps `this_active_func`
568    /// as a local of the enclosing function; an arrow that escaped the constructor
569    /// (`iter.return = () => super()`) then finds it in its closure even with the
570    /// constructor nowhere on the call stack.
571    needs_active_func_local: bool,
572    /// Hidden locals of the `with` blocks currently open, innermost last.
573    with_names: Vec<String>,
574    /// Set while a with-guard is being emitted, so the guard's own accesses are not
575    /// wrapped in another guard.
576    emitting_with_guard: bool,
577    self_name: Option<String>,
578    /// Where the function body starts, in source order; see [`Function::body_start`].
579    body_start: (u32, u32),
580    /// Whether the body contains a *direct* `eval(...)` call.
581    ///
582    /// A direct eval sees every binding of the function that called it, including ones
583    /// no other code mentions. It also hands those bindings to any closure it creates,
584    /// which can outlive the function. Both need the bindings to live in cells, so this
585    /// flag makes the function treat all of them as captured.
586    has_direct_eval: bool,
587    /// Whether the parameter list contains a default expression, which is what gives
588    /// the function a second variable environment (see [`PARAM_SCOPE`]).
589    has_parameter_expressions: bool,
590    /// Whether the instructions being emitted belong to the parameter list.
591    ///
592    /// References made here must not see the body's `var`s: the body has not run yet,
593    /// and the reference's own model keeps the two scopes apart.
594    in_params: bool,
595    /// Whether an arrow created in this function's parameter list needs the parameter
596    /// scope's `arguments` binding.
597    needs_param_arguments: bool,
598    /// Whether this function was *created* inside a parameter list.
599    ///
600    /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
601    /// arrow too. The name reference is the arrow's, but the scope it must not see
602    /// belongs to the function the arrow was born in.
603    created_in_params: bool,
604    /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
605    ///
606    /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
607    /// final while the body is still being compiled: a named function expression declares
608    /// its own name binding *after* the body, and that binding is exactly what
609    /// `eval("myfunc = 1")` has to find.
610    eval_sites: Vec<EvalSite>,
611    /// Direct `eval` call sites seen so far: where, and the block that was current.
612    pending_eval_sites: Vec<(Span, u64, bool)>,
613    /// Whether this body contains `await`.
614    ///
615    /// For a *module* this decides whether its body is an async function: top-level
616    /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
617    /// to survive to the compiled function rather than being a local of the compiler.
618    has_await: bool,
619    /// The module tables, when this body is a module.
620    ///
621    /// Only the top-level state ever has one: `export` and `import` are top-level
622    /// statements, so nothing nested can add to these tables.
623    module: Option<ModuleMeta>,
624    /// Whether the self-name prologue (`special_object 2` then the store) has been
625    /// emitted for this function.
626    ///
627    /// A *nested* function's lookup declares the binding early (see
628    /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
629    /// prologue is still needed — the binding existing is not the same as it being
630    /// initialised.
631    self_name_initialized: bool,
632    /// Whether the code emitted so far leaves the program's result on the stack.
633    /// The reference tracks this for the hidden `<ret>` local of an eval script.
634    leaves_value: bool,
635    /// Statement nesting depth, used to tell top-level statements apart.
636    stmt_depth: u32,
637    /// Function declarations waiting to be instantiated at scope entry, as
638    /// (target slot, constant pool index). The reference emits these from
639    /// `instantiate_hoisted_definitions` rather than at the statement, because a
640    /// declaration is visible before it is reached.
641    hoisted: Vec<(u64, HoistTarget, u32)>,
642    /// Function declarations whose bodies are compiled only once the enclosing scope
643    /// has finished hoisting, as (owning block, declaration).
644    ///
645    /// Compiling a body at the declaration makes the result depend on source order: in
646    /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
647    /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
648    /// names first and the bodies second is what removes that dependence.
649    deferred_funcs: Vec<(u64, Box<ast::Function>)>,
650    /// The source position of the node being compiled. Every instruction emitted
651    /// takes it, which is how the position table that feeds stack traces is built.
652    cur_pos: Option<Position>,
653    /// One position per entry in `insns`, index-aligned.
654    insn_pos: Vec<Option<Position>>,
655}
656
657/// Where a hoisted function declaration is stored.
658#[derive(Debug, Clone)]
659enum HoistTarget {
660    Arg(u32),
661    Loc(u32),
662    /// A global, which the resolver looks up by name.
663    Global(String),
664}
665
666impl FnState {
667    /// Whether this function suspends: a generator or an async function.
668    ///
669    /// A suspending function's `return` is a `return_async` and its body starts with an
670    /// `initial_yield`, so almost every statement that touches control flow asks this.
671    fn is_suspending(&self) -> bool {
672        self.kind.is_generator() || self.kind.is_async()
673    }
674
675    fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
676        FnState {
677            name: name.into(),
678            kind,
679            strict: false,
680            args: Vec::new(),
681            vars: Vec::new(),
682            closure_vars: Vec::new(),
683            cpool: Vec::new(),
684            atoms: Vec::new(),
685            blocks: Vec::new(),
686            current_block: 0,
687            created_in_block: NO_PARENT,
688            var_block: Vec::new(),
689            no_value: false,
690            label_since_insn: false,
691            discard_value: false,
692            body_block: 0,
693            block_heads: Vec::new(),
694            jump_targets: Vec::new(),
695            insns: Vec::new(),
696            labels: Vec::new(),
697            var_ref_count: 0,
698            line: 1,
699            column: 1,
700            is_script: false,
701            is_module: false,
702            is_arrow: false,
703            defined_args: 0,
704            param_prologue: Vec::new(),
705            ctor_kind: CtorKind::None,
706            class_ctor_pending: None,
707            needs_this_local: false,
708            needs_arguments_local: false,
709            needs_new_target_local: false,
710            has_this_prologue: false,
711            needs_home_object_local: false,
712            needs_active_func_local: false,
713            with_names: Vec::new(),
714            emitting_with_guard: false,
715            self_name: None,
716            has_direct_eval: false,
717            body_start: (0, 0),
718            has_parameter_expressions: false,
719            in_params: false,
720            needs_param_arguments: false,
721            created_in_params: false,
722            eval_sites: Vec::new(),
723            pending_eval_sites: Vec::new(),
724            has_await: false,
725            module: None,
726            self_name_initialized: false,
727            leaves_value: false,
728            stmt_depth: 0,
729            hoisted: Vec::new(),
730            deferred_funcs: Vec::new(),
731            cur_pos: None,
732            insn_pos: Vec::new(),
733        }
734    }
735
736    /// The scope a declaration lands in: a script's top-level declarations are
737    /// globals, everything else gets a slot.
738    /// Whether a binding declared *now* becomes a property of the global object.
739    ///
740    /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
741    /// The `var` case is decided by the keyword rather than by the cursor position:
742    /// `var` is function-scoped, so a `var i` in a `for` head is still the same
743    /// binding as a `var i` in the body, even though the head has its own block.
744    fn declares_globally(&self, def: &VarDef) -> bool {
745        // A module's top-level declarations are *module*-scoped: they live in the module
746        // record, never on the global object. Two modules can both declare `var x`
747        // without seeing each other, which is the whole point.
748        if self.is_module {
749            return false;
750        }
751        self.is_script && (!def.is_lexical || self.current_block == self.body_block)
752    }
753}
754
755/// The compiler's entry point.
756pub struct Compiler {
757    module: bool,
758    /// Whether the program itself is the body of an `async` function.
759    ///
760    /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
761    /// completion value is wrapped so a returned promise is not adopted.
762    async_body: bool,
763    /// Enclosing functions, outermost first. The last entry is the current one.
764    stack: Vec<FnState>,
765    /// The private names visible at this point, innermost class body last.
766    ///
767    /// A stack rather than a field of `FnState` because a private name is *lexically* scoped
768    /// to the class body: a method, an arrow inside it and a class nested inside that arrow
769    /// all resolve against the same entries, and the parser accepts exactly that set
770    /// (`self.private` in `parser.rs`). `FnState` is per-function, so it would lose the outer
771    /// class's names the moment a method started.
772    private_scopes: Vec<std::collections::HashMap<String, PrivateUse>>,
773}
774
775/// How a use site of a private name compiles.
776///
777/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
778/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
779/// of a setter-only accessor pair.
780#[derive(Clone, Copy, PartialEq, Eq)]
781enum PrivateKind {
782    /// `#x = 1`: an own property keyed by the symbol in the binding.
783    Field,
784    /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
785    Method,
786    /// `get #a() {}`: the binding holds the getter, and a read calls it.
787    Getter,
788    /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
789    /// the same `TypeError` as reading an uninitialised `const`.
790    Setter,
791}
792
793/// What the compiler knows about one `#name` where it is used.
794#[derive(Clone)]
795struct PrivateUse {
796    kind: PrivateKind,
797    /// `#a<set>` when the class defines a setter for this name.
798    ///
799    /// A second binding, not a second field of the first: the reference stores the setter
800    /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
801    setter: Option<String>,
802}
803
804/// The class-scope bindings one class body needs, in declaration order.
805#[derive(Default)]
806struct ClassPlan {
807    /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
808    /// at class entry, in member order.
809    bindings: Vec<String>,
810    /// The private names, for the use sites inside the body.
811    uses: std::collections::HashMap<String, PrivateUse>,
812    /// Computed field keys, by element index, so the emission pass does not have to redo the
813    /// per-half counter that names them.
814    computed: std::collections::HashMap<usize, String>,
815    /// Whether the instance initialiser has to add the brand to `this`.
816    instance_brand: bool,
817    /// Whether the constructor itself has to carry the brand.
818    static_brand: bool,
819}
820
821impl ClassPlan {
822    /// Walk a class body once and decide every class-scope binding it needs.
823    ///
824    /// Order is the reference's: a member's binding is created when the member is parsed, so
825    /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
826    /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
827    /// the disassembly stops matching even when every instruction is right.
828    fn build(class: &Class) -> ClassPlan {
829        let mut plan = ClassPlan::default();
830        let mut instance_keys = 0usize;
831        let mut static_keys = 0usize;
832        for (index, element) in class.elements.iter().enumerate() {
833            match element {
834                ClassElement::Method {
835                    key: PropName::Private(ident),
836                    kind,
837                    is_static,
838                    ..
839                } => {
840                    let name = format!("#{}", ident.name);
841                    let first = !plan.uses.contains_key(&name);
842                    if first {
843                        plan.bindings.push(name.clone());
844                        plan.uses.insert(
845                            name.clone(),
846                            PrivateUse {
847                                kind: match kind {
848                                    MethodKind::Get => PrivateKind::Getter,
849                                    MethodKind::Set => PrivateKind::Setter,
850                                    _ => PrivateKind::Method,
851                                },
852                                setter: None,
853                            },
854                        );
855                    }
856                    match kind {
857                        MethodKind::Set => {
858                            let binding = format!("{name}<set>");
859                            plan.bindings.push(binding.clone());
860                            if let Some(use_) = plan.uses.get_mut(&name) {
861                                use_.setter = Some(binding);
862                            }
863                        }
864                        // A getter is what makes the name readable, so a pair that started
865                        // as a setter becomes readable once the getter arrives.
866                        MethodKind::Get => {
867                            if let Some(use_) = plan.uses.get_mut(&name) {
868                                use_.kind = PrivateKind::Getter;
869                            }
870                        }
871                        _ => {}
872                    }
873                    if *is_static {
874                        plan.static_brand = true;
875                    } else {
876                        plan.instance_brand = true;
877                    }
878                }
879                ClassElement::Method {
880                    key: PropName::Computed(_),
881                    ..
882                } => {}
883                ClassElement::Method { .. } => {}
884                ClassElement::Field {
885                    key: PropName::Private(ident),
886                    ..
887                } => {
888                    let name = format!("#{}", ident.name);
889                    if !plan.uses.contains_key(&name) {
890                        plan.bindings.push(name.clone());
891                        plan.uses.insert(
892                            name,
893                            PrivateUse {
894                                kind: PrivateKind::Field,
895                                setter: None,
896                            },
897                        );
898                    }
899                }
900                ClassElement::Field {
901                    key: PropName::Computed(_),
902                    is_static,
903                    ..
904                } => {
905                    let index_in_half = if *is_static {
906                        static_keys += 1;
907                        static_keys - 1
908                    } else {
909                        instance_keys += 1;
910                        instance_keys - 1
911                    };
912                    let binding = computed_field_binding(index_in_half, *is_static);
913                    plan.bindings.push(binding.clone());
914                    plan.computed.insert(index, binding);
915                }
916                ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
917            }
918        }
919        plan
920    }
921
922    /// How a private name used inside the body compiles, or `None` if no enclosing class
923    /// declares it.
924    fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
925        compiler
926            .private_scopes
927            .iter()
928            .rev()
929            .find_map(|scope| scope.get(name))
930    }
931}
932
933/// Compile a script.
934pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
935    Compiler::new(false).compile(program)
936}
937
938/// Compile a script whose top level is the body of an `async` function.
939///
940/// The body is an ordinary script in every other way — it still reports a completion value
941/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
942/// it answers a promise instead of a value. The wrapper is what keeps that promise from
943/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
944/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
945/// documents.
946pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
947    Compiler::for_suspensible_script().compile(program)
948}
949
950/// Compile a module.
951pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
952    Compiler::new(true).compile(program)
953}
954
955impl Compiler {
956    /// Create a compiler.
957    pub fn new(module: bool) -> Compiler {
958        Compiler {
959            module,
960            async_body: false,
961            stack: Vec::new(),
962            private_scopes: Vec::new(),
963        }
964    }
965
966    /// Create a compiler for a script whose top level is an `async` function body.
967    fn for_suspensible_script() -> Compiler {
968        Compiler {
969            module: false,
970            async_body: true,
971            stack: Vec::new(),
972            private_scopes: Vec::new(),
973        }
974    }
975
976    /// Compile a whole program into its top-level function.
977    pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
978        let mut state = FnState::new("<eval>", FunctionKind::Normal);
979        // A module body is *not* a script: it has no completion value, so no hidden
980        // `<ret>` local and no `put_loc0` before each statement. What it shares with one
981        // is having no `arguments` of its own and no receiver — see `is_module`.
982        state.is_script = !self.module;
983        state.is_module = self.module;
984        if self.module {
985            state.module = Some(ModuleMeta::default());
986        }
987        state.strict = program.strict || self.module;
988        state.line = program.span.start.line;
989        state.column = program.span.start.column;
990        // Locals are numbered in declaration order; `<ret>` is always slot 0.
991        //
992        // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
993        // slot that only appears in one of the two arrays shifts every later
994        // binding's block and silently loses the temporal-dead-zone marking for
995        // the script's own blocks. A function frame has no `<ret>`, which is why
996        // the misalignment only showed up at the top level.
997        if !self.module {
998            state.vars.push(VarDef::var("<ret>"));
999            state.var_block.push(FUNCTION_SCOPE);
1000        }
1001        self.stack.push(state);
1002        // The body is its own scope, keyed by the position of the program.
1003        // The script body needs a key no statement can produce. Statement keys are
1004        // source offsets, and the program's own start offset is `0` — which is also
1005        // the offset of the first statement, so a top-level `{ let x }` or
1006        // `for (let i …)` used to share the body's block and lose its scope.
1007        let body_key = SCRIPT_BODY;
1008        self.push_block(body_key, NO_PARENT);
1009        self.state().body_block = body_key;
1010        // A module body opens with a re-entry guard. The host evaluates a module exactly
1011        // once, so the guard never fires in practice — but the reference emits it, and a
1012        // module function called a second time (through `eval` of its own source, say)
1013        // must not run its body again.
1014        let module_guard = self.module.then(|| self.new_label());
1015        if let Some(body) = module_guard {
1016            // The guard wraps the *hoisting* too: a second evaluation of the same module
1017            // body must not even re-create its function declarations.
1018            self.emit(Opcode::PushThis, &[]);
1019            self.emit_jump(Opcode::IfFalse, body, &[]);
1020        }
1021        self.hoist(&program.body, body_key)?;
1022        // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
1023        // come before the guard's `return_undef`: the reference's jump target sits past
1024        // both, and a second evaluation therefore re-creates nothing.
1025        self.emit_scope_enter(body_key);
1026        if let Some(body) = module_guard {
1027            self.emit(Opcode::ReturnUndef, &[]);
1028            self.place_label(body);
1029        }
1030        // Through `stmts` rather than the loop, so a `using` region at the top level of an
1031        // eval'd body or a module gets its disposal epilogue like any other block.
1032        self.stmts(&program.body)?;
1033        if self.module {
1034            // A module has no completion value; its body simply ends.
1035            self.emit(Opcode::Undefined, &[]);
1036            self.emit(Opcode::ReturnAsync, &[]);
1037            // Top-level `await` makes the body an async function, so the host runs it as
1038            // a coroutine and waits. Without this the `await` opcode would suspend in a
1039            // body that nothing knows how to resume — which is what "a generator body ran
1040            // as an ordinary call" was reporting.
1041            if self.cur().has_await {
1042                self.state().kind = FunctionKind::Async;
1043            }
1044        } else if self.async_body {
1045            // An async body reports its completion value the same way, but through an
1046            // object: the function answers a promise, and resolving that promise *with*
1047            // the completion value would adopt a promise completion instead of reporting
1048            // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
1049            // resolve to `{value: <promise>}` rather than to `7`.
1050            //
1051            // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
1052            // value in an object so that promises can be safely returned").
1053            self.emit(Opcode::Object, &[]);
1054            self.emit(Opcode::Dup, &[]);
1055            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1056            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
1057            self.emit(Opcode::Return, &[]);
1058            self.state().kind = FunctionKind::Async;
1059        } else {
1060            // The program's value is whatever the last expression statement stored in
1061            // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
1062            // case into a single `set_loc0`.
1063            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1064            self.emit(Opcode::Return, &[]);
1065        }
1066        Ok(self.finish_current())
1067    }
1068
1069    // -- emitting ----------------------------------------------------------
1070
1071    fn state(&mut self) -> &mut FnState {
1072        self.stack.last_mut().expect("a function is being compiled")
1073    }
1074
1075    fn cur(&self) -> &FnState {
1076        self.stack.last().expect("a function is being compiled")
1077    }
1078
1079    fn emit(&mut self, op: Opcode, operands: &[Op]) {
1080        self.state().label_since_insn = false;
1081        let pos = self.cur().cur_pos;
1082        self.state().insns.push(Insn::Fixed {
1083            op,
1084            operands: operands.to_vec(),
1085        });
1086        self.state().insn_pos.push(pos);
1087    }
1088
1089    /// Reset the script's hidden return value to `undefined`.
1090    ///
1091    /// Called at the start of every statement that does not itself produce the
1092    /// program's value, which is how the reference keeps `if`/loop results from
1093    /// leaking into an eval result.
1094    fn reset_value(&mut self) {
1095        if !self.cur().is_script {
1096            return;
1097        }
1098        self.emit(Opcode::Undefined, &[]);
1099        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1100        self.state().leaves_value = false;
1101    }
1102
1103    /// Whether `name` is a local or argument slot rather than a global.
1104    fn is_slot(&self, name: &str) -> bool {
1105        self.cur().vars.iter().any(|v| v.name == name)
1106            || self.cur().args.iter().any(|a| a.name == name)
1107    }
1108
1109    /// `with (object) body`
1110    ///
1111    /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
1112    /// what makes the object reachable from a closure created inside the block, and it
1113    /// is also what lets an `eval` find it: the runtime collects the active `With`
1114    /// locals of every frame and resolves names against them before the realm.
1115    ///
1116    /// Inside the block every name reference is spelled as "look in the with objects
1117    /// first", innermost outwards, and falls through to the ordinary access. The test is
1118    /// `in`, which is `HasProperty` — the same question the spec's Object Environment
1119    /// Record asks.
1120    fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
1121        let name = self.next_with_name();
1122        // The object expression is evaluated *outside* the scope it introduces, so no
1123        // wrapper may be emitted for the names it mentions.
1124        let saved = std::mem::take(&mut self.state().with_names);
1125        self.expr(object)?;
1126        self.state().with_names = saved;
1127        self.emit(Opcode::ToObject, &[]);
1128        self.declare_hidden_local(&name, VarKind::With);
1129        // Pushed before the store so the store itself is not guarded by an *outer*
1130        // `with` — the object being stored is the new one, not something to look up.
1131        self.state().with_names.push(name.clone());
1132        self.emit_var(VarAction::Put, &name);
1133        let result = self.stmt(body);
1134        self.state().with_names.pop();
1135        result
1136    }
1137
1138    /// A hidden-local name for one `with` block, distinct from every enclosing one.
1139    fn next_with_name(&self) -> String {
1140        let depth = self.cur().with_names.len();
1141        if depth == 0 {
1142            "<with>".to_string()
1143        } else {
1144            format!("<with{depth}>")
1145        }
1146    }
1147
1148    /// Declare a hidden local that must stay a *local* even in a script.
1149    ///
1150    /// A script's `var` is a property of the global object, but the `with` object is not
1151    /// part of the source program's name space at all — it only exists for the compiler
1152    /// and the runtime — so it goes straight into the frame's slot list.
1153    fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
1154        let state = self.state();
1155        if state.vars.iter().any(|v| v.name == name) {
1156            return;
1157        }
1158        state.var_block.push(FUNCTION_SCOPE);
1159        state.vars.push(VarDef {
1160            kind,
1161            ..VarDef::var(name)
1162        });
1163    }
1164
1165    /// Emit a name access, guarded by every active `with` object.
1166    ///
1167    /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
1168    /// the read itself; the outer guards and the plain access are what the `if_false`
1169    /// jumps to, so the innermost object wins.
1170    fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
1171        let names = self.cur().with_names.clone();
1172        let done = self.new_label();
1173        let mut starts = Vec::new();
1174        // Innermost object first: the last `with` opened is the one that shadows the
1175        // others, so its guard has to be the first chance to satisfy the name.
1176        for with_name in names.iter().rev() {
1177            let next = self.new_label();
1178            // `in` takes the key then the object.
1179            self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1180            self.emit_var(VarAction::Get, with_name);
1181            self.emit(Opcode::In, &[]);
1182            self.emit_jump(Opcode::IfFalse, next, &[]);
1183            starts.push(next);
1184            match action {
1185                // A store keeps the value under the receiver, which is where
1186                // `put_field` expects it.
1187                VarAction::Put | VarAction::PutInit => {
1188                    self.emit_var(VarAction::Get, with_name);
1189                    self.emit(Opcode::Swap, &[]);
1190                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(name))]);
1191                }
1192                _ => {
1193                    self.emit_var(VarAction::Get, with_name);
1194                    self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1195                    self.emit(Opcode::GetArrayEl, &[]);
1196                }
1197            }
1198            self.emit_jump(Opcode::Goto, done, &[]);
1199            self.place_label(next);
1200        }
1201        self.emit_var(action, name);
1202        self.place_label(done);
1203    }
1204
1205    fn emit_var(&mut self, action: VarAction, name: &str) {
1206        // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
1207        // stores and keeps the value in one instruction. The reference does this
1208        // in a post-pass; folding it at emit time keeps instruction indices
1209        // stable, which matters because labels are recorded as indices.
1210        //
1211        // Only slots have a `set_` form: a global is stored with `put_var` and
1212        // read with `get_var`, and the reference does not fold those.
1213        //
1214        // A label between the two cancels the fold. `set_x v` leaves the value on
1215        // the stack, which is only equivalent when the read immediately follows the
1216        // store; when a jump target sits in between, the store must *consume* the
1217        // value and the read must fetch it afresh. A loop head is exactly that
1218        // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
1219        // condition re-reads it — and folding across the label would make the
1220        // condition compare whatever the previous iteration left on the stack.
1221        if action == VarAction::Get {
1222            let is_slot = self.is_slot(name);
1223            let at_label = std::mem::take(&mut self.state().label_since_insn);
1224            //
1225            // `arguments` is excluded because the reference treats it as a special
1226            // binding: it is initialised once and read many times, and folding its
1227            // initialisation into a `set_` would leave the object on the stack where
1228            // the reference leaves nothing.
1229            if is_slot
1230                && name != "arguments"
1231                && !at_label
1232                && let Some(Insn::Var {
1233                    action: previous,
1234                    name: previous_name,
1235                    ..
1236                }) = self.state().insns.last_mut()
1237                && *previous == VarAction::Put
1238                && previous_name == name
1239            {
1240                *previous = VarAction::Set;
1241                return;
1242            }
1243        }
1244        // Inside a `with`, every name lookup consults the with objects first. The
1245        // hidden `<with…>` locals themselves are exempt, or the guard would recurse.
1246        let guarded = !self.cur().with_names.is_empty()
1247            && !self.cur().with_names.iter().any(|hidden| hidden == name)
1248            && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1249            && !self.state().emitting_with_guard;
1250        if guarded {
1251            self.state().emitting_with_guard = true;
1252            self.emit_with_guarded(action, name);
1253            self.state().emitting_with_guard = false;
1254            return;
1255        }
1256        let block = self.cur().current_block;
1257        self.state().label_since_insn = false;
1258        let pos = self.cur().cur_pos;
1259        let in_params = self.cur().in_params;
1260        self.state().insns.push(Insn::Var {
1261            action,
1262            name: name.to_string(),
1263            block,
1264            in_params,
1265        });
1266        self.state().insn_pos.push(pos);
1267    }
1268
1269    fn new_label(&mut self) -> Label {
1270        let state = self.state();
1271        state.labels.push(None);
1272        Label(state.labels.len() as u32 - 1)
1273    }
1274
1275    fn place_label(&mut self, label: Label) {
1276        let index = self.cur().insns.len();
1277        self.state().label_since_insn = true;
1278        self.state().labels[label.0 as usize] = Some(index);
1279    }
1280
1281    fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1282        let mut operands = vec![Op::Label(label)];
1283        operands.extend_from_slice(extra);
1284        self.emit(op, &operands);
1285    }
1286
1287    // -- scopes ------------------------------------------------------------
1288
1289    /// Start a new lexical scope inside `parent`.
1290    fn push_block(&mut self, key: u64, parent: u64) {
1291        let state = self.state();
1292        if !state.blocks.iter().any(|b| b.key == key) {
1293            state.blocks.push(Block { key, parent });
1294        }
1295        state.current_block = key;
1296    }
1297
1298    /// Emit the code that runs when a lexical scope is entered.
1299    ///
1300    /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1301    /// so entering its block marks it uninitialised. Hoisted function
1302    /// declarations are created here instead, which is why a call before the
1303    /// declaration still works.
1304    ///
1305    /// The order is not obvious: bindings are emitted in *reverse* declaration
1306    /// order, because the reference walks its scope chain, which is built by
1307    /// prepending.
1308    fn emit_scope_enter(&mut self, block: u64) {
1309        let hoisted = std::mem::take(&mut self.state().hoisted);
1310        let mut mine: Vec<(HoistTarget, u32)> = hoisted
1311            .into_iter()
1312            .filter(|(owner, _, _)| *owner == block)
1313            .map(|(_, target, pool_index)| (target, pool_index))
1314            .collect();
1315        mine.sort_by_key(|(target, _)| match target {
1316            HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1317            HoistTarget::Global(_) => u32::MAX,
1318        });
1319        for (target, pool_index) in mine {
1320            self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1321            match target {
1322                HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1323                HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1324                HoistTarget::Global(name) => {
1325                    // A global binding lives in a reference cell, so the store
1326                    // goes through `put_var_ref` while reads use `get_var`.
1327                    let block = self.cur().current_block;
1328                    let pos = self.cur().cur_pos;
1329                    let in_params = self.cur().in_params;
1330                    self.state().insns.push(Insn::Var {
1331                        action: VarAction::PutRef,
1332                        name,
1333                        block,
1334                        in_params,
1335                    });
1336                    self.state().insn_pos.push(pos);
1337                }
1338            }
1339        }
1340        for index in self.block_vars_reversed(block) {
1341            self.emit(
1342                Opcode::SetLocUninitialized,
1343                &[Op::Slot(Slot::Loc(index as u32))],
1344            );
1345        }
1346    }
1347
1348    /// Emit the code that runs when a lexical scope is exited.
1349    ///
1350    /// A captured binding has to be closed: detaching its reference cell freezes
1351    /// the value the binding had when the block ended, which is what a closure
1352    /// created inside the block must keep seeing.
1353    fn emit_scope_leave(&mut self, block: u64) {
1354        for index in self.block_vars_reversed(block) {
1355            if self.cur().vars[index].is_captured {
1356                self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1357            }
1358        }
1359    }
1360
1361    /// Locals declared in `block`, in reverse declaration order.
1362    fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1363        let state = self.cur();
1364        let mut out: Vec<usize> = (0..state.vars.len())
1365            .filter(|index| {
1366                state.var_block.get(*index).copied() == Some(block)
1367                    && state.vars[*index].is_lexical
1368                    // A derived constructor's `this` is lexical but is not initialised by
1369                    // entering the scope: `check_ctor` proves it, so its dead-zone marker
1370                    // was emitted with the constructor's own prologue.
1371                    && state.vars[*index].name != "this"
1372            })
1373            .collect();
1374        out.reverse();
1375        out
1376    }
1377
1378    /// Declare a local, even at the top level of a script.
1379    ///
1380    /// A `catch` parameter is always a local: the reference puts it in the
1381    /// function's own variable list (`1: catch e`), never in the global object,
1382    /// because it only exists while the handler runs.
1383    fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1384        let state = self.state();
1385        let index = state.vars.len() as u32;
1386        // A `catch` parameter belongs to a scope even though it is not lexical: the
1387        // runtime instantiates it per handler entry, but it never sits in the
1388        // temporal dead zone.
1389        let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1390            state.current_block
1391        } else {
1392            0
1393        };
1394        state.var_block.push(block);
1395        state.vars.push(def);
1396        index
1397    }
1398
1399    fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1400        if self.cur().is_module
1401            && self.cur().current_block == self.cur().body_block
1402            && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1403        {
1404            // Only the body's own block: a `let` inside a module-level `{}` is still an
1405            // ordinary local of that block, not a module variable.
1406            //
1407            // A `using` binding is excluded on purpose, and the reference excludes it in
1408            // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1409            // "'using' variables are currently not exported in modules"): a module-level
1410            // `using` is an ordinary *local* of the module body function, not a module
1411            // cell. Two things follow, and both are what the reference does — `export {a}`
1412            // of a `using` binding is "exported variable 'a' does not exist", and
1413            // disposal works, because the disposal epilogue addresses locals by slot.
1414            //
1415            // The hidden dispose-method variable is excluded for a stronger reason: it is
1416            // *always* a local (`add_scope_var` in the reference), and it must sit
1417            // immediately after its value so `using_dispose` can find it at `slot + 1`.
1418            return self.declare_module(name, &def);
1419        }
1420        if self.cur().declares_globally(&def) {
1421            self.declare_global(name, &def);
1422            return 0;
1423        }
1424        let state = self.state();
1425        let index = state.vars.len() as u32;
1426        let block = if def.is_lexical {
1427            state.current_block
1428        } else {
1429            0
1430        };
1431        state.var_block.push(block);
1432        state.vars.push(def);
1433        index
1434    }
1435
1436    /// Declare a `using` binding and its cached dispose method, returning both slots.
1437    ///
1438    /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1439    /// `(value, value + 1)` — the reference does the same and documents the constraint.
1440    fn declare_using(&mut self, name: &str) -> (u32, u32) {
1441        let mut def = VarDef::lexical(name);
1442        def.kind = VarKind::Using;
1443        let value = self.declare(name, def);
1444        let mut method = VarDef::lexical(using_method_name(name));
1445        method.kind = VarKind::UsingMethod;
1446        let method_slot = self.declare(&using_method_name(name), method);
1447        (value, method_slot)
1448    }
1449
1450    /// The slot a `using` binding's dispose method lives in.
1451    fn using_method_slot(&self, name: &str) -> Option<u32> {
1452        let hidden = using_method_name(name);
1453        self.cur()
1454            .vars
1455            .iter()
1456            .position(|var| var.name == hidden)
1457            .map(|index| index as u32)
1458    }
1459
1460    // -- statements --------------------------------------------------------
1461
1462    fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1463        self.stmt_labelled(stmt, &[])
1464    }
1465
1466    /// Compile a statement that a chain of labels names.
1467    ///
1468    /// Only a loop consumes `labels`; every other statement ignores them (the
1469    /// parser has already rejected a label on a statement that cannot use it).
1470    fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1471        // Only a *top-level* expression statement supplies the program's value.
1472        let saved = self.cur().leaves_value;
1473        self.state().leaves_value =
1474            matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1475        self.state().stmt_depth += 1;
1476        let result = self.stmt_inner(stmt, labels);
1477        self.state().stmt_depth -= 1;
1478        // A nested statement never contributes the program's value, so the flag
1479        // the wrapper set above is what survives.
1480        let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1481        self.state().leaves_value = produced;
1482        let _ = saved;
1483        result
1484    }
1485
1486    fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1487        match &stmt.kind {
1488            StmtKind::Empty | StmtKind::Debugger => {}
1489            StmtKind::Expr(expr) => {
1490                // The statement's first token is a position the reference records: an
1491                // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1492                // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1493                // is why an error from a construct with no position of its own (`[...it]`
1494                // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1495                let saved = self.cur().cur_pos;
1496                self.state().cur_pos = Some(expr.span.start);
1497                // An expression statement's value is thrown away — except in a
1498                // script, where it becomes the program's result. `assign` reads this
1499                // and clears it, so a nested assignment still produces a value.
1500                self.state().discard_value = !self.cur().is_script;
1501                let result = self.expr(expr);
1502                self.state().discard_value = false;
1503                result?;
1504                if std::mem::take(&mut self.state().no_value) {
1505                    // A store whose value was discarded left nothing to drop.
1506                } else if self.cur().is_script {
1507                    // The program's value lands in the hidden `<ret>` local.
1508                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1509                } else {
1510                    self.emit(Opcode::Drop, &[]);
1511                }
1512                // Restored last: the trailing `drop` is part of the statement, and in the
1513                // reference it simply inherits whatever the expression last recorded.
1514                self.state().cur_pos = saved;
1515            }
1516            StmtKind::Block(body) => {
1517                // The block's declarations were hoisted with its enclosing
1518                // statement list, so there is nothing left to declare here.
1519                let key = stmt.span.start.offset as u64;
1520                let parent = self.cur().current_block;
1521                self.push_block(key, parent);
1522                self.emit_scope_enter(key);
1523                // A block is where a `using` region lives, so its statements have to go
1524                // through `stmts`: that is what emits the disposal epilogue.
1525                self.stmts(body)?;
1526                self.emit_scope_leave(key);
1527                self.state().current_block = parent;
1528            }
1529            StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1530            // A function declaration was already instantiated when its scope was
1531            // entered, so the statement itself emits nothing.
1532            StmtKind::FuncDecl(_) => {}
1533            StmtKind::If { test, cons, alt } => {
1534                self.reset_value();
1535                let else_label = self.new_label();
1536                let end_label = self.new_label();
1537                self.expr(test)?;
1538                self.emit_jump(Opcode::IfFalse, else_label, &[]);
1539                self.stmt(cons)?;
1540                if alt.is_some() {
1541                    self.emit_jump(Opcode::Goto, end_label, &[]);
1542                }
1543                self.place_label(else_label);
1544                if let Some(alt) = alt {
1545                    self.stmt(alt)?;
1546                    self.place_label(end_label);
1547                }
1548            }
1549            StmtKind::While { test, body } => {
1550                self.reset_value();
1551                let top = self.new_label();
1552                let end = self.new_label();
1553                self.place_label(top);
1554                self.expr(test)?;
1555                // The condition's false branch and `break` share one target,
1556                // which is why a `while` loop needs only one end label.
1557                self.emit_jump(Opcode::IfFalse, end, &[]);
1558                self.loop_body(body, labels, top, end)?;
1559                self.emit_jump(Opcode::Goto, top, &[]);
1560                self.place_label(end);
1561            }
1562            StmtKind::DoWhile { body, test } => {
1563                self.reset_value();
1564                let top = self.new_label();
1565                let cont = self.new_label();
1566                let end = self.new_label();
1567                self.place_label(top);
1568                // `continue` in a `do…while` runs the test, so it lands on `cont`
1569                // rather than on the loop head.
1570                self.loop_body(body, labels, cont, end)?;
1571                self.place_label(cont);
1572                self.expr(test)?;
1573                self.emit_jump(Opcode::IfTrue, top, &[]);
1574                self.place_label(end);
1575            }
1576            StmtKind::For {
1577                init,
1578                test,
1579                update,
1580                body,
1581            } => {
1582                self.reset_value();
1583                let for_key = stmt.span.start.offset as u64;
1584                let for_parent = self.cur().current_block;
1585                self.push_block(for_key, for_parent);
1586                self.emit_scope_enter(for_key);
1587                if let Some(init) = init {
1588                    match init {
1589                        ForInit::VarDecl(decl) => {
1590                            self.var_decl(decl)?;
1591                        }
1592                        ForInit::Expr(expr) => {
1593                            // The head's value is discarded. Saying so lets an
1594                            // assignment store with `put` instead of `dup`+`put`, which
1595                            // is what the reference emits — and the difference matters:
1596                            // a `dup`/`drop` pair around the store gives the peephole a
1597                            // chance to fold the store into the *condition's* read.
1598                            self.state().discard_value = true;
1599                            let result = self.expr(expr);
1600                            self.state().discard_value = false;
1601                            result?;
1602                            if !std::mem::take(&mut self.state().no_value) {
1603                                self.emit(Opcode::Drop, &[]);
1604                            }
1605                        }
1606                    }
1607                }
1608                // A `let`/`const` in the head gets a *fresh binding per iteration*,
1609                // so a closure made in the body captures that iteration's value
1610                // instead of sharing one. The reference expresses this with
1611                // `close_loc`, which swaps in a new reference cell holding the
1612                // current value; the three points below are the ones it uses — after
1613                // the initialiser, before the update, and after the loop.
1614                let loop_bindings = match init {
1615                    Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
1616                        let mut names: Vec<String> = Vec::new();
1617                        for declarator in &decl.declarators {
1618                            let mut idents = Vec::new();
1619                            declarator.target.bound_names(&mut idents);
1620                            names.extend(idents.into_iter().map(|ident| ident.name));
1621                        }
1622                        names
1623                    }
1624                    _ => Vec::new(),
1625                };
1626                // The reference also closes right after the initialiser, so the first
1627                // iteration's closures get their own cell rather than sharing the one
1628                // the initialiser wrote into.
1629                for name in &loop_bindings {
1630                    let pos = self.cur().cur_pos;
1631                    self.state().insns.push(Insn::CloseCaptured {
1632                        name: name.clone(),
1633                        block: for_key,
1634                    });
1635                    self.state().insn_pos.push(pos);
1636                }
1637                let top = self.new_label();
1638                let cont = self.new_label();
1639                let end = self.new_label();
1640                self.place_label(top);
1641                if let Some(test) = test {
1642                    self.expr(test)?;
1643                    self.emit_jump(Opcode::IfFalse, end, &[]);
1644                }
1645                // `continue` runs the update expression first, so it lands on
1646                // `cont`, which sits just before the update.
1647                self.loop_body(body, labels, cont, end)?;
1648                self.place_label(cont);
1649                // Each iteration ends with a fresh cell, so the closures the body just
1650                // created keep the cell they captured and the update writes to a new
1651                // one. Without this every closure in the loop shares one binding.
1652                let binding_block = for_key;
1653                for name in &loop_bindings {
1654                    let pos = self.cur().cur_pos;
1655                    self.state().insns.push(Insn::CloseCaptured {
1656                        name: name.clone(),
1657                        block: binding_block,
1658                    });
1659                    self.state().insn_pos.push(pos);
1660                }
1661                if let Some(update) = update {
1662                    self.state().discard_value = true;
1663                    let result = self.expr(update);
1664                    self.state().discard_value = false;
1665                    result?;
1666                    if !std::mem::take(&mut self.state().no_value) {
1667                        self.emit(Opcode::Drop, &[]);
1668                    }
1669                }
1670                self.emit_jump(Opcode::Goto, top, &[]);
1671                self.place_label(end);
1672                self.emit_scope_leave(for_key);
1673                self.state().current_block = for_parent;
1674            }
1675            StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1676            StmtKind::Throw(expr) => {
1677                self.expr(expr)?;
1678                self.emit(Opcode::Throw, &[]);
1679            }
1680            StmtKind::Break(_) | StmtKind::Continue(_) => {
1681                // Labels and loops are wired up in a later milestone; a bare
1682                // break/continue jumps to the innermost enclosing target, which
1683                // the loop helpers register.
1684                self.control_transfer(stmt)?;
1685            }
1686            StmtKind::Labeled { label, body } => {
1687                self.labeled(label, body, stmt)?;
1688            }
1689            StmtKind::Switch {
1690                discriminant,
1691                cases,
1692            } => {
1693                self.switch(discriminant, cases, stmt)?;
1694            }
1695            StmtKind::Try {
1696                block,
1697                handler,
1698                finalizer,
1699            } => {
1700                self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
1701            }
1702            StmtKind::ForIn { left, right, body } => {
1703                self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
1704            }
1705            StmtKind::ForOf {
1706                left,
1707                right,
1708                body,
1709                is_await,
1710            } => {
1711                let kind = if *is_await {
1712                    ForLoopKind::AwaitOf
1713                } else {
1714                    ForLoopKind::Of
1715                };
1716                self.for_in_of(stmt, left, right, body, kind, labels)?;
1717            }
1718            StmtKind::With { object, body } => self.with_stmt(object, body)?,
1719            StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
1720            // `import` emits nothing: hoisting already bound its names, and the host
1721            // fills their cells before the body runs.
1722            StmtKind::Import(_) => {}
1723            StmtKind::Export(decl) => self.export_stmt(decl)?,
1724        }
1725        Ok(())
1726    }
1727
1728    /// Compile `return`, running every enclosing finalizer on the way out.
1729    ///
1730    /// `nip_catch` is what makes this possible: it discards everything on the stack
1731    /// down to and including the `catch` offset while keeping the return value on
1732    /// top, so the frame the finalizer sees has the same shape as on the normal
1733    /// path.
1734    fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
1735        let mut has_value = value.is_some();
1736        if let Some(expr) = value {
1737            // `return f(x)` is a tail call *only* when nothing has to happen to the
1738            // value afterwards. A `finally` or an open iterator in scope forces the
1739            // normal path, because the cleanup has to run after the call returns —
1740            // which is exactly what a tail call refuses to do.
1741            let plain = self
1742                .cur()
1743                .jump_targets
1744                .iter()
1745                .all(|target| target.finally_label.is_none() && !target.has_iterator);
1746            if plain && self.expr_if_tail_call(expr)? {
1747                return Ok(());
1748            }
1749            self.expr(expr)?;
1750        }
1751        // `return v` in an *async generator* awaits `v` before anything else happens —
1752        // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
1753        // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
1754        // exactly that reason ("the await must be done before handling the finally in case
1755        // it raises an exception").
1756        if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
1757            self.emit(Opcode::Await, &[]);
1758            self.state().has_await = true;
1759        }
1760        has_value = self.emit_unwind_for_return(has_value);
1761        // A generator or async function does not return to its caller: it either
1762        // finishes, and the value becomes `{value, done: true}`, or it suspends.
1763        // `return_async` is the "finished" half, and it reads the value off the stack
1764        // rather than carrying it, which is what the resume machinery expects.
1765        if self.cur().is_suspending() {
1766            if !has_value {
1767                self.emit(Opcode::Undefined, &[]);
1768            }
1769            self.emit(Opcode::ReturnAsync, &[]);
1770            return Ok(());
1771        }
1772        if has_value {
1773            self.emit(Opcode::Return, &[]);
1774        } else {
1775            self.emit(Opcode::ReturnUndef, &[]);
1776        }
1777        Ok(())
1778    }
1779
1780    /// Close an iterator: the reference's `emit_iterator_close`.
1781    ///
1782    /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
1783    /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
1784    /// sequence, and three details in it are load-bearing:
1785    ///
1786    /// * the iterator object is compared against `undefined` first, because a loop that
1787    ///   ran to completion clears that slot rather than closing an exhausted iterator;
1788    /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
1789    /// * `preserve_completion` keeps whatever was underneath (the return value of the
1790    ///   function being left), which is why one branch ends on `nip` and the other on `drop`.
1791    fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
1792        if !is_async {
1793            if preserve_completion {
1794                self.emit(Opcode::Rot3r, &[]);
1795                self.emit(Opcode::Undefined, &[]);
1796            }
1797            self.emit(Opcode::IteratorClose, &[]);
1798            return;
1799        }
1800        if preserve_completion {
1801            // `iter next completion -> completion iter`
1802            self.emit(Opcode::Nip, &[]);
1803            self.emit(Opcode::Swap, &[]);
1804        } else {
1805            // `iter next catch_offset -> iter`
1806            self.emit(Opcode::Drop, &[]);
1807            self.emit(Opcode::Drop, &[]);
1808        }
1809        let done = self.new_label();
1810        let no_return = self.new_label();
1811        self.emit(Opcode::Dup, &[]);
1812        self.emit(Opcode::IsUndefined, &[]);
1813        self.emit_jump(Opcode::IfTrue, done, &[]);
1814        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
1815        self.emit(Opcode::Dup, &[]);
1816        self.emit(Opcode::IsUndefinedOrNull, &[]);
1817        self.emit_jump(Opcode::IfTrue, no_return, &[]);
1818        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
1819        self.emit(Opcode::Await, &[]);
1820        self.state().has_await = true;
1821        self.emit_jump(Opcode::Goto, done, &[]);
1822        self.place_label(no_return);
1823        self.emit(Opcode::Drop, &[]);
1824        self.place_label(done);
1825        self.emit(Opcode::Drop, &[]);
1826    }
1827
1828    /// Emit the finalizer/iterator cleanup for leaving the current position with a
1829    /// return, and report whether a value is now on the stack for it to carry.
1830    ///
1831    /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
1832    /// enclosing `finally` at once, and the two used to be separate — the `yield` path
1833    /// simply emitted `return_async`, so `it.return()` ended the generator without ever
1834    /// running `finally` blocks the body was sitting inside.
1835    fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
1836        let targets = self.cur().jump_targets.clone();
1837        for target in targets.iter().rev() {
1838            if target.finally_label.is_none() && !target.has_iterator {
1839                continue;
1840            }
1841            if !has_value {
1842                // The cleanup expects a value to pass through; with nothing to
1843                // return, `undefined` stands in.
1844                self.emit(Opcode::Undefined, &[]);
1845                has_value = true;
1846            }
1847            self.emit(Opcode::NipCatch, &[]);
1848            if target.has_iterator {
1849                // Rewind to the loop's own slots and hand the close a dummy catch offset:
1850                // the loop is being abandoned, so there is nothing left to catch.
1851                self.emit_iterator_close(target.is_async_iterator, true);
1852            } else if let Some(finally) = target.finally_label {
1853                self.emit_jump(Opcode::Gosub, finally, &[]);
1854            }
1855        }
1856        has_value
1857    }
1858
1859    /// Compile a statement list, stopping at the first statement that cannot
1860    /// fall through.
1861    fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
1862        for (index, stmt) in body.iter().enumerate() {
1863            // A `using` declaration is not just a binding: everything after it, to the end
1864            // of the list, runs inside its disposal region. Compiling the rest of the list
1865            // recursively is what gives nested regions their innermost-first order.
1866            if Self::using_declaration(stmt).is_some() {
1867                return self.using_region(stmt, &body[index + 1..]);
1868            }
1869            self.stmt(stmt)?;
1870            if Self::terminates(stmt) {
1871                break;
1872            }
1873        }
1874        Ok(())
1875    }
1876
1877    /// The declaration a `using` statement carries, if it is one.
1878    fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
1879        match &stmt.kind {
1880            StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
1881            _ => None,
1882        }
1883    }
1884
1885    /// Compile `decl` and then the rest of its block, disposing when the block ends.
1886    ///
1887    /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
1888    /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
1889    /// exception — and this engine already funnels all of those through `catch` plus
1890    /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
1891    /// `return` and `break` dispose without knowing anything about `using`.
1892    ///
1893    /// ```text
1894    ///   <declaration>              value -> x, method -> x+1
1895    ///   catch CATCH                <- an exception in the rest lands here
1896    /// REST:
1897    ///   <the rest of the block>
1898    ///   drop                       <- the catch offset, on the fall-through path
1899    ///   undefined; gosub DISPOSE; drop
1900    ///   goto END
1901    /// CATCH:
1902    ///   using_dispose x            <- merges the failure into the pending exception
1903    ///   throw
1904    /// DISPOSE:
1905    ///   using_dispose_init
1906    ///   using_dispose x
1907    ///   using_dispose_end          <- rethrows if a dispose failed
1908    ///   ret
1909    /// END:
1910    /// ```
1911    fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
1912        let Some(decl) = Self::using_declaration(stmt) else {
1913            unreachable!("using_region is only called for a using declaration");
1914        };
1915        // `using` binds exactly one name and has no pattern form, which the parser
1916        // enforces; the region still has to know *which* slot to dispose.
1917        let name = decl
1918            .declarators
1919            .first()
1920            .and_then(|declarator| match &declarator.target.kind {
1921                PatternKind::Ident(ident) => Some(ident.name.clone()),
1922                _ => None,
1923            });
1924        self.stmt(stmt)?;
1925        let Some(name) = name else {
1926            // Unreachable for a well-formed `using`, but a bare `using` with no declarator
1927            // must not make the compiler panic.
1928            return self.stmts(rest);
1929        };
1930        let Some(value_slot) = self.using_value_slot(&name) else {
1931            // Declared globally, which the parser rules out for a script; a module's
1932            // top level is a scope, and there the disposal stays a known gap.
1933            return self.stmts(rest);
1934        };
1935        // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
1936        // exit path already disposed.
1937        let live = !rest.last().is_some_and(Self::terminates);
1938        self.using_region_around(value_slot, live, |compiler| compiler.stmts(rest))
1939    }
1940
1941    /// The slot a `using` binding's value lives in.
1942    fn using_value_slot(&self, name: &str) -> Option<u32> {
1943        self.cur()
1944            .vars
1945            .iter()
1946            .position(|var| var.name == name && var.kind == VarKind::Using)
1947            .map(|index| index as u32)
1948    }
1949
1950    /// Wrap `inside` in a disposal region for the resource in `value_slot`.
1951    ///
1952    /// Shared between a `using` statement — which owns the rest of its block — and a
1953    /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
1954    /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
1955    /// the end, `return`, `break`, `continue`, and an exception — and this engine already
1956    /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
1957    /// target with a `finally_label` is what makes `return` and `break` dispose without
1958    /// knowing anything about `using`.
1959    ///
1960    /// ```text
1961    ///   catch CATCH                <- an exception inside lands here
1962    ///   <inside>
1963    ///   drop                       <- the catch offset, on the fall-through path
1964    ///   undefined; gosub DISPOSE; drop
1965    ///   goto END
1966    /// CATCH:
1967    ///   using_dispose slot         <- merges the failure into the pending exception
1968    ///   throw
1969    /// DISPOSE:
1970    ///   using_dispose_init
1971    ///   using_dispose slot
1972    ///   using_dispose_end          <- rethrows if a dispose failed
1973    ///   ret
1974    /// END:
1975    /// ```
1976    fn using_region_around(
1977        &mut self,
1978        value_slot: u32,
1979        live: bool,
1980        inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
1981    ) -> Result<(), SyntaxError> {
1982        let catch_label = self.new_label();
1983        let end_label = self.new_label();
1984        let dispose_label = self.new_label();
1985
1986        self.emit_jump(Opcode::Catch, catch_label, &[]);
1987        self.push_jump_target(JumpTarget {
1988            names: Vec::new(),
1989            break_label: None,
1990            continue_label: None,
1991            // The catch offset is the one thing on the stack that leaving has to remove.
1992            drop_count: 1,
1993            finally_label: Some(dispose_label),
1994            is_regular_stmt: false,
1995            has_iterator: false,
1996            is_async_iterator: false,
1997        });
1998        inside(self)?;
1999        self.pop_jump_target();
2000
2001        if live {
2002            self.emit(Opcode::Drop, &[]);
2003            self.emit(Opcode::Undefined, &[]);
2004            self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2005            self.emit(Opcode::Drop, &[]);
2006            self.emit_jump(Opcode::Goto, end_label, &[]);
2007        }
2008
2009        // An exception unwinds to here with the thrown value on the stack, which is exactly
2010        // the shape `using_dispose` expects as its error state.
2011        self.place_label(catch_label);
2012        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2013        self.emit(Opcode::Throw, &[]);
2014
2015        self.place_label(dispose_label);
2016        // Inside the subroutine the return value and the `gosub` return address are both
2017        // live, and neither an outer finalizer nor another region may run before this one
2018        // has finished.
2019        self.push_jump_target(JumpTarget {
2020            names: Vec::new(),
2021            break_label: None,
2022            continue_label: None,
2023            drop_count: 2,
2024            finally_label: None,
2025            is_regular_stmt: false,
2026            has_iterator: false,
2027            is_async_iterator: false,
2028        });
2029        self.emit(Opcode::UsingDisposeInit, &[]);
2030        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2031        self.emit(Opcode::UsingDisposeEnd, &[]);
2032        self.pop_jump_target();
2033        self.emit(Opcode::Ret, &[]);
2034        self.place_label(end_label);
2035        Ok(())
2036    }
2037
2038    /// Declare every name a statement list introduces, before compiling any of
2039    /// it, so a reference that appears textually before a declaration still
2040    /// resolves.
2041    ///
2042    /// Declarations are walked in source order because that is the order the
2043    /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2044    /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2045    /// declarations hoist out to the function scope; lexical names belong to the
2046    /// block they were written in, which `block` records.
2047    fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2048        let saved = self.cur().current_block;
2049        self.state().current_block = block;
2050        let result = self.hoist_list(body);
2051        // Only now is every binding of this scope known, so the deferred function
2052        // bodies can be compiled against the finished list. Compiled at its own
2053        // declaration instead, a body that names a `var` written further down would
2054        // have resolved that name as a global.
2055        if result.is_ok() {
2056            let deferred = std::mem::take(&mut self.state().deferred_funcs);
2057            let mut outcome = Ok(());
2058            for (owner, func) in deferred {
2059                let previous = self.cur().current_block;
2060                self.state().current_block = owner;
2061                outcome = self.func_decl(&func);
2062                self.state().current_block = previous;
2063                if outcome.is_err() {
2064                    break;
2065                }
2066            }
2067            self.state().current_block = saved;
2068            return outcome;
2069        }
2070        // `current_block` is restored by the caller for a block statement, since
2071        // it needs it set while compiling; only clean up on the hoist path.
2072        self.state().current_block = saved;
2073        result
2074    }
2075
2076    fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2077        for stmt in body {
2078            self.hoist_stmt(stmt)?;
2079        }
2080        Ok(())
2081    }
2082
2083    /// Whether a statement always transfers control away, making everything after
2084    /// it in the same list unreachable.
2085    ///
2086    /// The reference drops such statements in `skip_dead_code`, so `return 1;
2087    /// let x = 2;` compiles to the same bytecode as `return 1;`.
2088    fn terminates(stmt: &Stmt) -> bool {
2089        matches!(
2090            stmt.kind,
2091            StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2092        )
2093    }
2094
2095    fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2096        match &stmt.kind {
2097            StmtKind::VarDecl(decl) => {
2098                for declarator in &decl.declarators {
2099                    let mut names = Vec::new();
2100                    declarator.target.bound_names(&mut names);
2101                    for name in names {
2102                        let text = name.name.clone();
2103                        if decl.kind == VarDeclKind::Var {
2104                            let def = VarDef::var(text.clone());
2105                            self.declare_var(&text, def);
2106                        } else if decl.kind.is_using() {
2107                            // Two adjacent slots: the resource, then the dispose method
2108                            // snapshotted at declaration. `using_dispose` reads them as a
2109                            // pair `(slot, slot + 1)`, so nothing may be declared between
2110                            // them — which is why both are declared here, in one step,
2111                            // rather than the method being added at emission time.
2112                            self.declare_using(&text);
2113                        } else {
2114                            let def = if decl.kind == VarDeclKind::Const {
2115                                VarDef::constant(text.clone())
2116                            } else {
2117                                VarDef::lexical(text.clone())
2118                            };
2119                            self.declare(&text, def);
2120                        }
2121                    }
2122                }
2123            }
2124            StmtKind::FuncDecl(func) => {
2125                if let Some(name) = &func.name {
2126                    // A function declaration is a `var` binding that happens to
2127                    // hold a function, not a lexical one.
2128                    let def = VarDef::var(name.name.clone());
2129                    self.declare_var(&name.name.clone(), def);
2130                }
2131                // The function object is created when the scope is entered, so it
2132                // exists before the declaration is reached. Its body is compiled
2133                // *after* this scope's hoisting finishes, so a name it uses resolves
2134                // even when the `var` that declares it comes later in the source.
2135                let owner = self.cur().current_block;
2136                self.state().deferred_funcs.push((owner, func.clone()));
2137            }
2138            StmtKind::ClassDecl(class) => {
2139                if let Some(name) = &class.name {
2140                    self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2141                }
2142            }
2143            // A module's imports are bound before any of its code runs, and its exports
2144            // declare the very bindings they export — so both hoist the declarations
2145            // their `StmtKind` arm will later emit code for.
2146            StmtKind::Import(decl) => self.hoist_import(decl)?,
2147            StmtKind::Export(decl) => self.hoist_export(decl)?,
2148            StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2149            StmtKind::If { cons, alt, .. } => {
2150                self.hoist_stmt(cons)?;
2151                if let Some(alt) = alt {
2152                    self.hoist_stmt(alt)?;
2153                }
2154            }
2155            StmtKind::While { body, .. }
2156            | StmtKind::DoWhile { body, .. }
2157            | StmtKind::Labeled { body, .. }
2158            | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2159            StmtKind::For { init, body, .. } => {
2160                // A `for` head gets its own scope even when it declares nothing,
2161                // because `let` in the head is scoped to the loop.
2162                let key = stmt.span.start.offset as u64;
2163                let parent = self.cur().current_block;
2164                self.push_block(key, parent);
2165                if let Some(init) = init
2166                    && let ForInit::VarDecl(decl) = init
2167                {
2168                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2169                }
2170                self.hoist_stmt(body)?;
2171                self.state().current_block = parent;
2172            }
2173            StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
2174                let key = stmt.span.start.offset as u64;
2175                let parent = self.cur().current_block;
2176                self.push_block(key, parent);
2177                if let ForHead::VarDecl(decl) = left {
2178                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2179                }
2180                self.hoist_stmt(body)?;
2181                self.state().current_block = parent;
2182            }
2183            StmtKind::Try {
2184                block,
2185                handler,
2186                finalizer,
2187            } => {
2188                self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2189                let try_parent = self.cur().current_block;
2190                if let Some(handler) = handler {
2191                    // The catch parameter belongs to the function scope, not to a
2192                    // block: it is a `catch` binding rather than a `let`, so it is
2193                    // never in the temporal dead zone and `emit_scope_enter` must
2194                    // not mark it uninitialised. It still has to be declared before
2195                    // the handler body is hoisted, so it takes the slot the
2196                    // reference gives it (bindings are numbered in source order).
2197                    if let Some(pattern) = &handler.param {
2198                        // The parameter gets its own scope, so entering the handler
2199                        // does not have to re-declare it. It is not lexical, so it
2200                        // is never marked uninitialised.
2201                        let key = Self::try_block_key(stmt, TryPart::Param);
2202                        let parent = self.cur().current_block;
2203                        self.push_block(key, parent);
2204                        // A destructuring parameter binds several names, one slot each,
2205                        // in the order they are written. The reference declares those as
2206                        // `let`s rather than as one `catch` binding — its dump prints
2207                        // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2208                        // so the kind follows the shape of the parameter.
2209                        //
2210                        // Neither form is in the dead zone: the stores run as the handler
2211                        // is entered, so both use the unchecked `put_loc`.
2212                        let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2213                        let mut names = Vec::new();
2214                        pattern.bound_names(&mut names);
2215                        for name in names {
2216                            let def = VarDef {
2217                                name: name.name.clone(),
2218                                is_const: false,
2219                                is_lexical: destructures,
2220                                kind: if destructures {
2221                                    crate::bytecode::VarKind::LexicalCatch
2222                                } else {
2223                                    crate::bytecode::VarKind::Catch
2224                                },
2225                                is_captured: false,
2226                                scope_level: 0,
2227                                scope_next: None,
2228                            };
2229                            self.declare_local(&name.name.clone(), def);
2230                        }
2231                        // The handler body nests inside the parameter's scope, so the
2232                        // body's bindings chain on to the parameter (the reference
2233                        // prints `let y [next:1]`, pointing at `e`).
2234                        self.state().current_block = key;
2235                    }
2236                    self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2237                    // Back to the block the `try` itself lives in, so the finalizer
2238                    // is a sibling of the handler rather than nested in it.
2239                    self.state().current_block = try_parent;
2240                }
2241                if let Some(finalizer) = finalizer {
2242                    self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2243                }
2244            }
2245            StmtKind::Switch { cases, .. } => {
2246                let key = stmt.span.start.offset as u64;
2247                let parent = self.cur().current_block;
2248                self.push_block(key, parent);
2249                for case in cases {
2250                    self.hoist_list(&case.body)?;
2251                }
2252                self.state().current_block = parent;
2253            }
2254            _ => {}
2255        }
2256        Ok(())
2257    }
2258
2259    /// Hoist a nested statement list, which is its own lexical scope.
2260    fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2261        let parent = self.cur().current_block;
2262        self.push_block(key, parent);
2263        self.hoist_list(body)?;
2264        self.state().current_block = parent;
2265        Ok(())
2266    }
2267
2268    /// A block key for one part of a `try` statement.
2269    ///
2270    /// The three parts are three separate scopes, so they cannot share the key a
2271    /// statement's own offset would give them: the try block, the handler body and
2272    /// the finalizer would then look like one scope, and their `let` bindings would
2273    /// be marked uninitialised only on entering the first of them.
2274    fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2275        (stmt.span.start.offset as u64) * 4 + part as u64
2276    }
2277
2278    /// Declare a `var`: it lives in the function's own scope, not the block's.
2279    fn declare_var(&mut self, name: &str, def: VarDef) {
2280        if self.cur().is_module {
2281            self.declare_module(name, &def);
2282            return;
2283        }
2284        if self.cur().declares_globally(&def) {
2285            self.declare_global(name, &def);
2286            return;
2287        }
2288        let state = self.state();
2289        // A binding of the *parameter* scope does not count: the body's `var` of the
2290        // same name is a different binding and needs a slot of its own.
2291        if state.vars.iter().enumerate().any(|(index, v)| {
2292            v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
2293        }) {
2294            return;
2295        }
2296        // A `var` belongs to the function scope, never to the enclosing block.
2297        state.var_block.push(FUNCTION_SCOPE);
2298        state.vars.push(def);
2299    }
2300
2301    /// Declare `name` as a binding of the parameter scope, returning its slot.
2302    fn declare_param_var(&mut self, name: &str) -> u32 {
2303        declare_param_var_at(self.state(), name)
2304    }
2305
2306    /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2307    ///
2308    /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2309    /// so each points at the one declared before it and the oldest ends the chain with
2310    /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2311    /// runtime walks when it instantiates them.
2312    fn declare_param_binding(&mut self, name: &str) -> u32 {
2313        let state = self.state();
2314        let previous = state
2315            .vars
2316            .iter()
2317            .enumerate()
2318            .rev()
2319            .find(|(index, var)| {
2320                state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2321            })
2322            .map(|(index, _)| index as i32);
2323        let index = state.vars.len() as u32;
2324        state.var_block.push(PARAM_SCOPE);
2325        let mut def = VarDef::lexical(name);
2326        // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2327        // the function's, and its bindings are initialised one by one rather than all at
2328        // once — which is exactly what the dead zone needs.
2329        def.scope_level = 1;
2330        def.scope_next = Some(previous.unwrap_or(-2));
2331        state.vars.push(def);
2332        index
2333    }
2334
2335    /// The slot of a parameter-list binding, if the list has one by that name.
2336    fn param_binding_slot(&self, name: &str) -> Option<u32> {
2337        let state = self.cur();
2338        state
2339            .vars
2340            .iter()
2341            .enumerate()
2342            .position(|(index, var)| {
2343                var.name == name
2344                    && var.is_lexical
2345                    && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2346            })
2347            .map(|index| index as u32)
2348    }
2349
2350    /// Every parameter-list binding, in declaration order.
2351    fn param_binding_names(&self) -> Vec<String> {
2352        let state = self.cur();
2353        state
2354            .vars
2355            .iter()
2356            .enumerate()
2357            .filter(|(index, var)| {
2358                var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2359            })
2360            .map(|(_, var)| var.name.clone())
2361            .collect()
2362    }
2363
2364    /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2365    fn body_var_slot(&self, name: &str) -> Option<u32> {
2366        let state = self.cur();
2367        state
2368            .vars
2369            .iter()
2370            .enumerate()
2371            .find(|(index, var)| {
2372                var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2373            })
2374            .map(|(index, _)| index as u32)
2375    }
2376
2377    /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2378    /// one.
2379    ///
2380    /// With parameter expressions the reference creates two: an unmapped one in the
2381    /// argument scope, for the defaults and anything they close over, and the body's own.
2382    /// They are separate bindings, which is what makes
2383    /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2384    /// report 1 from `p` and 2 from the body.
2385    fn provide_param_arguments(&mut self) {
2386        if !self.cur().has_parameter_expressions {
2387            return;
2388        }
2389        let mentioned = self.cur().needs_param_arguments
2390            || self
2391                .cur()
2392                .insns
2393                .iter()
2394                .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2395        if !mentioned {
2396            return;
2397        }
2398        let slot = self.declare_param_var("arguments");
2399        let magic = if self.cur().strict { 0 } else { 1 };
2400        self.prepend_initialiser_to(
2401            slot,
2402            Insn::Fixed {
2403                op: Opcode::SpecialObject,
2404                operands: vec![Op::Int(magic)],
2405            },
2406        );
2407    }
2408
2409    /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2410    fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2411        let current = self.stack.len() - 1;
2412        let init = [
2413            producer,
2414            Insn::Fixed {
2415                op: Opcode::PutLoc,
2416                operands: vec![Op::Slot(Slot::Loc(slot))],
2417            },
2418        ];
2419        let inserted = init.len();
2420        for (index, instruction) in init.into_iter().enumerate() {
2421            self.stack[current].insns.insert(index, instruction);
2422        }
2423        for placed in self.stack[current].labels.iter_mut().flatten() {
2424            *placed += inserted;
2425        }
2426        self.state().label_since_insn = false;
2427    }
2428
2429    /// Give the function an `arguments` binding if its body mentions one.
2430    ///
2431    /// The check runs on the *instruction* stream rather than the AST: by this point
2432    /// every reference has become an `Insn::Var`, so scanning is exact and needs no
2433    /// AST walker. Declaring lazily matters for more than tidiness — always declaring
2434    /// would renumber every later local slot and stop the bytecode matching the
2435    /// reference, which only adds the binding when the body uses it.
2436    ///
2437    /// `arguments` is a local, initialised at the top of the body by
2438    /// `special_object`; that is the reference's shape, so the disassembly agrees.
2439    fn provide_arguments(&mut self) {
2440        let current = self.stack.len() - 1;
2441        if self.stack[current].is_script || self.stack[current].is_module {
2442            // A module has no `arguments` binding; referring to it is a ReferenceError,
2443            // which is exactly what an unbound name produces.
2444            return;
2445        }
2446        // An arrow has no `arguments` of its own: the binding belongs to the enclosing
2447        // function, which is why `() => arguments` sees the caller's arguments.
2448        if self.stack[current].is_arrow {
2449            if self.mentions("arguments") {
2450                self.ensure_enclosing_arguments();
2451            }
2452            return;
2453        }
2454        // Only a *body* mention needs the body's binding: the parameter list has one of
2455        // its own (see [`Compiler::provide_param_arguments`]).
2456        let mentioned = self.cur().insns.iter().any(|insn| {
2457            matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params)
2458        });
2459        if !mentioned && !self.cur().needs_arguments_local {
2460            return;
2461        }
2462        // The request may have come only from a parameter-list arrow, in which case the
2463        // parameter scope's binding already answers for it and the body needs none.
2464        if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
2465            return;
2466        }
2467        // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`. The mapping itself is
2468        // not implemented, so the two behave alike for now.
2469        //
2470        // With parameter expressions the list and the body are separate environments, so
2471        // an assignment to a parameter cannot be reflected into `arguments` at all — the
2472        // arguments object is unmapped whatever the mode, which is why the reference emits
2473        // `special_object 0` here even in sloppy code.
2474        let magic = if self.stack[current].strict || self.stack[current].has_parameter_expressions {
2475            0
2476        } else {
2477            1
2478        };
2479        self.prepend_binding("arguments", magic);
2480    }
2481
2482    /// Whether a *body* instruction refers to `arguments`.
2483    fn body_mentions_arguments(&self) -> bool {
2484        self.cur()
2485            .insns
2486            .iter()
2487            .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
2488    }
2489
2490    /// Whether the function body's instruction stream refers to `name`.
2491    fn mentions(&self, name: &str) -> bool {
2492        let current = self.stack.len() - 1;
2493        // A binding of the parameter scope does not answer for the body: the body's own
2494        // `arguments` (or self-name) still has to be provided for it.
2495        if self.stack[current]
2496            .vars
2497            .iter()
2498            .enumerate()
2499            .any(|(index, v)| {
2500                v.name == name
2501                    && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
2502            })
2503        {
2504            return false;
2505        }
2506        self.stack[current]
2507            .insns
2508            .iter()
2509            .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
2510    }
2511
2512    /// Bind the name a named function expression uses to refer to itself.
2513    ///
2514    /// The value is `special_object 2`, the function currently running, so the binding
2515    /// is the closure itself and not a copy. It is a local of this function, which is
2516    /// what keeps `g` out of the enclosing scope.
2517    /// Give the function a local `this`, for an arrow inside it to capture.
2518    fn provide_this_local(&mut self) {
2519        let current = self.stack.len() - 1;
2520        if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
2521            return;
2522        }
2523        if !self.stack[current]
2524            .vars
2525            .iter()
2526            .any(|var| var.name == "this")
2527        {
2528            self.declare_hidden_local("this", VarKind::Normal);
2529        }
2530        self.prepend_initialiser(
2531            "this",
2532            Insn::Fixed {
2533                op: Opcode::PushThis,
2534                operands: vec![],
2535            },
2536        );
2537    }
2538
2539    /// Give the function a local `<home_object>`, for an arrow or a static block inside it
2540    /// to read through `super`.
2541    fn provide_home_object_local(&mut self) {
2542        let current = self.stack.len() - 1;
2543        if !self.stack[current].needs_home_object_local {
2544            return;
2545        }
2546        if !self.stack[current]
2547            .vars
2548            .iter()
2549            .any(|var| var.name == HOME_OBJECT)
2550        {
2551            self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
2552        }
2553        self.prepend_initialiser(
2554            HOME_OBJECT,
2555            Insn::Fixed {
2556                op: Opcode::SpecialObject,
2557                operands: vec![Op::Int(4)],
2558            },
2559        );
2560    }
2561
2562    fn provide_self_name(&mut self) {
2563        let current = self.stack.len() - 1;
2564        let Some(name) = self.stack[current].self_name.clone() else {
2565            return;
2566        };
2567        if self.stack[current].self_name_initialized {
2568            return;
2569        }
2570        // Either the body refers to the name, or a nested function already forced the
2571        // binding into existence while being resolved. A direct `eval` can name it
2572        // without mentioning it, so its presence is a third reason: in strict mode
2573        // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
2574        // that only happens if the binding exists.
2575        let declared = self.stack[current].vars.iter().any(|v| v.name == name);
2576        if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
2577            return;
2578        }
2579        self.stack[current].self_name_initialized = true;
2580        self.prepend_binding_with(&name, 2, VarKind::FunctionName);
2581    }
2582
2583    /// Insert `special_object magic` plus the store to `name` at the top of the body.
2584    ///
2585    /// Prepending shifts every label that has been placed, so they are all moved by
2586    /// the number of instructions inserted.
2587    fn prepend_binding(&mut self, name: &str, magic: i32) {
2588        self.prepend_binding_with(name, magic, VarKind::Normal);
2589    }
2590
2591    /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
2592    fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
2593        let current = self.stack.len() - 1;
2594        // A function-expression's own name is immutable in strict mode, which is what
2595        // makes `f = 1` inside a strict body throw instead of being dropped.
2596        let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
2597        self.declare_var(
2598            name,
2599            VarDef {
2600                kind,
2601                is_const,
2602                ..VarDef::var(name)
2603            },
2604        );
2605        let init = [
2606            Insn::Fixed {
2607                op: Opcode::SpecialObject,
2608                operands: vec![Op::Int(magic)],
2609            },
2610            Insn::Var {
2611                // An initialisation, not an assignment: sloppy mode drops stores to a
2612                // function-expression's own name, and the prologue is what puts the
2613                // value there in the first place.
2614                action: if kind == VarKind::FunctionName {
2615                    VarAction::PutInit
2616                } else {
2617                    VarAction::Put
2618                },
2619                name: name.to_string(),
2620                block: 0,
2621                in_params: false,
2622            },
2623        ];
2624        let inserted = init.len();
2625        for (index, instruction) in init.into_iter().enumerate() {
2626            self.stack[current].insns.insert(index, instruction);
2627        }
2628        for placed in self.stack[current].labels.iter_mut().flatten() {
2629            *placed += inserted;
2630        }
2631        // A store sits at the insertion point now, so the `put`/`get` fold must not
2632        // reach across it.
2633        self.stack[current].label_since_insn = true;
2634    }
2635
2636    /// Record a top-level script declaration as a global.
2637    ///
2638    /// A script's top-level `var`/`let`/`function` create properties of the
2639    /// global object, not slots in the script's frame, so they show up as closure
2640    /// variables instead.
2641    fn declare_global(&mut self, name: &str, def: &VarDef) {
2642        let state = self.state();
2643        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2644            // The name was already referenced, from a function compiled before this
2645            // declaration was reached — `function a(){ b() } function b(){}` resolves
2646            // `b` while `b` is still unknown, and that guess has to be corrected here.
2647            // Leaving it as a plain global meant the declaration was never registered,
2648            // so the binding did not exist at run time and `a()` threw
2649            // `b is not defined`.
2650            if matches!(existing.closure_type, ClosureType::Global) {
2651                existing.closure_type = ClosureType::GlobalDecl;
2652                existing.is_const = def.is_const;
2653                existing.is_lexical = def.is_lexical;
2654            }
2655            return;
2656        }
2657        state.closure_vars.push(ClosureVar {
2658            name: name.to_string(),
2659            is_const: def.is_const,
2660            is_lexical: def.is_lexical,
2661            closure_type: ClosureType::GlobalDecl,
2662            var_idx: 0,
2663        });
2664    }
2665
2666    /// Record a module-level declaration as a module variable.
2667    ///
2668    /// The binding is a closure variable of the module body, so reads and writes are
2669    /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
2670    /// *who fills the cell*: the module record does, before the body runs, and an import
2671    /// points its cell at the exporting module's, which is what makes bindings live and
2672    /// cycles work.
2673    fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
2674        let state = self.state();
2675        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2676            // The name may have been referenced before this declaration was hoisted,
2677            // which resolved it as a plain global. Correct that here, the way
2678            // `declare_global` does.
2679            if matches!(existing.closure_type, ClosureType::Global) {
2680                existing.closure_type = ClosureType::ModuleDecl;
2681                existing.is_const = def.is_const;
2682                existing.is_lexical = def.is_lexical;
2683            }
2684            return 0;
2685        }
2686        state.closure_vars.push(ClosureVar {
2687            name: name.to_string(),
2688            is_const: def.is_const,
2689            is_lexical: def.is_lexical,
2690            closure_type: ClosureType::ModuleDecl,
2691            var_idx: 0,
2692        });
2693        0
2694    }
2695
2696    /// Declare a module variable and answer its closure-variable index.
2697    ///
2698    /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
2699    /// module variable is not one. The import table needs the real index instead, because
2700    /// that is the position the host writes the cell into.
2701    fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
2702        self.declare_module(name, def);
2703        self.cur()
2704            .closure_vars
2705            .iter()
2706            .position(|c| c.name == name)
2707            .map(|index| index as u32)
2708            .unwrap_or(0)
2709    }
2710
2711    /// Declare one imported binding as a module variable.
2712    ///
2713    /// Returns the closure-variable index, which is what the import table records: the
2714    /// host writes the exporter's cell into that slot before the body runs.
2715    fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
2716        let state = self.state();
2717        if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
2718            // Keep the slot, fix the kind: the name may already have been referenced.
2719            state.closure_vars[index].closure_type = ClosureType::ModuleImport;
2720            state.closure_vars[index].is_const = is_const;
2721            return index as u32;
2722        }
2723        state.closure_vars.push(ClosureVar {
2724            name: name.to_string(),
2725            // An imported binding cannot be assigned: `x = 1` on an import is a
2726            // `TypeError` at run time, which the const flag is what produces.
2727            is_const: true,
2728            // Lexical, so reads go through `get_var_ref_check`: before linking has filled
2729            // the cell an import is in its dead zone, and reading it there must say so
2730            // rather than answer `undefined`.
2731            is_lexical: true,
2732            closure_type: ClosureType::ModuleImport,
2733            var_idx: 0,
2734        });
2735        state.closure_vars.len() as u32 - 1
2736    }
2737
2738    /// Emit the code an `export` needs.
2739    ///
2740    /// Only `export default <expr>` has any: everything else is a table entry whose
2741    /// binding is declared elsewhere. The expression is stored into the hidden
2742    /// `*default*` variable rather than returned, because the module body has no value
2743    /// to speak of.
2744    fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2745        match &decl.kind {
2746            ExportKind::Declaration(stmt) => self.stmt(stmt),
2747            ExportKind::Default(expr) => {
2748                // A named default function/class is already a module binding; the export
2749                // points at it and there is nothing to evaluate.
2750                if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some())
2751                    || matches!(&expr.kind, ExprKind::Class(class) if class.name.is_some())
2752                {
2753                    return Ok(());
2754                }
2755                self.expr(expr)?;
2756                let index = self.declare_export_default();
2757                self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
2758                Ok(())
2759            }
2760            ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
2761        }
2762    }
2763
2764    /// A module name as the string it denotes.
2765    fn module_name_text(name: &ModuleName) -> &str {
2766        match name {
2767            ModuleName::Ident(ident) => &ident.name,
2768            ModuleName::Str(text) => text,
2769        }
2770    }
2771
2772    /// Bind `import`'s local names and record where each one comes from.
2773    ///
2774    /// Nothing is emitted: an import is not an instruction, it is a promise that the
2775    /// binding's cell will be filled before the body runs. The cell lands in the module's
2776    /// environment at a fixed index, and the host fills it from the exporter's cell —
2777    /// which is why a cyclic import can bind before the other module has evaluated.
2778    fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
2779        let request = self.module_request(&decl.source, &decl.attributes);
2780        for specifier in &decl.specifiers {
2781            let (local, name, is_star) = match specifier {
2782                ImportSpecifier::Default(ident) => {
2783                    (ident.name.clone(), "default".to_string(), false)
2784                }
2785                ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
2786                ImportSpecifier::Named { imported, local } => (
2787                    local.name.clone(),
2788                    Self::module_name_text(imported).to_string(),
2789                    false,
2790                ),
2791            };
2792            // `import * as ns` is *not* a live binding of another module's variable —
2793            // it is a value of its own, which is why the reference declares it like a
2794            // module variable and the host stores the namespace object in that cell.
2795            let var_idx = if is_star {
2796                // `const`: a namespace object is a value, and the binding is immutable.
2797                self.declare_module_var(&local, &VarDef::constant(local.clone()))
2798            } else {
2799                self.declare_import(&local, true)
2800            };
2801            self.module_meta().imports.push(ImportEntry {
2802                module: request,
2803                name,
2804                var_idx,
2805                is_star,
2806            });
2807        }
2808        Ok(())
2809    }
2810
2811    /// Record what an `export` offers, declaring the binding it exports.
2812    ///
2813    /// `export var x = 1` is a declaration like any other; only the table entry is extra.
2814    fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2815        match &decl.kind {
2816            ExportKind::Declaration(stmt) => {
2817                // The inner declaration keeps its own hoisting, then every name it binds
2818                // becomes an export of the same name.
2819                self.hoist_stmt(stmt)?;
2820                let mut names = Vec::new();
2821                Self::declared_names(stmt, &mut names);
2822                for name in names {
2823                    let var_idx = self.module_binding_index(&name);
2824                    self.exports_local(&name, var_idx);
2825                }
2826            }
2827            ExportKind::Default(expr) => {
2828                // The reference puts a default export in a hidden `*default*` variable,
2829                // so `export default function f(){}` can export a *value* while `f` stays
2830                // a binding of the module.
2831                if let ExprKind::Function(func) = &expr.kind
2832                    && let Some(name) = &func.name
2833                {
2834                    let text = name.name.clone();
2835                    self.hoist_stmt(&Stmt {
2836                        kind: StmtKind::FuncDecl(func.clone()),
2837                        span: expr.span,
2838                    })?;
2839                    let var_idx = self.module_binding_index(&text);
2840                    self.module_meta().exports.push(ExportEntry::Local {
2841                        export_name: "default".to_string(),
2842                        var_idx,
2843                    });
2844                    return Ok(());
2845                }
2846                if let ExprKind::Class(class) = &expr.kind
2847                    && let Some(name) = &class.name
2848                {
2849                    let text = name.name.clone();
2850                    self.hoist_stmt(&Stmt {
2851                        kind: StmtKind::ClassDecl(class.clone()),
2852                        span: expr.span,
2853                    })?;
2854                    let var_idx = self.module_binding_index(&text);
2855                    let _ = var_idx;
2856                }
2857                let var_idx = self.declare_export_default();
2858                self.module_meta().exports.push(ExportEntry::Local {
2859                    export_name: "default".to_string(),
2860                    var_idx,
2861                });
2862            }
2863            ExportKind::Named {
2864                specifiers,
2865                source,
2866                attributes,
2867            } => match source {
2868                Some(source) => {
2869                    let request = self.module_request(source, attributes);
2870                    for specifier in specifiers {
2871                        self.module_meta().exports.push(ExportEntry::Indirect {
2872                            export_name: Self::module_name_text(&specifier.exported).to_string(),
2873                            module: request,
2874                            import_name: Self::module_name_text(&specifier.local).to_string(),
2875                        });
2876                    }
2877                }
2878                None => {
2879                    for specifier in specifiers {
2880                        let local = Self::module_name_text(&specifier.local).to_string();
2881                        let var_idx = self.module_binding_index(&local);
2882                        let export_name = Self::module_name_text(&specifier.exported).to_string();
2883                        self.module_meta().exports.push(ExportEntry::Local {
2884                            export_name,
2885                            var_idx,
2886                        });
2887                    }
2888                }
2889            },
2890            ExportKind::All {
2891                source,
2892                exported,
2893                attributes,
2894            } => {
2895                let request = self.module_request(source, attributes);
2896                match exported {
2897                    Some(name) => {
2898                        self.module_meta().exports.push(ExportEntry::StarAs {
2899                            export_name: Self::module_name_text(name).to_string(),
2900                            module: request,
2901                        });
2902                    }
2903                    None => {
2904                        self.module_meta()
2905                            .exports
2906                            .push(ExportEntry::Star { module: request });
2907                    }
2908                }
2909            }
2910        }
2911        Ok(())
2912    }
2913
2914    /// The names a declaration binds, which is what `export <decl>` exports.
2915    fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
2916        match &stmt.kind {
2917            StmtKind::VarDecl(decl) => {
2918                for declarator in &decl.declarators {
2919                    let mut names = Vec::new();
2920                    declarator.target.bound_names(&mut names);
2921                    out.extend(names.into_iter().map(|name| name.name));
2922                }
2923            }
2924            StmtKind::FuncDecl(func) => {
2925                if let Some(name) = &func.name {
2926                    out.push(name.name.clone());
2927                }
2928            }
2929            StmtKind::ClassDecl(class) => {
2930                if let Some(name) = &class.name {
2931                    out.push(name.name.clone());
2932                }
2933            }
2934            _ => {}
2935        }
2936    }
2937
2938    /// The closure-variable index of a module binding, declaring it if the name was
2939    /// exported without being declared here.
2940    ///
2941    /// `export { x }` where `x` is not declared in the module is a link-time
2942    /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
2943    fn module_binding_index(&mut self, name: &str) -> u32 {
2944        if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
2945            return index as u32;
2946        }
2947        self.declare_module_var(name, &VarDef::lexical(name.to_string()))
2948    }
2949
2950    fn exports_local(&mut self, export_name: &str, var_idx: u32) {
2951        self.module_meta().exports.push(ExportEntry::Local {
2952            export_name: export_name.to_string(),
2953            var_idx,
2954        });
2955    }
2956
2957    /// The hidden `*default*` binding `export default <expr>` stores into.
2958    fn declare_export_default(&mut self) -> u32 {
2959        const DEFAULT: &str = "*default*";
2960        if let Some(index) = self
2961            .cur()
2962            .closure_vars
2963            .iter()
2964            .position(|c| c.name == DEFAULT)
2965        {
2966            return index as u32;
2967        }
2968        self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
2969    }
2970
2971    /// The module tables, which only the top-level state has.
2972    fn module_meta(&mut self) -> &mut ModuleMeta {
2973        self.state()
2974            .module
2975            .as_mut()
2976            .expect("module tables are only touched while compiling a module")
2977    }
2978
2979    /// The index of `specifier`'s request, adding it if it is new.
2980    ///
2981    /// Deduplicated on the specifier *and* its attributes: the same file imported once as
2982    /// JSON and once as text is two modules with two different contents, which is exactly
2983    /// what `hello_module.js` does.
2984    fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
2985        let attributes: Vec<(String, String)> = attributes
2986            .iter()
2987            .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
2988            .collect();
2989        let meta = self.module_meta();
2990        if let Some(index) = meta
2991            .requests
2992            .iter()
2993            .position(|request| request.specifier == specifier && request.attributes == attributes)
2994        {
2995            return index as u32;
2996        }
2997        meta.requests.push(ModuleRequest {
2998            specifier: specifier.to_string(),
2999            attributes,
3000        });
3001        meta.requests.len() as u32 - 1
3002    }
3003
3004    /// Compile a loop body with a `break`/`continue` target pushed for it.
3005    fn loop_body(
3006        &mut self,
3007        body: &Stmt,
3008        labels: &[String],
3009        continue_label: Label,
3010        break_label: Label,
3011    ) -> Result<(), SyntaxError> {
3012        self.push_jump_target(JumpTarget {
3013            names: labels.to_vec(),
3014            break_label: Some(break_label),
3015            continue_label: Some(continue_label),
3016            // A loop leaves nothing of its own on the value stack.
3017            drop_count: 0,
3018            finally_label: None,
3019            is_regular_stmt: false,
3020            has_iterator: false,
3021            is_async_iterator: false,
3022        });
3023        let result = self.stmt(body);
3024        self.pop_jump_target();
3025        result
3026    }
3027
3028    fn push_jump_target(&mut self, target: JumpTarget) {
3029        self.state().jump_targets.push(target);
3030    }
3031
3032    fn pop_jump_target(&mut self) {
3033        self.state().jump_targets.pop();
3034    }
3035
3036    fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3037        let (label, is_break) = match &stmt.kind {
3038            StmtKind::Break(label) => (label.as_ref(), true),
3039            StmtKind::Continue(label) => (label.as_ref(), false),
3040            _ => unreachable!("control_transfer is only called for break and continue"),
3041        };
3042
3043        // Walk outward from the innermost construct. Everything considered before
3044        // the match is a construct control is leaving, and leaving it has a cost:
3045        // its stack slots go, and its finalizer runs.
3046        let targets = self.cur().jump_targets.clone();
3047        for target in targets.iter().rev() {
3048            let destination = match (label, is_break) {
3049                // An unlabelled `break` skips a labelled non-loop statement: `break`
3050                // may name one, but the bare form only means "leave the loop".
3051                (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3052                (None, false) => target.continue_label,
3053                (Some(name), true) => target
3054                    .break_label
3055                    .filter(|_| target.names.contains(&name.name)),
3056                (Some(name), false) => target
3057                    .continue_label
3058                    .filter(|_| target.names.contains(&name.name)),
3059            };
3060
3061            if let Some(destination) = destination {
3062                self.emit_jump(Opcode::Goto, destination, &[]);
3063                return Ok(());
3064            }
3065
3066            // Closing the iterator consumes the three slots the loop keeps on the
3067            // stack (iterator, next method, catch offset), so those are not dropped
3068            // again below.
3069            let mut remaining = target.drop_count;
3070            if target.has_iterator {
3071                self.emit_iterator_close(target.is_async_iterator, false);
3072                remaining = remaining.saturating_sub(3);
3073            }
3074            for _ in 0..remaining {
3075                self.emit(Opcode::Drop, &[]);
3076            }
3077            if let Some(finally) = target.finally_label {
3078                // The finalizer runs as a subroutine and is handed a dummy return
3079                // value, which is dropped afterwards to keep the stack the depth it
3080                // had before.
3081                self.emit(Opcode::Undefined, &[]);
3082                self.emit_jump(Opcode::Gosub, finally, &[]);
3083                self.emit(Opcode::Drop, &[]);
3084            }
3085        }
3086
3087        // The parser rejects a break/continue with no target, so reaching here
3088        // means the compiler's own bookkeeping is wrong.
3089        Err(SyntaxError::new(
3090            if is_break {
3091                "break has no enclosing loop or switch"
3092            } else {
3093                "continue has no enclosing loop"
3094            },
3095            stmt.span,
3096        ))
3097    }
3098
3099    /// Compile a labelled statement.
3100    ///
3101    /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3102    /// that loop's targets, so the chain is collected and handed to the loop. A
3103    /// label on a non-loop statement only provides a `break` target, because
3104    /// `continue` may not target it.
3105    fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3106        let mut names = vec![label.name.clone()];
3107        let mut inner = body;
3108        while let StmtKind::Labeled {
3109            label: next,
3110            body: deeper,
3111        } = &inner.kind
3112        {
3113            names.push(next.name.clone());
3114            inner = deeper;
3115        }
3116        if Self::is_loop(inner) {
3117            return self.stmt_labelled(inner, &names);
3118        }
3119        let end = self.new_label();
3120        self.push_jump_target(JumpTarget {
3121            names,
3122            break_label: Some(end),
3123            continue_label: None,
3124            drop_count: 0,
3125            finally_label: None,
3126            is_regular_stmt: true,
3127            has_iterator: false,
3128            is_async_iterator: false,
3129        });
3130        let result = self.stmt(inner);
3131        self.pop_jump_target();
3132        result?;
3133        self.place_label(end);
3134        let _ = stmt;
3135        Ok(())
3136    }
3137
3138    /// Whether a statement is a loop, i.e. a valid target for `continue`.
3139    fn is_loop(stmt: &Stmt) -> bool {
3140        matches!(
3141            stmt.kind,
3142            StmtKind::While { .. }
3143                | StmtKind::DoWhile { .. }
3144                | StmtKind::For { .. }
3145                | StmtKind::ForIn { .. }
3146                | StmtKind::ForOf { .. }
3147        )
3148    }
3149
3150    /// Compile `switch`.
3151    ///
3152    /// The discriminant is evaluated once and stays on the value stack while the
3153    /// clauses compare against copies of it, so it is dropped at the end — which is
3154    /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3155    /// clause's body jumps over the *next* clause's tests straight into its body.
3156    ///
3157    /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3158    /// the next run's tests. Only the last run's miss reaches the `default` body, or
3159    /// the end of the switch when there is no `default`. That failure path can point
3160    /// backwards (`default` written first), so the runs and their labels are worked
3161    /// out before any code is emitted.
3162    fn switch(
3163        &mut self,
3164        discriminant: &Expr,
3165        cases: &[SwitchCase],
3166        stmt: &Stmt,
3167    ) -> Result<(), SyntaxError> {
3168        self.reset_value();
3169        // The discriminant is evaluated outside the switch's block scope, before
3170        // any `case` clause exists.
3171        self.expr(discriminant)?;
3172
3173        let switch_key = stmt.span.start.offset as u64;
3174        let switch_parent = self.cur().current_block;
3175        self.push_block(switch_key, switch_parent);
3176        self.emit_scope_enter(switch_key);
3177
3178        let break_label = self.new_label();
3179        self.push_jump_target(JumpTarget {
3180            names: Vec::new(),
3181            break_label: Some(break_label),
3182            // `switch` is a valid `break` target but not a `continue` target.
3183            continue_label: None,
3184            // The discriminant stays on the value stack for the whole statement, so
3185            // a `break` aimed further out has to discard it.
3186            drop_count: 1,
3187            finally_label: None,
3188            is_regular_stmt: false,
3189            has_iterator: false,
3190            is_async_iterator: false,
3191        });
3192
3193        // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3194        // its label to the clause after it, so both tests reach the same body.
3195        let mut runs: Vec<(usize, usize)> = Vec::new();
3196        let mut scan = 0;
3197        while scan < cases.len() {
3198            if cases[scan].test.is_some() {
3199                let mut last = scan;
3200                while last + 1 < cases.len()
3201                    && cases[last].test.is_some()
3202                    && cases[last].body.is_empty()
3203                    && cases[last + 1].test.is_some()
3204                {
3205                    last += 1;
3206                }
3207                runs.push((scan, last));
3208                scan = last + 1;
3209            } else {
3210                scan += 1;
3211            }
3212        }
3213
3214        let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3215        let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3216        let default_at = cases.iter().position(|case| case.test.is_none());
3217        // Where the last run sends control when nothing matched.
3218        let miss_target = match default_at {
3219            Some(index) => body_labels[index],
3220            None => break_label,
3221        };
3222
3223        // When `default` comes first, control has to jump over it to reach the
3224        // tests. It only needs to when some clause actually has a test; otherwise
3225        // the default body is the entry point.
3226        let mut entry = None;
3227        if default_at == Some(0) && !runs.is_empty() {
3228            self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3229            entry = Some(run_labels[0]);
3230        }
3231
3232        let mut index = 0;
3233        let mut run = 0;
3234        let result = (|| -> Result<(), SyntaxError> {
3235            while index < cases.len() {
3236                if cases[index].test.is_some() {
3237                    let (first, last) = runs[run];
3238                    // Reaching these tests from the preceding body is a
3239                    // fallthrough, which continues inside the body and skips them.
3240                    if index > 0 {
3241                        self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3242                    }
3243                    if let Some(label) = entry.take() {
3244                        self.place_label(label);
3245                    }
3246                    self.place_label(run_labels[run]);
3247
3248                    for (offset, case) in cases[first..=last].iter().enumerate() {
3249                        let test = case.test.as_ref().unwrap();
3250                        self.emit(Opcode::Dup, &[]);
3251                        self.expr(test)?;
3252                        self.emit(Opcode::StrictEq, &[]);
3253                        if first + offset < last {
3254                            self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3255                        } else {
3256                            // Hand over to the next run's tests, or give up.
3257                            let next = match runs.get(run + 1) {
3258                                Some(_) => run_labels[run + 1],
3259                                None => miss_target,
3260                            };
3261                            self.emit_jump(Opcode::IfFalse, next, &[]);
3262                        }
3263                    }
3264
3265                    self.place_label(body_labels[index]);
3266                    for case in &cases[first..=last] {
3267                        self.stmts(&case.body)?;
3268                    }
3269                    index = last + 1;
3270                    run += 1;
3271                } else {
3272                    // `default`: control arrives here either by falling through or
3273                    // because every test missed.
3274                    self.place_label(body_labels[index]);
3275                    self.stmts(&cases[index].body)?;
3276                    index += 1;
3277                }
3278            }
3279            Ok(())
3280        })();
3281
3282        if result.is_ok() {
3283            self.place_label(break_label);
3284            // Discard the discriminant now that no test needs it.
3285            self.emit(Opcode::Drop, &[]);
3286        }
3287
3288        self.pop_jump_target();
3289        self.emit_scope_leave(switch_key);
3290        self.state().current_block = switch_parent;
3291        result
3292    }
3293
3294    /// Compile `try`/`catch`/`finally`.
3295    ///
3296    /// The shape is an exception table built out of `catch` instructions, each of
3297    /// which records where control goes if the instructions that follow raise:
3298    ///
3299    /// ```text
3300    /// catch HANDLER            <- if the guarded block throws, jump to HANDLER
3301    ///   <guarded block>
3302    ///   drop                   <- discard the catch offset
3303    ///   undefined; gosub FINALLY; drop
3304    ///   goto END
3305    /// HANDLER:
3306    ///   <bind the catch parameter>
3307    ///   catch CATCH2           <- if the handler itself throws, go to CATCH2
3308    ///   <handler body>
3309    ///   drop; undefined; gosub FINALLY; drop; goto END
3310    /// CATCH2:
3311    ///   gosub FINALLY; throw   <- run the finalizer, then let the error out
3312    /// FINALLY:
3313    ///   <finalizer>
3314    ///   ret                    <- return to the `gosub`
3315    /// END:
3316    /// ```
3317    ///
3318    /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
3319    /// of the finalizer serves the normal path, the handler path and the
3320    /// propagating-exception path.
3321    ///
3322    /// The `undefined` before each `gosub` is a dummy return value: the finalizer
3323    /// runs with `ret_value` on the stack, and the normal path has no value to
3324    /// keep, so it pushes one to keep the stack depth identical on every path.
3325    fn try_stmt(
3326        &mut self,
3327        stmt: &Stmt,
3328        block: &[Stmt],
3329        handler: &Option<CatchClause>,
3330        finalizer: Option<&[Stmt]>,
3331    ) -> Result<(), SyntaxError> {
3332        self.reset_value();
3333
3334        let catch_label = self.new_label();
3335        let catch2_label = self.new_label();
3336        let finally_label = self.new_label();
3337        let end_label = self.new_label();
3338
3339        self.emit_jump(Opcode::Catch, catch_label, &[]);
3340
3341        // The guarded block. `break` may not target it, so its entry exists purely
3342        // to unwind: a jump out has to discard the catch offset and run the
3343        // finalizer.
3344        self.push_jump_target(JumpTarget {
3345            names: Vec::new(),
3346            break_label: None,
3347            continue_label: None,
3348            drop_count: 1,
3349            finally_label: Some(finally_label),
3350            is_regular_stmt: false,
3351            has_iterator: false,
3352            is_async_iterator: false,
3353        });
3354
3355        let block_key = Self::try_block_key(stmt, TryPart::Block);
3356        let block_parent = self.cur().current_block;
3357        self.push_block(block_key, block_parent);
3358        self.emit_scope_enter(block_key);
3359        self.stmts(block)?;
3360        self.emit_scope_leave(block_key);
3361        self.state().current_block = block_parent;
3362        // A guarded block that ends in a `return`/`throw` never reaches the
3363        // epilogue, so the reference does not emit one.
3364        self.pop_jump_target();
3365        let block_live = !block.last().is_some_and(Self::terminates);
3366
3367        if block_live {
3368            self.emit(Opcode::Drop, &[]);
3369            self.emit(Opcode::Undefined, &[]);
3370            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3371            self.emit(Opcode::Drop, &[]);
3372            self.emit_jump(Opcode::Goto, end_label, &[]);
3373        }
3374
3375        if let Some(handler) = handler {
3376            self.place_label(catch_label);
3377            // The thrown value is on top of the stack: bind it, or discard it for
3378            // `catch { }`.
3379            match &handler.param {
3380                Some(pattern) => {
3381                    // The stores resolve the names, so they have to run inside the
3382                    // parameter's own scope; otherwise a same-named `catch` further out
3383                    // could win. A `catch` binding is never in the dead zone, so the store
3384                    // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
3385                    let param_key = Self::try_block_key(stmt, TryPart::Param);
3386                    let param_parent = self.cur().current_block;
3387                    self.push_block(param_key, param_parent);
3388                    self.destructure(pattern, Some(VarDeclKind::Var))?;
3389                    self.state().current_block = param_parent;
3390                }
3391                None => self.emit(Opcode::Drop, &[]),
3392            }
3393            self.emit_jump(Opcode::Catch, catch2_label, &[]);
3394
3395            self.push_jump_target(JumpTarget {
3396                names: Vec::new(),
3397                break_label: None,
3398                continue_label: None,
3399                drop_count: 1,
3400                finally_label: Some(finally_label),
3401                is_regular_stmt: false,
3402                has_iterator: false,
3403                is_async_iterator: false,
3404            });
3405            let catch_key = Self::try_block_key(stmt, TryPart::Catch);
3406            let catch_parent = self.cur().current_block;
3407            self.push_block(catch_key, catch_parent);
3408            self.emit_scope_enter(catch_key);
3409            self.stmts(&handler.body)?;
3410            self.emit_scope_leave(catch_key);
3411            self.state().current_block = catch_parent;
3412            self.pop_jump_target();
3413            let handler_live = !handler.body.last().is_some_and(Self::terminates);
3414
3415            if handler_live {
3416                self.emit(Opcode::Drop, &[]);
3417                self.emit(Opcode::Undefined, &[]);
3418                self.emit_jump(Opcode::Gosub, finally_label, &[]);
3419                self.emit(Opcode::Drop, &[]);
3420                self.emit_jump(Opcode::Goto, end_label, &[]);
3421            }
3422
3423            // An error raised inside the handler still has to run the finalizer.
3424            self.place_label(catch2_label);
3425            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3426            self.emit(Opcode::Throw, &[]);
3427        } else {
3428            // `try`/`finally` with no handler: the finalizer runs, then the error
3429            // keeps propagating.
3430            self.place_label(catch_label);
3431            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3432            self.emit(Opcode::Throw, &[]);
3433        }
3434
3435        self.place_label(finally_label);
3436        // Inside the finalizer, leaving has a different cost: the return value and
3437        // the `gosub` return address are both on the stack, and neither finalizer nor
3438        // any outer one may run before the block has finished.
3439        self.push_jump_target(JumpTarget {
3440            names: Vec::new(),
3441            break_label: None,
3442            continue_label: None,
3443            drop_count: 2,
3444            finally_label: None,
3445            is_regular_stmt: false,
3446            has_iterator: false,
3447            is_async_iterator: false,
3448        });
3449        if let Some(finalizer) = finalizer {
3450            let finally_key = Self::try_block_key(stmt, TryPart::Finally);
3451            let finally_parent = self.cur().current_block;
3452            self.push_block(finally_key, finally_parent);
3453            self.emit_scope_enter(finally_key);
3454            self.stmts(finalizer)?;
3455            self.emit_scope_leave(finally_key);
3456            self.state().current_block = finally_parent;
3457        }
3458        self.pop_jump_target();
3459        self.emit(Opcode::Ret, &[]);
3460        self.place_label(end_label);
3461        Ok(())
3462    }
3463
3464    /// Compile `for`/`in` and `for`/`of`.
3465    ///
3466    /// Both keep an enumeration record on the value stack for the whole loop, which
3467    /// is what makes leaving early expensive: the record has to be dropped, or the
3468    /// iterator closed. The layout is
3469    ///
3470    /// ```text
3471    ///   <iterated expression>
3472    ///   for_in_start | for_of_start      <- pushes the record
3473    ///   goto TEST
3474    /// NEXT:
3475    ///   <bind the loop variable>
3476    ///   <body>
3477    /// TEST:
3478    ///   for_in_next | for_of_next 0
3479    ///   if_false NEXT                    <- not finished: next iteration
3480    ///   drop                             <- finished: discard the leftover value
3481    /// BREAK:
3482    ///   drop | iterator_close            <- the one cleanup `break` also uses
3483    /// ```
3484    ///
3485    /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
3486    /// normal exit share one copy — which is why `break` inside the loop emits nothing
3487    /// of its own, and only a jump that passes *through* the loop pays for its record.
3488    fn for_in_of(
3489        &mut self,
3490        stmt: &Stmt,
3491        left: &ForHead,
3492        right: &Expr,
3493        body: &Stmt,
3494        kind: ForLoopKind,
3495        labels: &[String],
3496    ) -> Result<(), SyntaxError> {
3497        self.reset_value();
3498
3499        let loop_key = stmt.span.start.offset as u64;
3500        let loop_parent = self.cur().current_block;
3501        self.push_block(loop_key, loop_parent);
3502        self.emit_scope_enter(loop_key);
3503
3504        // The iterated expression is evaluated inside the loop's scope, after the
3505        // bindings exist in the temporal dead zone.
3506        self.expr(right)?;
3507
3508        let next = self.new_label();
3509        let test = self.new_label();
3510        let break_target = self.new_label();
3511
3512        let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
3513        match kind {
3514            ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
3515            ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
3516            ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
3517        }
3518        self.emit_jump(Opcode::Goto, test, &[]);
3519
3520        self.push_jump_target(JumpTarget {
3521            // `outer: for (x of xs) … break outer` needs the name here. Without it the
3522            // loop had no label to break to, and the compiler reported "break has no
3523            // enclosing loop" for a loop that was plainly enclosing it.
3524            names: labels.to_vec(),
3525            break_label: Some(break_target),
3526            continue_label: Some(test),
3527            // Passing through the loop has to dispose of its record. A `for`/`of`
3528            // record is three slots, and closing the iterator consumes all of them.
3529            drop_count: if has_iterator { 3 } else { 1 },
3530            finally_label: None,
3531            is_regular_stmt: false,
3532            has_iterator,
3533            is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
3534        });
3535
3536        self.place_label(next);
3537        self.bind_loop_variable(left)?;
3538        // The reference marks the body with its own label here. Nothing jumps to it
3539        // once the loop is laid out, but it is not decoration: a label between the
3540        // store and the body is why `put_loc v; get_loc v` does *not* fold into
3541        // `set_loc v` when the body starts by reading the loop variable.
3542        let body_label = self.new_label();
3543        self.place_label(body_label);
3544        // `for (using x of …)` disposes once per iteration, so the body is a disposal
3545        // region rather than the whole loop: the resource is the element that this
3546        // iteration produced.
3547        let using_slot = match left {
3548            ForHead::VarDecl(decl) if decl.kind.is_using() => {
3549                decl.declarators
3550                    .first()
3551                    .and_then(|declarator| match &declarator.target.kind {
3552                        PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
3553                        _ => None,
3554                    })
3555            }
3556            _ => None,
3557        };
3558        match using_slot {
3559            Some(slot) => {
3560                let live = !Self::terminates(body);
3561                self.using_region_around(slot, live, |compiler| compiler.stmt(body))?;
3562            }
3563            None => self.stmt(body)?,
3564        }
3565
3566        self.place_label(test);
3567        match kind {
3568            ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
3569            ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
3570            ForLoopKind::AwaitOf => {
3571                // The reference's shape: step, `await` the result, then unpack it.
3572                self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
3573                self.emit(Opcode::Await, &[]);
3574                self.state().has_await = true;
3575                self.emit(Opcode::IteratorGetValueDone, &[]);
3576            }
3577        }
3578        self.emit_jump(Opcode::IfFalse, next, &[]);
3579        // The loop is finished; `for_xx_next` left an `undefined` behind.
3580        self.emit(Opcode::Drop, &[]);
3581
3582        self.pop_jump_target();
3583        self.place_label(break_target);
3584        if has_iterator {
3585            // A loop that ran to completion finds its iterator slot already cleared (see
3586            // `iterator_get_value_done`), so this closes only an iterator abandoned by a
3587            // `break` that jumped here.
3588            self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
3589        } else {
3590            self.emit(Opcode::Drop, &[]);
3591        }
3592
3593        self.emit_scope_leave(loop_key);
3594        self.state().current_block = loop_parent;
3595        Ok(())
3596    }
3597
3598    /// Store the value `for_xx_next` left on the stack into the loop variable.
3599    fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
3600        // A declaration *initialises* the binding, which is what takes a `let` out of
3601        // the temporal dead zone, so the store is the unchecked form. Assigning to a
3602        // binding declared elsewhere is an ordinary write and keeps its check.
3603        let (pattern, action) = match left {
3604            ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
3605            ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
3606        };
3607        match &pattern.kind {
3608            PatternKind::Ident(name) => {
3609                // `for (using x of …)` validates and snapshots each iteration's value
3610                // before the body runs, which is what makes a non-disposable element fail
3611                // on the iteration that produced it rather than at the end of the loop.
3612                if let ForHead::VarDecl(decl) = left
3613                    && decl.kind.is_using()
3614                {
3615                    let method_slot = self
3616                        .using_method_slot(&name.name)
3617                        .expect("a using binding was declared during hoisting");
3618                    self.emit(
3619                        Opcode::UsingCheck,
3620                        &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3621                    );
3622                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3623                }
3624                self.emit_var(action, &name.name);
3625                Ok(())
3626            }
3627            // Every other target stores through the same path an assignment pattern
3628            // uses, which is what makes `for (a[0] in obj)` write each key into the
3629            // property instead of refusing the loop outright.
3630            _ => self.destructure(
3631                pattern,
3632                match left {
3633                    ForHead::VarDecl(decl) => Some(decl.kind),
3634                    ForHead::Assign(_) => None,
3635                },
3636            ),
3637        }
3638    }
3639
3640    fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
3641        for declarator in &decl.declarators {
3642            let Some(init) = &declarator.init else {
3643                // `var x;` stays `undefined`. A lexical binding is different: it
3644                // has to be *initialised* to leave the temporal dead zone, so the
3645                // compiler supplies an explicit `undefined`.
3646                if decl.kind.is_lexical() {
3647                    // A lexical binding has to be *initialised* to leave the temporal
3648                    // dead zone, and a destructuring one is no different — `let {a}`
3649                    // with no initialiser is a syntax error, but `let [a] = []` still
3650                    // needs `a` to be initialised from an empty source, which the
3651                    // pattern does on its own.
3652                    self.emit(Opcode::Undefined, &[]);
3653                    self.destructure(&declarator.target, Some(decl.kind))?;
3654                }
3655                continue;
3656            };
3657            match &declarator.target.kind {
3658                PatternKind::Ident(name) => {
3659                    self.expr(init)?;
3660                    self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
3661                    if decl.kind.is_using() {
3662                        // `using_check` validates the value and snapshots its dispose
3663                        // method: `value -> value, method`. The snapshot is what makes a
3664                        // later change to `Symbol.dispose` irrelevant, and validating here
3665                        // is what keeps the body from running at all when the value is not
3666                        // disposable.
3667                        let method_slot = self
3668                            .using_method_slot(&name.name)
3669                            .expect("a using binding was declared during hoisting");
3670                        self.emit(
3671                            Opcode::UsingCheck,
3672                            &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3673                        );
3674                        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3675                        self.emit_var(VarAction::PutInit, &name.name);
3676                        continue;
3677                    }
3678                    // A declaration statement produces no value, so nothing is
3679                    // duplicated onto the stack.
3680                    match decl.kind {
3681                        VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
3682                        _ => self.emit_var(VarAction::PutInit, &name.name),
3683                    }
3684                }
3685                _ => {
3686                    // A destructuring declaration keeps nothing on the stack: the
3687                    // pattern consumes the initialiser.
3688                    self.expr(init)?;
3689                    self.destructure(&declarator.target, Some(decl.kind))?;
3690                }
3691            }
3692        }
3693        Ok(())
3694    }
3695
3696    /// Bind a destructuring pattern from the value on top of the stack.
3697    ///
3698    /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
3699    /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
3700    /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
3701    /// *assignment*, where a member expression is a legal target and the store is an
3702    /// ordinary property write.
3703    ///
3704    /// The value is consumed. An assignment expression's own result is the right-hand
3705    /// side, which the caller keeps separately — the spec does not make the pattern's
3706    /// last store produce it.
3707    fn destructure(
3708        &mut self,
3709        pattern: &Pattern,
3710        decl: Option<VarDeclKind>,
3711    ) -> Result<(), SyntaxError> {
3712        match &pattern.kind {
3713            PatternKind::Ident(name) => {
3714                match decl {
3715                    Some(VarDeclKind::Var) | None => {
3716                        self.emit_var(VarAction::Put, &name.name);
3717                    }
3718                    Some(_) => self.emit_var(VarAction::PutInit, &name.name),
3719                }
3720                Ok(())
3721            }
3722            PatternKind::Assign { target, default } => {
3723                // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
3724                // keeps `null`.
3725                //
3726                // The shape is the reference's: test for `undefined`, and when the value is
3727                // present fall **through** to a single store both paths share. The
3728                // alternatives — branching to the store on each side — need a second store
3729                // and a jump between them, which is what the dump used to show.
3730                let has_value = self.new_label();
3731                self.emit(Opcode::Dup, &[]);
3732                self.emit(Opcode::IsUndefined, &[]);
3733                self.emit_jump(Opcode::IfFalse, has_value, &[]);
3734                self.emit(Opcode::Drop, &[]);
3735                self.expr(default)?;
3736                // `var {f = function(){}} = {}` names the function `f`, like a plain
3737                // `var f = function(){}` does. Both pattern forms do it:
3738                // `BindingInitialization` names the value for a *binding* target, and since
3739                // ES2018 `DestructuringAssignmentEvaluation` does the same, so
3740                // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
3741                // no name to give, which is why only an identifier qualifies.
3742                if let PatternKind::Ident(name) = &target.kind {
3743                    self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
3744                }
3745                self.place_label(has_value);
3746                self.destructure(target, decl)
3747            }
3748            PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
3749            PatternKind::Object { properties, rest } => {
3750                self.destructure_object(properties, rest, decl, pattern)
3751            }
3752            PatternKind::Member(member) if decl.is_none() => {
3753                // An assignment pattern may store into a property. The value is on the
3754                // stack, so the receiver and the key go above it and `rot3l`/`swap2`
3755                // put the three in the order `put_array_el`/`put_field` expect.
3756                self.expr(&member.object)?;
3757                match &member.property {
3758                    MemberProp::Ident(name) => {
3759                        // `value obj` -> `obj value`, the order `put_field` takes.
3760                        // Nothing needs to be left behind: a pattern element's value is
3761                        // consumed by its own store.
3762                        self.emit(Opcode::Swap, &[]);
3763                        self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
3764                    }
3765                    MemberProp::Computed(index) => {
3766                        self.expr(index)?;
3767                        // `value obj key` -> `obj key value`.
3768                        self.emit(Opcode::Rot3l, &[]);
3769                        self.emit(Opcode::PutArrayEl, &[]);
3770                    }
3771                    MemberProp::Private(name) => {
3772                        // `value obj` -> `obj value`, and the store half of the assignment is
3773                        // the same one `obj.#x = value` uses — only without `insert2`,
3774                        // because a pattern element's value is not wanted back.
3775                        let binding = format!("#{}", name.name);
3776                        let (kind, setter) = self.private_use(&binding, member.span)?;
3777                        self.emit(Opcode::Swap, &[]);
3778                        self.private_store(&binding, kind, setter.as_deref())?;
3779                    }
3780                }
3781                Ok(())
3782            }
3783            PatternKind::Rest(inner) => self.destructure(inner, decl),
3784            PatternKind::Invalid(expr) => {
3785                Err(SyntaxError::new("invalid assignment target", expr.span))
3786            }
3787            _ => Err(SyntaxError::new(
3788                "this destructuring target is not supported by the compiler yet",
3789                pattern.span,
3790            )),
3791        }
3792    }
3793
3794    /// `[…]` on the left: drain an iterator, binding one target per element.
3795    fn destructure_array(
3796        &mut self,
3797        elements: &[Option<PatternElement>],
3798        rest: &Option<Box<RestElement>>,
3799        decl: Option<VarDeclKind>,
3800    ) -> Result<(), SyntaxError> {
3801        // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
3802        // pattern accepts any iterable and closes the iterator when the pattern ends
3803        // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
3804        // first because it is on top.
3805        self.emit(Opcode::ForOfStart, &[]);
3806        for element in elements {
3807            self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
3808            self.emit(Opcode::Drop, &[]);
3809            match element {
3810                Some(PatternElement::Pattern(pattern)) => self.destructure(pattern, decl)?,
3811                Some(PatternElement::Property { span, .. }) => {
3812                    return Err(SyntaxError::new(
3813                        "a property pattern is not a valid array element",
3814                        *span,
3815                    ));
3816                }
3817                // An elision skips the value, which is already on the stack.
3818                None => self.emit(Opcode::Drop, &[]),
3819            }
3820        }
3821        if let Some(rest) = rest {
3822            // The remaining values go into a fresh array. The target and its running
3823            // index stay on the stack above the iterator, which is what the operand of
3824            // `for_of_next` accounts for: two values sit above the iterator triple.
3825            self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
3826            self.emit(Opcode::Push0, &[]);
3827            let top = self.new_label();
3828            self.place_label(top);
3829            self.emit(Opcode::ForOfNext, &[Op::Int(2)]);
3830            let done = self.new_label();
3831            self.emit_jump(Opcode::IfTrue, done, &[]);
3832            self.emit(Opcode::DefineArrayEl, &[]);
3833            self.emit(Opcode::Inc, &[]);
3834            self.emit_jump(Opcode::Goto, top, &[]);
3835            self.place_label(done);
3836            self.emit(Opcode::Drop, &[]);
3837            self.emit(Opcode::Drop, &[]);
3838            self.destructure_rest(rest, decl)?;
3839        }
3840        self.emit(Opcode::IteratorClose, &[]);
3841        Ok(())
3842    }
3843
3844    /// `{…}` on the left: read properties off one boxed source object.
3845    fn destructure_object(
3846        &mut self,
3847        properties: &[Option<PatternElement>],
3848        rest: &Option<Box<RestElement>>,
3849        decl: Option<VarDeclKind>,
3850        pattern: &Pattern,
3851    ) -> Result<(), SyntaxError> {
3852        // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
3853        // aside for the rest element below.
3854        self.emit(Opcode::ToObject, &[]);
3855        let mut taken: Vec<Wtf8> = Vec::new();
3856        // Whether any key was computed, which a rest element cannot exclude.
3857        let mut computed = false;
3858        for property in properties {
3859            let Some(PatternElement::Property {
3860                key, value, span, ..
3861            }) = property
3862            else {
3863                return Err(SyntaxError::new(
3864                    "a bare pattern is not a valid object property",
3865                    properties
3866                        .iter()
3867                        .flatten()
3868                        .map(|element| match element {
3869                            PatternElement::Pattern(pattern) => pattern.span,
3870                            PatternElement::Property { span, .. } => *span,
3871                        })
3872                        .next()
3873                        .unwrap_or(pattern.span),
3874                ));
3875            };
3876            // Every read needs the source twice: to read from, and to keep for the next
3877            // property. `get_field2` is that duplicate-and-read in one instruction, but it
3878            // leaves the copy *under* the value, so it is only usable when whatever
3879            // consumes the value tolerates that. See [`reads_with_get_field2`].
3880            let nested = reads_with_get_field2(decl, value);
3881            if !nested {
3882                self.emit(Opcode::Dup, &[]);
3883            }
3884            match key {
3885                PropName::Literal(literal) => {
3886                    let name = self.property_key_text(literal, *span)?;
3887                    taken.push(name.clone());
3888                    self.emit(
3889                        if nested {
3890                            Opcode::GetField2
3891                        } else {
3892                            Opcode::GetField
3893                        },
3894                        &[Op::Atom(Atom::from_wtf8(&name))],
3895                    );
3896                }
3897                PropName::Computed(index) => {
3898                    // A computed key has no name to exclude ahead of time, so a rest
3899                    // element that has to skip it is refused below rather than silently
3900                    // copying the property into the rest object.
3901                    computed = true;
3902                    self.expr(index)?;
3903                    self.emit(Opcode::GetArrayEl, &[]);
3904                }
3905                PropName::Private(_) => {
3906                    return Err(SyntaxError::new(
3907                        "private fields are not supported by the compiler yet",
3908                        value.span,
3909                    ));
3910                }
3911            }
3912            self.destructure(value, decl)?;
3913        }
3914        match rest {
3915            Some(rest) => {
3916                if computed {
3917                    return Err(SyntaxError::new(
3918                        "a computed key with a rest element is not supported by the compiler yet",
3919                        Self::rest_span(rest),
3920                    ));
3921                }
3922                // `target src exclude`: the exclusion list is an array of the keys the
3923                // literal part already took, so the rest object gets only the others.
3924                self.emit(Opcode::Object, &[]);
3925                self.emit(Opcode::Swap, &[]);
3926                for name in &taken {
3927                    self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
3928                }
3929                self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
3930                self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
3931                self.emit(Opcode::Drop, &[]);
3932                self.emit(Opcode::Drop, &[]);
3933                self.destructure_rest(rest, decl)?;
3934            }
3935            // The source was only kept for a rest element.
3936            None => self.emit(Opcode::Drop, &[]),
3937        }
3938        Ok(())
3939    }
3940
3941    /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
3942    fn destructure_rest(
3943        &mut self,
3944        rest: &RestElement,
3945        decl: Option<VarDeclKind>,
3946    ) -> Result<(), SyntaxError> {
3947        match rest {
3948            RestElement::Pattern(pattern) => self.destructure(pattern, decl),
3949            // `[...a.b] = c` stores into a property.
3950            RestElement::Member(member) => {
3951                let pattern = Pattern {
3952                    kind: PatternKind::Member(member.clone()),
3953                    span: member.span,
3954                };
3955                self.destructure(&pattern, decl)
3956            }
3957        }
3958    }
3959
3960    /// The source range of a rest element, for error messages.
3961    fn rest_span(rest: &RestElement) -> Span {
3962        match rest {
3963            RestElement::Pattern(pattern) => pattern.span,
3964            RestElement::Member(member) => member.span,
3965        }
3966    }
3967
3968    /// Compile a function declaration and queue it for instantiation at scope
3969    /// entry.
3970    ///
3971    /// A declaration is visible before the statement that declares it, so the
3972    /// code that creates the function object belongs at the top of the enclosing
3973    /// scope, not at the declaration.
3974    fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
3975        let name = func.name.as_ref().expect("a declaration has a name");
3976        let function = self.compile_function(func)?;
3977        let pool_index = self.push_constant(Constant::Function(Box::new(function)));
3978        let target = self.hoist_target(&name.name);
3979        let block = self.cur().current_block;
3980        self.state().hoisted.push((block, target, pool_index));
3981        Ok(())
3982    }
3983
3984    /// Where a name lives, for a hoisted declaration.
3985    fn hoist_target(&self, name: &str) -> HoistTarget {
3986        let state = self.cur();
3987        if let Some(index) = state.args.iter().position(|a| a.name == name) {
3988            return HoistTarget::Arg(index as u32);
3989        }
3990        if let Some(index) = state.vars.iter().position(|v| v.name == name) {
3991            return HoistTarget::Loc(index as u32);
3992        }
3993        // A global function declaration is not a slot at all.
3994        HoistTarget::Global(name.to_string())
3995    }
3996
3997    // -- expressions -------------------------------------------------------
3998
3999    /// Compile one expression, recording where its instructions sit.
4000    ///
4001    /// The position is the node's operator when it has one and its first token
4002    /// otherwise, and it is restored on the way out so a parent's own instructions —
4003    /// which are emitted *after* its children — are blamed on the parent. Without the
4004    /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4005    fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4006        let saved = self.cur().cur_pos;
4007        // Only the node kinds the reference calls `emit_source_pos` for record a position:
4008        // the operator a node exists for, and a variable *read*, which the reference
4009        // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4010        // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4011        // start, a parenthesised group, an anonymous function expression — leaves the
4012        // previous position in place, because a table entry the reference never writes is
4013        // one we must not write either: the instruction that inherits a position (the
4014        // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4015        // report a more recent token than the reference does.
4016        let pos = expr.op_pos.or(match &expr.kind {
4017            ExprKind::Ident(ident) => Some(ident.span.start),
4018            _ => None,
4019        });
4020        match pos {
4021            Some(pos) => self.state().cur_pos = Some(pos),
4022            // A node the reference records nothing for: its own instructions stay
4023            // unpositioned, so they inherit whatever was written last — which is what an
4024            // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4025            // enclosing position instead would blame them on a token the reference has not
4026            // reached yet: a spread's `iterator_open` reports the expression it follows, and
4027            // a template's `to_propkey` the interpolation.
4028            None => self.state().cur_pos = None,
4029        }
4030        // Note a direct `eval` call before compiling it, because the *whole* function
4031        // is affected: an eval can name any binding the function declares, so every one
4032        // of them has to live in a cell for a closure it creates to capture it.
4033        if Self::is_direct_eval(expr) {
4034            // Every enclosing function is affected too: the eval sees the whole scope
4035            // chain, and a closure it creates can capture a binding of any of them.
4036            // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a
4037            // cell, because the closure the eval builds outlives the loop iteration.
4038            for state in &mut self.stack {
4039                state.has_direct_eval = true;
4040            }
4041            let block = self.cur().current_block;
4042            let in_params = self.cur().in_params;
4043            self.state()
4044                .pending_eval_sites
4045                .push((expr.span, block, in_params));
4046        }
4047        let result = self.expr_inner(expr);
4048        self.state().cur_pos = saved;
4049        result
4050    }
4051
4052    /// Record which bindings are in scope at a direct `eval` call.
4053    ///
4054    /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
4055    /// resolves names from a string at run time, so the only chance to pin down *which*
4056    /// slot a name means is here. Visibility is the lexical rule: a binding counts when
4057    /// its block is the current block, an enclosing one, or the function scope.
4058    fn materialize_eval_sites(&mut self) {
4059        let pending = std::mem::take(&mut self.state().pending_eval_sites);
4060        for (span, site_block, in_params) in pending {
4061            self.resolve_eval_site(span, site_block, in_params);
4062        }
4063    }
4064
4065    /// Resolve the bindings visible at one `eval` call.
4066    fn resolve_eval_site(&mut self, span: Span, site_block: u64, site_in_params: bool) {
4067        /// How near a binding is: function distance first, then block depth, then the
4068        /// later declaration (which shadows the earlier one in the same block).
4069        type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
4070
4071        // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
4072        // walked, innermost function first: a direct `eval` sees every enclosing
4073        // function's bindings, and none of them can be resolved at run time because the
4074        // runtime only has names to go on.
4075        let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
4076        let deepest = self.stack.len() - 1;
4077        for (level, state) in self.stack.iter().enumerate().rev() {
4078            let owner = (deepest - level) as u32;
4079            // The innermost function's block is the one the call sat in, which is not
4080            // the block the compiler is in now; the enclosing functions are still at
4081            // the point where this one was created.
4082            let here = if level == deepest {
4083                site_block
4084            } else {
4085                state.current_block
4086            };
4087            // The chain of live blocks, innermost first, with a depth for each. The walk
4088            // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
4089            // block can start at source offset zero.
4090            let mut live: Vec<(u64, usize)> = vec![(here, 0)];
4091            let mut block = here;
4092            while let Some(parent) = state
4093                .blocks
4094                .iter()
4095                .find(|candidate| candidate.key == block)
4096                .map(|candidate| candidate.parent)
4097                .filter(|parent| *parent != NO_PARENT)
4098                .filter(|parent| parent != &block)
4099            {
4100                live.push((parent, live.len()));
4101                block = parent;
4102            }
4103            let depth_of = |key: u64| {
4104                live.iter()
4105                    .find(|(candidate, _)| *candidate == key)
4106                    .map(|(_, depth)| *depth)
4107                    // The function scope is the outermost depth there is. A binding of a
4108                    // block this site is not inside lands here too, which pushes it
4109                    // behind every live one — the right answer: it is out of scope.
4110                    .unwrap_or(live.len())
4111            };
4112            for (index, arg) in state.args.iter().enumerate() {
4113                bindings.push((
4114                    (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
4115                    EvalVisible {
4116                        name: arg.name.clone(),
4117                        is_arg: true,
4118                        index: index as u32,
4119                        owner,
4120                    },
4121                ));
4122            }
4123            // A parameter list cannot see the body, so a body `var` is not a binding the
4124            // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
4125            // not let that eval write the body's `c`.
4126            let hides_body = if level == deepest {
4127                site_in_params
4128            } else {
4129                state.created_in_params
4130            };
4131            for (index, var) in state.vars.iter().enumerate() {
4132                let block = state
4133                    .var_block
4134                    .get(index)
4135                    .copied()
4136                    .unwrap_or(FUNCTION_SCOPE);
4137                if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
4138                    continue;
4139                }
4140                bindings.push((
4141                    (
4142                        owner as usize,
4143                        depth_of(block),
4144                        std::cmp::Reverse(index as u32),
4145                    ),
4146                    EvalVisible {
4147                        name: var.name.clone(),
4148                        is_arg: false,
4149                        index: index as u32,
4150                        owner,
4151                    },
4152                ));
4153            }
4154        }
4155        // Innermost function first, then innermost block, then the later declaration
4156        // (which shadows the earlier one within a block).
4157        bindings.sort_by_key(|(priority, _)| *priority);
4158        let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
4159        self.state().eval_sites.push(EvalSite {
4160            line: span.start.line,
4161            column: span.start.column,
4162            bindings,
4163        });
4164    }
4165
4166    /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
4167    ///
4168    /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
4169    /// a bare identifier callee counts.
4170    fn is_direct_eval(expr: &Expr) -> bool {
4171        matches!(
4172            &expr.kind,
4173            ExprKind::Call { callee, .. }
4174                if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
4175        )
4176    }
4177
4178    fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4179        match &expr.kind {
4180            ExprKind::Number(value) => self.push_number(*value),
4181            ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
4182            ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
4183            ExprKind::Null => self.emit(Opcode::Null, &[]),
4184            ExprKind::String(text) => self.push_string(text),
4185            ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
4186            ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
4187            ExprKind::This => self.this_expression(),
4188            ExprKind::NewTarget => self.new_target_expression(),
4189            ExprKind::Paren(inner) => self.expr(inner)?,
4190            ExprKind::Binary { op, left, right } => {
4191                self.expr(left)?;
4192                self.expr(right)?;
4193                self.emit(binary_opcode(*op), &[]);
4194            }
4195            ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
4196            ExprKind::Unary {
4197                op: UnaryOp::Minus,
4198                argument,
4199            } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
4200                let ExprKind::Number(value) = argument.unparen().kind else {
4201                    unreachable!("matched above")
4202                };
4203                // The reference folds a negative literal only when the negation is
4204                // exact in the integer range: `-1` becomes `push_minus1` and
4205                // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
4206                // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
4207                // `-Infinity`, not `Infinity` — and folding a fraction would change
4208                // which instruction the reference emits.
4209                let negated = -value;
4210                // `-2147483648` is deliberately excluded: its magnitude is one past
4211                // `i32::MAX`, so the reference sends it through the constant pool and
4212                // negates at run time instead.
4213                if value > 0.0
4214                    && negated == negated.trunc()
4215                    && negated >= -(i32::MAX as f64)
4216                    && negated < 0.0
4217                {
4218                    self.push_number(negated);
4219                } else {
4220                    self.push_number(value);
4221                    self.emit(Opcode::Neg, &[]);
4222                }
4223            }
4224            ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
4225            ExprKind::Conditional { test, cons, alt } => {
4226                let else_label = self.new_label();
4227                let end_label = self.new_label();
4228                self.expr(test)?;
4229                self.emit_jump(Opcode::IfFalse, else_label, &[]);
4230                self.expr(cons)?;
4231                self.emit_jump(Opcode::Goto, end_label, &[]);
4232                self.place_label(else_label);
4233                self.expr(alt)?;
4234                self.place_label(end_label);
4235            }
4236            ExprKind::Assign { op, target, value } => self.assign(*op, target, value)?,
4237            ExprKind::Update {
4238                op,
4239                argument,
4240                prefix,
4241            } => self.update(*op, argument, *prefix)?,
4242            ExprKind::Sequence(items) => {
4243                for (index, item) in items.iter().enumerate() {
4244                    self.expr(item)?;
4245                    if index + 1 != items.len() {
4246                        self.emit(Opcode::Drop, &[]);
4247                    }
4248                }
4249            }
4250            ExprKind::Call { .. } => self.chain_link_top(expr)?,
4251            ExprKind::Member { .. } => self.chain_link_top(expr)?,
4252            ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
4253            ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
4254            ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
4255            ExprKind::Template(template) => self.template_literal(template)?,
4256            ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
4257            ExprKind::New { callee, arguments } => {
4258                // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
4259                // The `dup` is not redundant: `call_constructor` takes the
4260                // constructor twice, once as the target and once as `new.target`,
4261                // which is what makes `new.target === C` inside the body.
4262                self.expr(callee)?;
4263                self.emit(Opcode::Dup, &[]);
4264                let args = arguments.as_deref().unwrap_or(&[]);
4265                if Self::has_spread(args) {
4266                    // `C C array`: the duplicated callee is already both the target
4267                    // and `new.target`, so no reordering is needed before `apply 1`.
4268                    self.argument_array(args)?;
4269                    self.emit(Opcode::Apply, &[Op::Int(1)]);
4270                    return Ok(());
4271                }
4272                for argument in args {
4273                    self.expr(argument)?;
4274                }
4275                self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
4276            }
4277            ExprKind::Class(class) => self.class_definition(class, true)?,
4278            ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
4279            ExprKind::Yield { argument, delegate } => {
4280                self.yield_expression(argument.as_deref(), *delegate)?
4281            }
4282            ExprKind::Await(argument) => self.await_expression(argument)?,
4283            ExprKind::RegExp { pattern, flags } => {
4284                // A literal is compiled *here*, at parse time, not when the line runs. The
4285                // spec is explicit that an invalid pattern is an early error (§12.9.4:
4286                // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
4287                // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
4288                // also validates `\p{…}` names: 163 conformance cases are patterns that have
4289                // to be rejected before any code runs.
4290                //
4291                // This is the whole reason the engine lives in its own crate rather than
4292                // inside `quickjs-pure`: the compiler could not depend on the interpreter
4293                // (`pure` depends on `compile`), but both need this.
4294                // The lexer already rejected an unknown or repeated flag, so an unparsable
4295                // flag string here would be a bug in the lexer rather than in the script;
4296                // fall back to the default flags instead of inventing a second message.
4297                let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
4298                let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
4299                    SyntaxError::new(
4300                        format!("invalid regular expression: {}", error.message),
4301                        expr.span,
4302                    )
4303                })?;
4304                // The tree is thrown away and rebuilt when the literal first runs: keeping it
4305                // would mean serialising the syntax tree into the function's constant pool,
4306                // and a literal is created once per evaluation of its expression anyway.
4307                let _ = parsed;
4308                // The pattern and its flags travel as two string constants; `regexp` builds
4309                // the object. A dedicated opcode (rather than a call to the constructor) is
4310                // what the reference does too, so that a literal never goes through the
4311                // public `RegExp` function and its string-coercion rules.
4312                self.push_string(&Wtf8::new(pattern));
4313                self.push_string(&Wtf8::new(flags));
4314                self.emit(Opcode::Regexp, &[]);
4315            }
4316            ExprKind::Arrow(func) => {
4317                let function = self.compile_function(func)?;
4318                let index = self.push_constant(Constant::Function(Box::new(function)));
4319                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4320            }
4321            ExprKind::Function(func) => {
4322                let function = self.compile_function_with_name(func, true)?;
4323                let index = self.push_constant(Constant::Function(Box::new(function)));
4324                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4325            }
4326            // `import.meta`: the host fills a per-module object at link time.
4327            ExprKind::ImportMeta => {
4328                self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
4329            }
4330            // `import("x")` compiles to a two-slot push followed by one opcode: the
4331            // specifier, then the options object (`undefined` here, since this compiler
4332            // does not accept the second argument yet).
4333            ExprKind::ImportCall(specifier) => {
4334                self.expr(specifier)?;
4335                self.emit(Opcode::Undefined, &[]);
4336                self.emit(Opcode::Import, &[]);
4337            }
4338            ExprKind::PrivateIn { name, object } => {
4339                // `#x in o`: the object, then the binding, then one opcode which decides what
4340                // to do with the second operand. A field's binding holds a symbol and the
4341                // answer is an own-property test; a method's holds a function and the answer
4342                // is a brand check — both live in `private_in`, so the compiler emits the
4343                // same instruction for either.
4344                self.expr(object)?;
4345                self.emit_var(VarAction::Get, &format!("#{}", name.name));
4346                self.emit(Opcode::PrivateIn, &[]);
4347            }
4348            _ => {
4349                return Err(SyntaxError::new(
4350                    "this expression form is not supported by the compiler yet",
4351                    expr.span,
4352                ));
4353            }
4354        }
4355        Ok(())
4356    }
4357
4358    /// Build one array holding the evaluated call arguments, which is how a call
4359    /// containing a spread is compiled: the reference does the same, building the
4360    /// list on the stack and handing it to `apply`.
4361    fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
4362        let elements: Vec<Option<ArrayElement>> = arguments
4363            .iter()
4364            .map(|argument| match &argument.unparen().kind {
4365                ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
4366                _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
4367            })
4368            .collect();
4369        self.array_literal(&elements, Span::default())
4370    }
4371
4372    /// Whether any argument is a spread, which is what selects the `apply` form.
4373    fn has_spread(arguments: &[Expr]) -> bool {
4374        arguments
4375            .iter()
4376            .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
4377    }
4378
4379    /// Compile `a${x}b`.
4380    ///
4381    /// A template is a `+` chain built left to right: the leading chunk (or an empty
4382    /// string when the template starts with a substitution), then for each
4383    /// substitution its value, `to_propkey` and `add`, then the following chunk when
4384    /// it is not empty. `to_propkey` is what makes a number or object substitute the
4385    /// way `ToString` would while leaving the result a string for `add` to
4386    /// concatenate.
4387    ///
4388    /// The chunk is an atom rather than a constant-pool string, because a non-empty
4389    /// chunk always lands where a value is pushed and `push_atom_value` is the
4390    /// instruction the reference uses for it; the empty first chunk has its own
4391    /// zero-byte form.
4392    fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
4393        let first = template.quasis.first();
4394        match first.and_then(|quasi| quasi.cooked.clone()) {
4395            Some(text) if !text.is_empty() => {
4396                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4397            }
4398            // Either the template begins with a substitution, or the chunk is
4399            // empty — in both cases the chain needs a string to start from.
4400            _ => self.emit(Opcode::PushEmptyString, &[]),
4401        }
4402        for (index, expression) in template.expressions.iter().enumerate() {
4403            self.expr(expression)?;
4404            self.emit(Opcode::ToPropkey, &[]);
4405            self.emit(Opcode::Add, &[]);
4406            if let Some(text) = template
4407                .quasis
4408                .get(index + 1)
4409                .and_then(|quasi| quasi.cooked.clone())
4410                && !text.is_empty()
4411            {
4412                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4413                self.emit(Opcode::Add, &[]);
4414            }
4415        }
4416        Ok(())
4417    }
4418
4419    /// Compile an object literal.
4420    ///
4421    /// The object is built in place: `object` pushes it, and each property leaves it
4422    /// on the stack with one field more, so no temporary is needed and later
4423    /// properties can overwrite earlier ones.
4424    ///
4425    /// The instruction depends on *how* the property was written, not on what kind
4426    /// of value it holds:
4427    ///
4428    /// | source | instruction |
4429    /// |---|---|
4430    /// | `{ a: v }` | `define_field a` |
4431    /// | `{ __proto__: v }` | `set_proto` |
4432    /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
4433    /// | `{ m() {} }` | `define_method m,4` |
4434    /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
4435    /// | `{ [k]() {} }` | `define_method_computed 4` |
4436    /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
4437    ///
4438    /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
4439    /// key itself, which is why the trailing `drop` is absent there too.
4440    /// `tag`…``: a call whose first argument is the call site's template object.
4441    ///
4442    /// The template object is a frozen array of the cooked chunks with a frozen `raw`
4443    /// array beside it, so `String.raw` can read the source text back. It is a constant
4444    /// because its contents never change; the reference builds one per call site and
4445    /// reuses it, while this builds one per evaluation, which only `tag` code that
4446    /// compares template objects across calls could tell apart.
4447    fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
4448        let cooked = quasi
4449            .quasis
4450            .iter()
4451            .map(|chunk| chunk.cooked.clone())
4452            .collect();
4453        let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
4454        let index = self.push_constant(Constant::Template { cooked, raw });
4455        let count = quasi.expressions.len() + 1;
4456        // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
4457        if let ExprKind::Member {
4458            object, property, ..
4459        } = &tag.unparen().kind
4460        {
4461            self.expr(object)?;
4462            match property {
4463                MemberProp::Ident(name) => {
4464                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
4465                }
4466                MemberProp::Computed(key) => {
4467                    self.expr(key)?;
4468                    self.emit(Opcode::GetArrayEl2, &[]);
4469                }
4470                MemberProp::Private(name) => {
4471                    let binding = format!("#{}", name.name);
4472                    let (kind, _) = self.private_use(&binding, tag.span)?;
4473                    self.private_callee(&binding, kind)?;
4474                }
4475            }
4476            self.emit(Opcode::PushConst, &[Op::Const(index)]);
4477            for expression in &quasi.expressions {
4478                self.expr(expression)?;
4479            }
4480            self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
4481            return Ok(());
4482        }
4483        self.expr(tag)?;
4484        self.emit(Opcode::PushConst, &[Op::Const(index)]);
4485        for expression in &quasi.expressions {
4486            self.expr(expression)?;
4487        }
4488        self.emit(Opcode::Call, &[Op::Int(count as i32)]);
4489        Ok(())
4490    }
4491
4492    fn object_literal(
4493        &mut self,
4494        properties: &[ObjectProperty],
4495        span: Span,
4496    ) -> Result<(), SyntaxError> {
4497        self.emit(Opcode::Object, &[]);
4498        for property in properties {
4499            match property {
4500                ObjectProperty::Spread(value) => {
4501                    // `copy_data_properties` takes the target, the source and an
4502                    // exclusion list; a literal `null` means "exclude nothing".
4503                    // Flag bit 1 copies symbols, bits 2/5 pick the source and the
4504                    // exclusion list by stack offset.
4505                    self.expr(spread_argument(value))?;
4506                    self.emit(Opcode::Null, &[]);
4507                    self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4508                    self.emit(Opcode::Drop, &[]);
4509                    self.emit(Opcode::Drop, &[]);
4510                }
4511                ObjectProperty::Property {
4512                    key,
4513                    value,
4514                    kind,
4515                    shorthand,
4516                    span: property_span,
4517                } => match key {
4518                    PropName::Computed(key_expr) => {
4519                        self.expr(key_expr)?;
4520                        match kind {
4521                            PropertyKind::Value => {
4522                                self.emit(Opcode::ToPropkey, &[]);
4523                                self.expr(value)?;
4524                                self.set_name_if_anonymous_computed(value);
4525                                self.emit(Opcode::DefineArrayEl, &[]);
4526                                // `define_array_el` leaves the object and the key;
4527                                // the key is no longer needed.
4528                                self.emit(Opcode::Drop, &[]);
4529                            }
4530                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4531                                self.emit_method_function(value)?;
4532                                self.emit(
4533                                    Opcode::DefineMethodComputed,
4534                                    &[Op::Int(define_method_flags(*kind))],
4535                                );
4536                            }
4537                        }
4538                    }
4539                    PropName::Literal(key) => {
4540                        let name = self.property_key_text(key, *property_span)?;
4541                        match kind {
4542                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4543                                self.emit_method_function(value)?;
4544                                self.emit(
4545                                    Opcode::DefineMethod,
4546                                    &[
4547                                        Op::Atom(Atom::from_wtf8(&name)),
4548                                        Op::Int(define_method_flags(*kind)),
4549                                    ],
4550                                );
4551                            }
4552                            PropertyKind::Value => {
4553                                self.expr(value)?;
4554                                // `{__proto__: x}` sets the prototype instead of
4555                                // creating a property; the shorthand `{__proto__}`
4556                                // is an ordinary property and does not.
4557                                if name == "__proto__" && !shorthand {
4558                                    self.emit(Opcode::SetProto, &[]);
4559                                } else {
4560                                    self.set_name_if_anonymous(value, &name);
4561                                    self.emit(
4562                                        Opcode::DefineField,
4563                                        &[Op::Atom(Atom::from_wtf8(&name))],
4564                                    );
4565                                }
4566                            }
4567                        }
4568                    }
4569                    PropName::Private(_) => {
4570                        return Err(SyntaxError::new(
4571                            "private names are not valid in object literals",
4572                            *property_span,
4573                        ));
4574                    }
4575                },
4576            }
4577        }
4578        let _ = span;
4579        Ok(())
4580    }
4581
4582    /// Emit the function a method/accessor property defines.
4583    fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
4584        self.expr(value)
4585    }
4586
4587    /// The name a literal property key contributes.
4588    ///
4589    /// String keys are used as written. A numeric key is converted the way
4590    /// `ToString` would convert it, because the atom is made from that spelling:
4591    /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
4592    fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
4593        match key {
4594            PropKey::Str(text) => Ok(text.clone()),
4595            PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
4596        }
4597    }
4598
4599    /// Compile an optional chain.
4600    ///
4601    /// `?.` short-circuits the *whole remaining spine*, not just its own link:
4602    /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
4603    /// `undefined`. So the chain is compiled with one end label and every guard
4604    /// jumps to it. The parser hands us the extent of that spine as an
4605    /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
4606    /// exactly the scope the label has to cover.
4607    fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
4608        let end = self.new_label();
4609        self.chain_link(inner, end)?;
4610        self.place_label(end);
4611        Ok(())
4612    }
4613
4614    /// A member access or call reached from outside any optional chain.
4615    ///
4616    /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
4617    /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
4618    /// still created because [`Self::chain_link`] takes it, and placing it at the
4619    /// end is a no-op that keeps a single code path.
4620    fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4621        let end = self.new_label();
4622        self.chain_link(expr, end)?;
4623        self.place_label(end);
4624        Ok(())
4625    }
4626
4627    /// One link of a chain, where `end` is the label a `?.` guard jumps to.
4628    fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
4629        match &expr.kind {
4630            ExprKind::Member {
4631                object,
4632                property,
4633                optional,
4634            } => {
4635                // `super.x` is not a lookup on a value: it starts at the home object's
4636                // prototype and keeps `this` as the receiver, so it cannot go through
4637                // `chain_link` and the ordinary field read.
4638                if matches!(object.unparen().kind, ExprKind::SuperProp) {
4639                    self.super_base();
4640                    match property {
4641                        MemberProp::Ident(name) => self.emit(
4642                            Opcode::PushAtomValue,
4643                            &[Op::Atom(Atom::from_text(&name.name))],
4644                        ),
4645                        MemberProp::Computed(index) => self.expr(index)?,
4646                        MemberProp::Private(_) => {
4647                            return Err(SyntaxError::new(
4648                                "private fields are not supported by the compiler yet",
4649                                expr.span,
4650                            ));
4651                        }
4652                    }
4653                    self.emit(Opcode::GetSuperValue, &[]);
4654                    return Ok(());
4655                }
4656                self.chain_link(object, end)?;
4657                if *optional {
4658                    self.optional_guard(end);
4659                }
4660                match property {
4661                    // `.length` has its own opcode. The reference emits it for every
4662                    // object, not just arrays, so a name-based rule is right and
4663                    // cheaper than the generic field read.
4664                    MemberProp::Ident(name) if name.name == "length" => {
4665                        self.emit(Opcode::GetLength, &[]);
4666                    }
4667                    MemberProp::Ident(name) => {
4668                        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
4669                    }
4670                    MemberProp::Computed(index) => {
4671                        self.expr(index)?;
4672                        self.emit(Opcode::GetArrayEl, &[]);
4673                    }
4674                    MemberProp::Private(name) => {
4675                        // The binding comes from the class scope, so a read from outside the
4676                        // class cannot name it at all. `?.` checks the object, not the field:
4677                        // `o?.#x` guards on `o` being nullish.
4678                        let binding = format!("#{}", name.name);
4679                        let (kind, _) = self.private_use(&binding, expr.span)?;
4680                        self.private_load(&binding, kind, expr.span)?;
4681                    }
4682                }
4683                Ok(())
4684            }
4685            ExprKind::Call {
4686                callee,
4687                arguments,
4688                optional,
4689            } => {
4690                // `o.m(args)` has to pass `o` as `this`, which a plain `call`
4691                // cannot: it reads the function and then calls it with no
4692                // receiver at all. The reference's answer is to keep the object
4693                // under the function value — `get_field2` reads a field and leaves
4694                // its base in place — and to use `call_method`, which takes the
4695                // receiver from the stack. Missing this does not just cost an
4696                // instruction, it loses the `this` binding.
4697                if let ExprKind::Member {
4698                    object,
4699                    property,
4700                    optional: member_optional,
4701                } = &callee.unparen().kind
4702                {
4703                    // `super.m()` reads the method off the home object's prototype but
4704                    // calls it with `this`, so the receiver goes under the read instead of
4705                    // being replaced by it.
4706                    if matches!(object.unparen().kind, ExprKind::SuperProp) {
4707                        self.super_base();
4708                        match property {
4709                            MemberProp::Ident(name) => self.emit(
4710                                Opcode::PushAtomValue,
4711                                &[Op::Atom(Atom::from_text(&name.name))],
4712                            ),
4713                            MemberProp::Computed(index) => self.expr(index)?,
4714                            MemberProp::Private(_) => {
4715                                return Err(SyntaxError::new(
4716                                    "private fields are not supported by the compiler yet",
4717                                    expr.span,
4718                                ));
4719                            }
4720                        }
4721                        // The two-output form would drop the receiver; this one replaces
4722                        // the prototype and the key, leaving `this` underneath.
4723                        self.emit(Opcode::GetArrayEl, &[]);
4724                        if Self::has_spread(arguments) {
4725                            self.argument_array(arguments)?;
4726                            self.emit(Opcode::Perm3, &[]);
4727                            self.emit(Opcode::Apply, &[Op::Int(0)]);
4728                            return Ok(());
4729                        }
4730                        for argument in arguments {
4731                            self.expr(argument)?;
4732                        }
4733                        self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4734                        return Ok(());
4735                    }
4736                    self.chain_link(object, end)?;
4737                    if *member_optional {
4738                        self.optional_guard(end);
4739                    }
4740                    match property {
4741                        MemberProp::Ident(name) => {
4742                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4743                        }
4744                        MemberProp::Computed(index) => {
4745                            self.expr(index)?;
4746                            // The key is not needed after the read, so this is the
4747                            // two-output form: object, value.
4748                            self.emit(Opcode::GetArrayEl2, &[]);
4749                        }
4750                        MemberProp::Private(name) => {
4751                            // The receiver is already under the callee, which is exactly the
4752                            // shape `call_method` and `apply` want — so nothing is dropped.
4753                            let binding = format!("#{}", name.name);
4754                            let (kind, _) = self.private_use(&binding, expr.span)?;
4755                            self.private_callee(&binding, kind)?;
4756                        }
4757                    }
4758                    if Self::has_spread(arguments) {
4759                        // Stack is `obj func`; the array goes on top, then `perm3`
4760                        // reorders to the `func this array` that `apply` wants.
4761                        self.argument_array(arguments)?;
4762                        self.emit(Opcode::Perm3, &[]);
4763                        self.emit(Opcode::Apply, &[Op::Int(0)]);
4764                        return Ok(());
4765                    }
4766                    for argument in arguments {
4767                        self.expr(argument)?;
4768                    }
4769                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4770                    return Ok(());
4771                }
4772                // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
4773                // with `get_field2` so the base stays under it, and on the short-circuit
4774                // path pushes an extra `undefined` as a placeholder receiver — the call
4775                // then throws, which is what calling a missing optional chain should do.
4776                if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
4777                    && let ExprKind::Member {
4778                        object,
4779                        property,
4780                        optional: member_optional,
4781                    } = &inner.unparen().kind
4782                {
4783                    let call = self.new_label();
4784                    // A guard target of its own: the outer `end` skips the whole
4785                    // expression, and a short-circuited receiver still has to reach the
4786                    // call so that calling it throws.
4787                    let short = self.new_label();
4788                    self.chain_link(object, end)?;
4789                    if *member_optional {
4790                        self.optional_guard(short);
4791                    }
4792                    match property {
4793                        MemberProp::Ident(name) => {
4794                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4795                        }
4796                        MemberProp::Computed(index) => {
4797                            self.expr(index)?;
4798                            self.emit(Opcode::GetArrayEl2, &[]);
4799                        }
4800                        MemberProp::Private(name) => {
4801                            let binding = format!("#{}", name.name);
4802                            let (kind, _) = self.private_use(&binding, expr.span)?;
4803                            self.private_callee(&binding, kind)?;
4804                        }
4805                    }
4806                    self.emit_jump(Opcode::Goto, call, &[]);
4807                    self.place_label(short);
4808                    self.emit(Opcode::Undefined, &[]);
4809                    self.place_label(call);
4810                    if Self::has_spread(arguments) {
4811                        self.argument_array(arguments)?;
4812                        self.emit(Opcode::Perm3, &[]);
4813                        self.emit(Opcode::Apply, &[Op::Int(0)]);
4814                        return Ok(());
4815                    }
4816                    for argument in arguments {
4817                        self.expr(argument)?;
4818                    }
4819                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4820                    return Ok(());
4821                }
4822                self.chain_link(callee, end)?;
4823                if *optional {
4824                    self.optional_guard(end);
4825                }
4826                if Self::has_spread(arguments) {
4827                    // `func array -> func undefined array`, which is the plain-call
4828                    // form of `apply`: the receiver is `undefined`.
4829                    self.argument_array(arguments)?;
4830                    self.emit(Opcode::Undefined, &[]);
4831                    self.emit(Opcode::Swap, &[]);
4832                    self.emit(Opcode::Apply, &[Op::Int(0)]);
4833                    return Ok(());
4834                }
4835                for argument in arguments {
4836                    self.expr(argument)?;
4837                }
4838                self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
4839                Ok(())
4840            }
4841            _ => self.expr(expr),
4842        }
4843    }
4844
4845    /// Compile `expr` as a tail call when it is one, reporting whether it was.
4846    ///
4847    /// `tail_call` reuses the current frame instead of pushing a new one, so a
4848    /// tail-recursive function runs in constant stack space. It also has to be the
4849    /// *last* thing the function does, which is why only a `return` reaches here.
4850    fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
4851        let ExprKind::Call {
4852            callee,
4853            arguments,
4854            optional: false,
4855        } = &expr.unparen().kind
4856        else {
4857            return Ok(false);
4858        };
4859        // A spread call has no tail form: `tail_call` takes its arguments one at a time off
4860        // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
4861        // as an ordinary call costs the one frame the optimisation was saving and keeps the
4862        // semantics — the alternative was reaching the spread expression below and failing
4863        // with "this expression form is not supported", which is how `return super.m(...a)`
4864        // stopped compiling. Checked before anything is emitted, because the decision cannot
4865        // be taken back once `super_base` or a `get_field2` is on the stack.
4866        if Self::has_spread(arguments) {
4867            return Ok(false);
4868        }
4869        let end = self.new_label();
4870        if let ExprKind::Member {
4871            object,
4872            property,
4873            optional: false,
4874        } = &callee.unparen().kind
4875        {
4876            // `super.m()` in tail position is still an ordinary method call with `this`
4877            // as the receiver; only the read of the method differs.
4878            if matches!(object.unparen().kind, ExprKind::SuperProp) {
4879                self.super_base();
4880                match property {
4881                    MemberProp::Ident(name) => self.emit(
4882                        Opcode::PushAtomValue,
4883                        &[Op::Atom(Atom::from_text(&name.name))],
4884                    ),
4885                    MemberProp::Computed(index) => self.expr(index)?,
4886                    MemberProp::Private(_) => return Ok(false),
4887                }
4888                self.emit(Opcode::GetArrayEl, &[]);
4889                for argument in arguments {
4890                    self.expr(argument)?;
4891                }
4892                self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
4893                self.place_label(end);
4894                return Ok(true);
4895            }
4896            self.chain_link(object, end)?;
4897            match property {
4898                MemberProp::Ident(name) => {
4899                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4900                }
4901                MemberProp::Computed(index) => {
4902                    self.expr(index)?;
4903                    self.emit(Opcode::GetArrayEl2, &[]);
4904                }
4905                MemberProp::Private(_) => return Ok(false),
4906            }
4907            for argument in arguments {
4908                self.expr(argument)?;
4909            }
4910            self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
4911            self.place_label(end);
4912            return Ok(true);
4913        }
4914        self.chain_link(callee, end)?;
4915        for argument in arguments {
4916            self.expr(argument)?;
4917        }
4918        self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
4919        self.place_label(end);
4920        Ok(true)
4921    }
4922
4923    /// The `?.` guard: keep the value if it is neither null nor undefined,
4924    /// otherwise replace it with `undefined` and leave the whole chain.
4925    fn optional_guard(&mut self, end: Label) {
4926        let cont = self.new_label();
4927        self.emit(Opcode::Dup, &[]);
4928        self.emit(Opcode::IsUndefinedOrNull, &[]);
4929        self.emit_jump(Opcode::IfFalse, cont, &[]);
4930        self.emit(Opcode::Drop, &[]);
4931        self.emit(Opcode::Undefined, &[]);
4932        self.emit_jump(Opcode::Goto, end, &[]);
4933        self.place_label(cont);
4934    }
4935
4936    fn push_number(&mut self, value: f64) {
4937        // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
4938        // goes into the constant pool.
4939        if value == value.trunc() && value.abs() <= i32::MAX as f64 {
4940            let int = value as i32;
4941            if (-1..=7).contains(&int) {
4942                self.emit(Opcode::PushI32, &[Op::Int(int)]);
4943                return;
4944            }
4945            if (-128..=127).contains(&int) {
4946                self.emit(Opcode::PushI8, &[Op::Int(int)]);
4947                return;
4948            }
4949            if (-32768..=32767).contains(&int) {
4950                self.emit(Opcode::PushI16, &[Op::Int(int)]);
4951                return;
4952            }
4953            self.emit(Opcode::PushI32, &[Op::Int(int)]);
4954            return;
4955        }
4956        let index = self.push_constant(Constant::Number(value));
4957        self.emit(Opcode::PushConst, &[Op::Const(index)]);
4958    }
4959
4960    /// Push a `BigInt` literal.
4961    ///
4962    /// A value that fits an `i32` uses the immediate form, which is what the reference
4963    /// emits too; anything larger goes into the constant pool, because the operand of
4964    /// `push_bigint` is only four bytes wide.
4965    fn push_bigint(&mut self, digits: &str, radix: u32) {
4966        if radix == 10
4967            && let Ok(value) = digits.parse::<i64>()
4968            && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
4969        {
4970            self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
4971            return;
4972        }
4973        let index = self.push_constant(Constant::BigInt {
4974            digits: digits.to_string(),
4975            radix,
4976        });
4977        self.emit(Opcode::PushConst, &[Op::Const(index)]);
4978    }
4979
4980    fn push_string(&mut self, text: &Wtf8) {
4981        if text.is_empty() {
4982            self.emit(Opcode::PushEmptyString, &[]);
4983            return;
4984        }
4985        self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
4986    }
4987
4988    /// Name an anonymous function from the binding it is assigned to.
4989    ///
4990    /// `var f = function(){}` produces a function whose `name` is `f`, which the
4991    /// runtime cannot know without being told: the function object is created
4992    /// before the store. `set_name` carries the name across.
4993    fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
4994        if value.is_anonymous_function_definition() {
4995            self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
4996        }
4997    }
4998
4999    /// The same, for a computed key: the name comes from the value on the stack
5000    /// rather than from an atom, so a different instruction carries it.
5001    fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
5002        if value.is_anonymous_function_definition() {
5003            self.emit(Opcode::SetNameComputed, &[]);
5004        }
5005    }
5006
5007    /// Compile a function body that exists only in the compiler's head — a class's
5008    /// implicit constructor or its field initialiser.
5009    ///
5010    /// Everything structural is the same as a written function: a fresh `FnState`, its
5011    /// own body block, and resolution while the frame is still on the stack. Only the
5012    /// statements differ.
5013    fn compile_synthetic_function(
5014        &mut self,
5015        name: &str,
5016        strict: bool,
5017        span: Span,
5018        body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
5019    ) -> Result<CompiledFunction, SyntaxError> {
5020        let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
5021        state.strict = strict;
5022        state.created_in_block = self.cur().current_block;
5023        state.with_names = self.cur().with_names.clone();
5024        state.line = span.start.line;
5025        state.column = span.start.column;
5026        let depth = self.stack.len();
5027        self.stack.push(state);
5028        let body_key = span.start.offset as u64;
5029        self.push_block(body_key, NO_PARENT);
5030        self.state().body_block = body_key;
5031        let result = (|| {
5032            self.emit_scope_enter(body_key);
5033            body(self)?;
5034            if self.end_is_reachable() {
5035                self.emit(Opcode::ReturnUndef, &[]);
5036            }
5037            Ok(())
5038        })();
5039        if result.is_err() {
5040            self.stack.truncate(depth);
5041            return result.map(|()| unreachable!());
5042        }
5043        Ok(self.finish_current())
5044    }
5045
5046    /// The implicit return of a class constructor.
5047    ///
5048    /// A constructor that falls off the end initialises its instance fields first, and a
5049    /// derived one returns `this` — which is what makes `new D()` the object `super()`
5050    /// built rather than `undefined`.
5051    fn emit_class_constructor_tail(&mut self) {
5052        match self.cur().ctor_kind {
5053            CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
5054            // Nothing to install: a base constructor did it in its prologue and a derived
5055            // one at each `super()` site, which is where `this` first exists.
5056            CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
5057            CtorKind::Derived => {
5058                // `get_loc_check` rather than `get_loc`: reaching the end without ever
5059                // running `super()` is a ReferenceError, not `undefined`.
5060                self.emit_var(VarAction::Get, "this");
5061                self.emit(Opcode::Return, &[]);
5062            }
5063        }
5064    }
5065
5066    /// `yield expr` / `yield* expr`.
5067    ///
5068    /// The suspension itself is one instruction: the value is on the stack, `yield` hands
5069    /// it to the caller and parks the frame. On resume the stack holds the value the
5070    /// caller passed *and* a "magic" number saying which method resumed it — `next`
5071    /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
5072    /// `if_false <continue>` asks whether this was an ordinary `next`:
5073    ///
5074    /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
5075    /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
5076    ///   and uses the value sitting under the magic number.
5077    ///
5078    /// A `throw` never reaches here: the interpreter unwinds instead (see
5079    /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
5080    fn yield_expression(
5081        &mut self,
5082        argument: Option<&Expr>,
5083        delegate: bool,
5084    ) -> Result<(), SyntaxError> {
5085        if delegate {
5086            return self.yield_star(argument);
5087        }
5088        // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
5089        // does the same for the `return(v)` that can resume it — which is why an async
5090        // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
5091        // generator's is just `yield`.
5092        let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
5093        match argument {
5094            Some(value) => self.expr(value)?,
5095            None => self.emit(Opcode::Undefined, &[]),
5096        }
5097        if is_async {
5098            self.emit(Opcode::Await, &[]);
5099            self.state().has_await = true;
5100        }
5101        self.emit(Opcode::Yield, &[]);
5102        let resume = self.new_label();
5103        self.emit_jump(Opcode::IfFalse, resume, &[]);
5104        // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
5105        // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
5106        // finished the generator and never ran the `finally`.
5107        if is_async {
5108            self.emit(Opcode::Await, &[]);
5109        }
5110        self.emit_unwind_for_return(true);
5111        self.emit(Opcode::ReturnAsync, &[]);
5112        self.place_label(resume);
5113        // Nothing is emitted here: the value the caller passed to `next` *is* the value
5114        // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
5115        // it through the ordinary expression-statement discard.
5116        Ok(())
5117    }
5118
5119    /// `yield* iterable`.
5120    ///
5121    /// The shape is the reference's, and it is a fall-through chain rather than a
5122    /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
5123    /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
5124    /// the inner iterator and finishes, `throw` forwards the exception into it and
5125    /// continues only if it has a `throw` method.
5126    ///
5127    /// The stack is `iter next catch value` throughout, `catch` being the offset
5128    /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
5129    fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
5130        match argument {
5131            Some(value) => self.expr(value)?,
5132            // The parser rejects a bare `yield*`, so this is unreachable in practice.
5133            None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
5134        }
5135        // `for await of` is the same protocol as `for of` with two differences that matter
5136        // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
5137        // every `next()` result is a promise the delegate has to await.
5138        let is_async = self.cur().kind.is_async();
5139        self.emit(
5140            if is_async {
5141                Opcode::ForAwaitOfStart
5142            } else {
5143                Opcode::ForOfStart
5144            },
5145            &[],
5146        );
5147        self.emit(Opcode::Drop, &[]);
5148        self.emit(Opcode::Undefined, &[]);
5149        self.emit(Opcode::Undefined, &[]);
5150        let next = self.new_label();
5151        let resume = self.new_label();
5152        let finished = self.new_label();
5153        let rethrow = self.new_label();
5154        let throw_no_method = self.new_label();
5155        let done = self.new_label();
5156        self.place_label(next);
5157        self.emit(Opcode::IteratorNext, &[]);
5158        if is_async {
5159            self.emit(Opcode::Await, &[]);
5160            self.state().has_await = true;
5161        }
5162        self.emit(Opcode::IteratorCheckObject, &[]);
5163        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5164        self.emit_jump(Opcode::IfTrue, done, &[]);
5165        // The suspension. `resume` is both the label the return path jumps back to in order
5166        // to yield one more value and where the caller's answer arrives, as the value
5167        // followed by the magic number.
5168        //
5169        // The two forms differ in what they hand the suspension: `yield_star` takes the
5170        // result object itself, `async_yield_star` takes `.value`, because an async
5171        // generator awaits and re-wraps whatever it yields.
5172        self.place_label(resume);
5173        if is_async {
5174            self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5175            self.emit(Opcode::AsyncYieldStar, &[]);
5176        } else {
5177            self.emit(Opcode::YieldStar, &[]);
5178        }
5179        self.emit(Opcode::Dup, &[]);
5180        self.emit_jump(Opcode::IfTrue, rethrow, &[]);
5181        self.emit(Opcode::Drop, &[]);
5182        self.emit_jump(Opcode::Goto, next, &[]);
5183
5184        // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
5185        self.place_label(rethrow);
5186        self.emit(Opcode::PushI32, &[Op::Int(2)]);
5187        self.emit(Opcode::StrictEq, &[]);
5188        self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
5189        // A `return` closes the inner iterator; if it had none, the delegate simply
5190        // finishes with the requested value. In an async generator both the call and its
5191        // result are awaited, because the inner `return` may itself be async.
5192        if is_async {
5193            self.emit(Opcode::Await, &[]);
5194        }
5195        self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
5196        self.emit_jump(Opcode::IfTrue, finished, &[]);
5197        if is_async {
5198            self.emit(Opcode::Await, &[]);
5199        }
5200        self.emit(Opcode::IteratorCheckObject, &[]);
5201        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5202        self.emit_jump(Opcode::IfFalse, resume, &[]);
5203        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5204        self.place_label(finished);
5205        self.emit(Opcode::Nip, &[]);
5206        self.emit(Opcode::Nip, &[]);
5207        self.emit(Opcode::Nip, &[]);
5208        // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
5209        // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
5210        // awaits the value in an async generator and then runs the same `finally`/iterator
5211        // unwinding a written `return` would. Skipping the unwinding made
5212        // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
5213        if is_async {
5214            self.emit(Opcode::Await, &[]);
5215        }
5216        self.emit_unwind_for_return(true);
5217        self.emit(Opcode::ReturnAsync, &[]);
5218
5219        // `throw(e)`: forward it into the inner iterator.
5220        self.place_label(throw_no_method);
5221        self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
5222        let no_throw = self.new_label();
5223        self.emit_jump(Opcode::IfTrue, no_throw, &[]);
5224        if is_async {
5225            self.emit(Opcode::Await, &[]);
5226        }
5227        self.emit(Opcode::IteratorCheckObject, &[]);
5228        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5229        self.emit_jump(Opcode::IfFalse, resume, &[]);
5230        self.emit_jump(Opcode::Goto, done, &[]);
5231        // No `throw` method: close the iterator, then report the spec's TypeError. The
5232        // `if_true` before the `await` is the reference's shape — the flag it consumes is
5233        // what `iterator_call` leaves behind, and a close that *did* find no `return`
5234        // method has nothing to await.
5235        self.place_label(no_throw);
5236        self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
5237        let no_close = self.new_label();
5238        self.emit_jump(Opcode::IfTrue, no_close, &[]);
5239        if is_async {
5240            self.emit(Opcode::Await, &[]);
5241        }
5242        self.place_label(no_close);
5243        self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
5244
5245        // The inner iterator finished: the delegate's value is the `yield*` expression's
5246        // value, so it is left on the stack for whatever consumes it.
5247        self.place_label(done);
5248        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5249        self.emit(Opcode::Nip, &[]);
5250        self.emit(Opcode::Nip, &[]);
5251        self.emit(Opcode::Nip, &[]);
5252        Ok(())
5253    }
5254
5255    /// `await expr`: exactly one instruction.
5256    ///
5257    /// No resume-magic branch follows it. The reference's `await` leaves a single value
5258    /// on the stack and completion is signalled by the `return_async` at the end of the
5259    /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
5260    /// reference never emits, and a `for await` loop — which reaches `await` through the
5261    /// same opcode — would then spill a value the loop's unpacking does not expect.
5262    fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
5263        self.expr(argument)?;
5264        self.emit(Opcode::Await, &[]);
5265        self.state().has_await = true;
5266        Ok(())
5267    }
5268
5269    /// The `super` base: the receiver followed by the home object's prototype.
5270    ///
5271    /// Everything `super` does needs both. A *read* starts at the prototype but reports
5272    /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
5273    /// prototype but calls it with the receiver.
5274    fn super_base(&mut self) {
5275        self.this_expression();
5276        self.home_object();
5277        self.emit(Opcode::GetSuper, &[]);
5278    }
5279
5280    /// `[[HomeObject]]` as `super` sees it.
5281    ///
5282    /// A method, a constructor and a field initialiser each carry one — `set_home_object`
5283    /// put it there — so for them the special object *is* the answer. An arrow and a
5284    /// static block have none: they read the enclosing function's, which has to be
5285    /// materialised into a local, exactly as `this` is for an arrow.
5286    ///
5287    /// The name matches what the reference stores, so the disassembly agrees; it is not a
5288    /// name any program can write.
5289    fn home_object(&mut self) {
5290        if !self.cur().is_arrow {
5291            self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
5292            return;
5293        }
5294        if let Some(target) = self.enclosing_function() {
5295            self.state_at(target).needs_home_object_local = true;
5296            self.declare_at(target, HOME_OBJECT);
5297        }
5298        self.emit_var(VarAction::Get, HOME_OBJECT);
5299    }
5300
5301    /// `super(args)`: construct the parent class and adopt the result as `this`.
5302    ///
5303    /// The parent is the prototype of the constructor that is running, which is exactly
5304    /// what `extends` set up. `new.target` is passed through unchanged so that
5305    /// `new.target` inside the parent is the class actually being constructed.
5306    fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5307        self.active_func_expression();
5308        self.emit(Opcode::GetSuper, &[]);
5309        self.new_target_expression();
5310        if Self::has_spread(arguments) {
5311            self.argument_array(arguments)?;
5312            self.emit(Opcode::Apply, &[Op::Int(1)]);
5313        } else {
5314            for argument in arguments {
5315                self.expr(argument)?;
5316            }
5317            self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
5318        }
5319        // The value stays on the stack: `super()` is an expression, and a derived
5320        // constructor's `this` may only be initialised once.
5321        self.emit(Opcode::Dup, &[]);
5322        self.emit_var(VarAction::PutInitChecked, "this");
5323        // Instance fields are installed here, not at the top of the body: a derived
5324        // constructor has no `this` to install them on until `super()` returns. The
5325        // reference emits the same call at every `super()` site.
5326        self.call_field_initialiser();
5327        Ok(())
5328    }
5329
5330    /// `this` as a local, which every class constructor and field initialiser needs.
5331    ///
5332    /// The reference materialises the receiver into a local rather than reading
5333    /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
5334    /// and a field initialiser has to see the final value.
5335    fn begin_this_local(&mut self) {
5336        self.declare_hidden_local("this", VarKind::Normal);
5337        self.emit(Opcode::PushThis, &[]);
5338        self.emit_var(VarAction::Put, "this");
5339        // The store is already at the top of the body, so `provide_this_local` has
5340        // nothing left to prepend. Without this the initialiser ended up with
5341        // `push_this; put_loc0 this` twice whenever the class also held a field
5342        // initialiser whose body read `this` through an arrow.
5343        self.state().has_this_prologue = true;
5344    }
5345
5346    /// Compile a constructor the class wrote.
5347    ///
5348    /// The flags have to be in place before the body is compiled, but
5349    /// `compile_function_with_name` creates its own state — so the caller's state is
5350    /// marked instead and the new one inherits it. That is the same trick the parameter
5351    /// prologue uses, and it keeps one code path for both.
5352    fn compile_class_constructor(
5353        &mut self,
5354        func: &ast::Function,
5355        has_heritage: bool,
5356    ) -> Result<CompiledFunction, SyntaxError> {
5357        let saved = self.cur().ctor_kind;
5358        self.state().class_ctor_pending = Some(if has_heritage {
5359            CtorKind::Derived
5360        } else {
5361            CtorKind::Base
5362        });
5363        let result = self.compile_function_with_name(func, false);
5364        self.state().ctor_kind = saved;
5365        self.state().class_ctor_pending = None;
5366        result
5367    }
5368
5369    /// The constructor a class gets when it does not declare one.
5370    ///
5371    /// A base class's is empty; a derived class's forwards every argument to the parent
5372    /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
5373    /// instance field initialiser afterwards when the class has fields, which is why the
5374    /// initialiser is captured rather than inlined.
5375    fn compile_implicit_constructor(
5376        &mut self,
5377        class: &Class,
5378        has_heritage: bool,
5379    ) -> Result<CompiledFunction, SyntaxError> {
5380        self.compile_synthetic_function(
5381            "",
5382            true,
5383            Span::new(class.body_end, class.body_end),
5384            |compiler| {
5385                if has_heritage {
5386                    // A derived constructor's `this` does not exist until `super()` returns,
5387                    // so it starts in the dead zone and `init_ctor` fills it.
5388                    compiler.declare("this", VarDef::lexical("this"));
5389                    compiler.emit(
5390                        Opcode::SetLocUninitialized,
5391                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5392                    );
5393                    compiler.emit(Opcode::InitCtor, &[]);
5394                    compiler.emit(
5395                        Opcode::PutLocCheckInit,
5396                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5397                    );
5398                } else {
5399                    compiler.begin_this_local();
5400                    compiler.emit(Opcode::CheckCtor, &[]);
5401                }
5402                compiler.call_field_initialiser();
5403                // A derived constructor returns `this`, the object `super()` built. Without
5404                // this the implicit constructor fell through to `return_undef`, and `new B()`
5405                // handed back the empty object `construct` had made instead of the one the
5406                // parent constructor initialised.
5407                if has_heritage {
5408                    compiler.emit_var(VarAction::Get, "this");
5409                    compiler.emit(Opcode::Return, &[]);
5410                }
5411                Ok(())
5412            },
5413        )
5414    }
5415
5416    /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
5417    ///
5418    /// A class with no instance fields leaves the binding `undefined`, and calling it
5419    /// would throw; the reference emits the same guard rather than branching at compile
5420    /// time because a class can be extended by a subclass whose fields still have to run.
5421    fn call_field_initialiser(&mut self) {
5422        let skip = self.new_label();
5423        self.emit_var(VarAction::Get, "<class_fields_init>");
5424        self.emit(Opcode::Dup, &[]);
5425        self.emit_jump(Opcode::IfFalse, skip, &[]);
5426        self.emit_var(VarAction::Get, "this");
5427        self.emit(Opcode::Swap, &[]);
5428        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
5429        self.place_label(skip);
5430        self.emit(Opcode::Drop, &[]);
5431    }
5432
5433    /// The function that defines one class's fields on `this`, and runs its static blocks.
5434    ///
5435    /// `define_field` rather than `put_field`: a field is an own property created
5436    /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
5437    /// `x = 1` field must not call the setter.
5438    ///
5439    /// One function serves the whole class: it is called once per instance (or once, for
5440    /// the static half) and walks the members in source order. Static blocks are compiled
5441    /// into the same function because they *are* part of the same sequence — `static a =
5442    /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
5443    /// different values, so the two kinds cannot be split apart.
5444    fn compile_field_initialiser(
5445        &mut self,
5446        items: &[StaticInitItem<'_>],
5447        span: Span,
5448        instance: bool,
5449        add_brand: bool,
5450    ) -> Result<CompiledFunction, SyntaxError> {
5451        self.compile_synthetic_function("", true, span, |compiler| {
5452            if instance {
5453                // An instance initialiser always carries a `<home_object>` local, because the
5454                // brand block below reads it — even when that block turns out to be dead. The
5455                // reference has the same artefact, and the store is visible in its dump.
5456                let current = compiler.stack.len() - 1;
5457                compiler.stack[current].needs_home_object_local = true;
5458            }
5459            compiler.begin_this_local();
5460            if instance {
5461                // `this` gets the brand the prototype created, before any field is defined —
5462                // which is what makes `#m()` usable from inside a field initialiser.
5463                //
5464                // The reference always emits `push_false; if_false L; this; home; add_brand;
5465                // L:` and patches the `push_false` to `push_true` from the class parse when
5466                // the class has private methods; either way the branch folds, but the *mark*
5467                // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
5468                // `this` local from being fused into a `set_loc`.
5469                let skip = compiler.new_label();
5470                if add_brand {
5471                    compiler.emit(Opcode::PushTrue, &[]);
5472                } else {
5473                    compiler.emit(Opcode::PushFalse, &[]);
5474                }
5475                compiler.emit_jump(Opcode::IfFalse, skip, &[]);
5476                compiler.emit_var(VarAction::Get, "this");
5477                compiler.emit_var(VarAction::Get, HOME_OBJECT);
5478                compiler.emit(Opcode::AddBrand, &[]);
5479                compiler.place_label(skip);
5480            }
5481            for item in items {
5482                match item {
5483                    StaticInitItem::Field(key, value) => {
5484                        // A private field is *defined*, not assigned: `define_private_field`
5485                        // reads `obj symbol value`, and its point is that it fails on a
5486                        // receiver that is not this class's — which `put_field` would not.
5487                        //
5488                        // The three shapes are the reference's: `define_field <atom>` for a
5489                        // static name, `define_array_el` for a key that is only known at run
5490                        // time (`obj key value`), `define_private_field` for `#x`, and a
5491                        // computed key is read from its binding rather than recomputed.
5492                        compiler.emit_var(VarAction::Get, "this");
5493                        match key {
5494                            FieldKey::Private(binding) | FieldKey::Computed(binding) => {
5495                                compiler.emit_var(VarAction::Get, binding);
5496                            }
5497                            FieldKey::Literal(_) => {}
5498                        }
5499                        match value {
5500                            Some(value) => compiler.expr(value)?,
5501                            None => compiler.emit(Opcode::Undefined, &[]),
5502                        }
5503                        match key {
5504                            FieldKey::Literal(literal) => {
5505                                let text = compiler.property_key_text(literal, span)?;
5506                                compiler
5507                                    .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
5508                            }
5509                            FieldKey::Computed(_) => {
5510                                compiler.emit(Opcode::DefineArrayEl, &[]);
5511                                // `define_array_el` leaves `obj key`; the key is consumed by
5512                                // the copy the pattern machinery wants, so both go.
5513                                compiler.emit(Opcode::Drop, &[]);
5514                            }
5515                            FieldKey::Private(_) => {
5516                                compiler.emit(Opcode::DefinePrivateField, &[]);
5517                            }
5518                        }
5519                        compiler.emit(Opcode::Drop, &[]);
5520                    }
5521                    StaticInitItem::Block { body, body_start } => {
5522                        let block = compiler.compile_static_block(body, *body_start)?;
5523                        let index = compiler.push_constant(Constant::Function(Box::new(block)));
5524                        // `this fclosure`, so `call_method` finds the receiver below the
5525                        // callee: the block runs with `this` bound to the class.
5526                        compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
5527                        compiler.emit_var(VarAction::Get, "this");
5528                        compiler.emit(Opcode::Swap, &[]);
5529                        compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
5530                        // Nothing the block evaluates is wanted; its effects are the point.
5531                        compiler.emit(Opcode::Drop, &[]);
5532                    }
5533                }
5534            }
5535            Ok(())
5536        })
5537    }
5538
5539    /// Compile a `static { … }` body into the function the class calls for it.
5540    ///
5541    /// Shaped like an arrow, because that is the one function form with no `this`,
5542    /// `new.target` or `arguments` of its own: all three reach the enclosing static
5543    /// initialiser, and through it the class. `arguments` never gets that far — the parser
5544    /// rejects the reference — but `this` and `super` both depend on it.
5545    ///
5546    /// The body is hoisted like a function body's, because the reference parses it as one:
5547    /// `var` inside a block is a local of the block's function, not of whatever encloses
5548    /// the class.
5549    fn compile_static_block(
5550        &mut self,
5551        body: &[Stmt],
5552        body_start: Position,
5553    ) -> Result<CompiledFunction, SyntaxError> {
5554        let mut state = FnState::new(String::new(), FunctionKind::Normal);
5555        // Class bodies are strict, so a static block is too.
5556        state.strict = true;
5557        // The one property that makes this an arrow: nothing of its own to bind `this` to,
5558        // so `this` and `super` come from the initialiser that calls it.
5559        state.is_arrow = true;
5560        state.created_in_block = self.cur().current_block;
5561        state.with_names = self.cur().with_names.clone();
5562        state.line = body_start.line;
5563        state.column = body_start.column;
5564        let depth = self.stack.len();
5565        self.stack.push(state);
5566        let body_key = body_start.offset as u64;
5567        self.push_block(body_key, NO_PARENT);
5568        self.state().body_block = body_key;
5569        let result = (|| {
5570            self.hoist(body, body_key)?;
5571            self.emit_scope_enter(body_key);
5572            for statement in body {
5573                self.stmt(statement)?;
5574            }
5575            if self.end_is_reachable() {
5576                self.emit(Opcode::ReturnUndef, &[]);
5577            }
5578            Ok(())
5579        })();
5580        if result.is_err() {
5581            self.stack.truncate(depth);
5582            return result.map(|()| unreachable!());
5583        }
5584        Ok(self.finish_current())
5585    }
5586
5587    /// Compile a class, leaving the constructor on the stack when `keep`.
5588    ///
5589    /// The shape follows the reference: the class body is its own scope holding the
5590    /// class's *inner* name as a `const` — which is what lets a method refer to the
5591    /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
5592    /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
5593    /// on the top of the stack: the prototype for instance members, the constructor
5594    /// itself for `static` ones, which is why a static member costs an extra `swap`.
5595    fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
5596        let parent_block = self.cur().current_block;
5597        let key = class.span.start.offset as u64;
5598        self.push_block(key, parent_block);
5599        let name = class.name.as_ref().map(|ident| ident.name.clone());
5600        // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
5601        // resolves `E` without a global lookup. An *unnamed* class expression has no such
5602        // binding, and `define_class` is handed the empty name.
5603        if let Some(name) = &name {
5604            self.declare(name, VarDef::constant(name.clone()));
5605        }
5606        self.emit_scope_enter(key);
5607
5608        // The heritage clause is evaluated outside the class's own scope: it cannot see
5609        // the class binding it is about to initialise.
5610        let saved_block = self.cur().current_block;
5611        self.state().current_block = parent_block;
5612        match &class.super_class {
5613            Some(parent) => self.expr(parent)?,
5614            None => self.emit(Opcode::Undefined, &[]),
5615        }
5616        self.state().current_block = saved_block;
5617        let has_heritage = class.super_class.is_some();
5618
5619        // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
5620        // lands after the heritage's code — which is where the reference puts it, because it
5621        // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
5622        // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
5623        // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
5624        // came out in the opposite order from the reference's.
5625        //
5626        // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
5627        // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
5628        // a const accepts — so the old comment's worry ("a const would refuse the second
5629        // store") did not apply: there is no second store.
5630        // Every `#name` the class declares gets a `const` binding in the class scope, and so
5631        // does every computed field key. That is how the reference does it
5632        // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
5633        // what makes a private name resolve like any other class-scope variable — including
5634        // through a nested function's closure — while remaining invisible outside.
5635        //
5636        // All of them are declared *before* `<class_fields_init>`, in member order, because
5637        // that is when the reference's parser creates them.
5638        let plan = ClassPlan::build(class);
5639        // The body's private names are visible from here to the end of the class, and shadow
5640        // any outer class's of the same spelling. Pushed *before* the constructor is compiled
5641        // — it is compiled first because `define_class` consumes it, but its body can name
5642        // `#x` like any other member's.
5643        self.private_scopes.push(plan.uses.clone());
5644        let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
5645        for binding in &plan.bindings {
5646            class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
5647        }
5648        let fci = self.declare(
5649            "<class_fields_init>",
5650            VarDef::constant("<class_fields_init>"),
5651        );
5652        // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
5653        // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
5654        // members' bindings follow in reverse.
5655        self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
5656        for slot in class_slots.iter().rev() {
5657            self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
5658        }
5659
5660        // The constructor is compiled before `define_class` because that instruction
5661        // consumes it; a class without one gets the implicit version.
5662        let constructor = class.elements.iter().find_map(|element| match element {
5663            ClassElement::Method {
5664                kind: MethodKind::Constructor,
5665                func,
5666                ..
5667            } => Some(&**func),
5668            _ => None,
5669        });
5670        // A constructor is compiled differently from a method: it owns `this`. The flags
5671        // go on the *enclosing* state because a constructor is a nested function and
5672        // `compile_function_with_name` starts a fresh one.
5673        let ctor = match constructor {
5674            Some(func) => self.compile_class_constructor(func, has_heritage)?,
5675            None => self.compile_implicit_constructor(class, has_heritage)?,
5676        };
5677        // A closure, not the bare constant: the constructor captures
5678        // `<class_fields_init>`, which is only filled after `define_class` has run, so it
5679        // has to hold the cell rather than a copy of its value.
5680        //
5681        // The pool slot is left unassigned for now, because the reference gives the
5682        // constructor the *last* index of the members' range: `js_parse_class` emits a
5683        // `push_const` whose operand is patched at the end of the class parse, after every
5684        // method has taken a slot. Emitting the members first and the constant second is how
5685        // the numbering comes out the same; the instruction itself stays where it is.
5686        let ctor_insn = self.cur().insns.len();
5687        self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
5688        let flags = if has_heritage { 1 } else { 0 };
5689        self.emit(
5690            Opcode::DefineClass,
5691            &[
5692                Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
5693                Op::Int(flags),
5694            ],
5695        );
5696
5697        // Instance fields and static fields are two different functions: the first runs
5698        // per instance from the constructor, the second runs once, here.
5699        let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
5700        let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
5701        for (index, element) in class.elements.iter().enumerate() {
5702            match element {
5703                ClassElement::Method {
5704                    key: member_key,
5705                    is_static,
5706                    kind,
5707                    func,
5708                    span,
5709                } => {
5710                    if *kind == MethodKind::Constructor {
5711                        continue;
5712                    }
5713                    // `static(x)` is a *method* named `static`, not a static method; the
5714                    // parser already decided which by putting it in `kind`.
5715                    if *is_static {
5716                        self.emit(Opcode::Swap, &[]);
5717                    }
5718                    // A computed key is evaluated *here*, before the method's closure
5719                    // exists, and stays under it: `define_method_computed` pops
5720                    // `function, key, object`, so the stack has to read
5721                    // `[class, prototype, key, function]`. Evaluating the key after the
5722                    // `fclosure` and swapping the two put the prototype *below* the
5723                    // closure, which defined the method on the function and lost the
5724                    // prototype: `class C { [k]() {} }` left `C` undefined. The order is
5725                    // also the spec's — a class body evaluates every element's name before
5726                    // that element's function.
5727                    if let PropName::Computed(key) = member_key {
5728                        self.expr(key)?;
5729                    }
5730                    let function = self.compile_function_with_name(func, true)?;
5731                    let index = self.push_constant(Constant::Function(Box::new(function)));
5732                    self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5733                    match member_key {
5734                        // A private method is not a property of the prototype: it is a
5735                        // closure in the class scope, which is why nothing outside can reach
5736                        // it and why a use site has to brand-check. `set_name` gives the
5737                        // function its `name` (`#m`), which an accessor does not get — the
5738                        // reference leaves that commented out.
5739                        PropName::Private(ident) => {
5740                            let name = format!("#{}", ident.name);
5741                            // `set_home_object` first: the brand check reads the function's
5742                            // home object, and for a method that is the prototype.
5743                            self.emit(Opcode::SetHomeObject, &[]);
5744                            let binding = if *kind == MethodKind::Set {
5745                                format!("{name}<set>")
5746                            } else {
5747                                name.clone()
5748                            };
5749                            if *kind == MethodKind::Method {
5750                                self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
5751                            }
5752                            self.emit_var(VarAction::PutInit, &binding);
5753                        }
5754                        PropName::Computed(_) => {
5755                            self.emit(
5756                                Opcode::DefineMethodComputed,
5757                                &[Op::Int(class_method_flags(*kind))],
5758                            );
5759                        }
5760                        PropName::Literal(literal) => {
5761                            let text = self.property_key_text(literal, *span)?;
5762                            self.emit(
5763                                Opcode::DefineMethod,
5764                                &[
5765                                    Op::Atom(Atom::from_wtf8(&text)),
5766                                    Op::Int(class_method_flags(*kind)),
5767                                ],
5768                            );
5769                        }
5770                    }
5771                    if *is_static {
5772                        self.emit(Opcode::Swap, &[]);
5773                    }
5774                }
5775                ClassElement::Field {
5776                    key: field_key,
5777                    is_static,
5778                    value,
5779                    ..
5780                } => {
5781                    // A private field's *symbol* is created here, at the member, and stored
5782                    // in its binding: the field's property is keyed by it, so it has to exist
5783                    // before any initialiser runs, and a fresh one per class body is what
5784                    // makes two classes that both write `#x` independent.
5785                    //
5786                    // A computed key is evaluated once, here, and `to_propkey`'d once — a key
5787                    // whose `toString` has a side effect must not run again per instance.
5788                    let key = match field_key {
5789                        PropName::Private(ident) => {
5790                            let binding = format!("#{}", ident.name);
5791                            if *is_static {
5792                                self.emit(Opcode::Swap, &[]);
5793                            }
5794                            self.emit(
5795                                Opcode::PrivateSymbol,
5796                                &[Op::Atom(Atom::from_text(&binding))],
5797                            );
5798                            self.emit_var(VarAction::PutInit, &binding);
5799                            if *is_static {
5800                                self.emit(Opcode::Swap, &[]);
5801                            }
5802                            FieldKey::Private(binding)
5803                        }
5804                        PropName::Computed(expression) => {
5805                            let binding = plan
5806                                .computed
5807                                .get(&index)
5808                                .cloned()
5809                                .expect("every computed key got a binding");
5810                            if *is_static {
5811                                self.emit(Opcode::Swap, &[]);
5812                            }
5813                            self.expr(expression)?;
5814                            self.emit(Opcode::ToPropkey, &[]);
5815                            self.emit_var(VarAction::PutInit, &binding);
5816                            if *is_static {
5817                                self.emit(Opcode::Swap, &[]);
5818                            }
5819                            FieldKey::Computed(binding)
5820                        }
5821                        PropName::Literal(literal) => FieldKey::Literal(literal),
5822                    };
5823                    if *is_static {
5824                        static_items.push(StaticInitItem::Field(key, value.as_deref()));
5825                    } else {
5826                        instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
5827                    }
5828                }
5829                ClassElement::StaticBlock {
5830                    body, body_start, ..
5831                } => static_items.push(StaticInitItem::Block {
5832                    body,
5833                    body_start: *body_start,
5834                }),
5835            }
5836        }
5837
5838        // Now that every member has its slot, the constructor can have the next one and the
5839        // `fclosure` above can name it.
5840        let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
5841        match self.state().insns.get_mut(ctor_insn) {
5842            Some(Insn::Fixed { operands, .. }) => {
5843                operands[0] = Op::Const(ctor_index);
5844            }
5845            // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
5846            // loudly beats emitting a `fclosure` of slot 4294967295.
5847            _ => {
5848                return Err(SyntaxError::new(
5849                    "the class constructor's fclosure went missing",
5850                    class.span,
5851                ));
5852            }
5853        }
5854
5855        // The instance brand: a symbol created once on the prototype, which every instance
5856        // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
5857        // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
5858        // copy is created. The prototype is on top of the stack at this point.
5859        if plan.instance_brand {
5860            self.emit(Opcode::Dup, &[]);
5861            self.emit(Opcode::Null, &[]);
5862            self.emit(Opcode::Swap, &[]);
5863            self.emit(Opcode::AddBrand, &[]);
5864        }
5865
5866        // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
5867        // class has no instance fields. The constructor calls it only when it is defined.
5868        //
5869        // A class with private *methods* but no fields still needs one, because adding the
5870        // brand to each new instance is the initialiser's job.
5871        if instance_fields.is_empty() && !plan.instance_brand {
5872            self.emit(Opcode::Undefined, &[]);
5873        } else {
5874            let initialiser = self.compile_field_initialiser(
5875                &instance_fields,
5876                class.span,
5877                true,
5878                plan.instance_brand,
5879            )?;
5880            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
5881            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5882            // `set_home_object` reads `obj func`, so the prototype stays where it is.
5883            self.emit(Opcode::SetHomeObject, &[]);
5884        }
5885        self.emit_var(VarAction::PutInit, "<class_fields_init>");
5886        // The prototype has done its job: every instance member is defined on it. What
5887        // is left under it is the constructor.
5888        self.emit(Opcode::Drop, &[]);
5889
5890        // The static brand, for `static #m() {}`: same opcode, but the home object is the
5891        // constructor itself, so the symbol lands on the class and the class carries it.
5892        if plan.static_brand {
5893            self.emit(Opcode::Dup, &[]);
5894            self.emit(Opcode::Dup, &[]);
5895            self.emit(Opcode::AddBrand, &[]);
5896        }
5897
5898        // The class binding is initialised *before* static fields run, so a static field
5899        // can refer to the class by name (`static y = S.x`).
5900        // `set_loc` leaves the constructor on the stack, which is what the static field
5901        // call and the outer store both consume.
5902        //
5903        // Only when there *is* such a binding: an anonymous class expression declares no
5904        // class-scope name, and asking for one by the empty string resolved to nothing —
5905        // which made `var x = class {}` assign `undefined` and put a bogus global store in
5906        // the instruction stream.
5907        if let Some(name) = &name {
5908            self.emit_var(VarAction::SetInit, name);
5909        }
5910        if !static_items.is_empty() {
5911            // The static half has no brand prologue of its own: the constructor got its
5912            // brand above, before this runs.
5913            let initialiser =
5914                self.compile_field_initialiser(&static_items, class.span, false, false)?;
5915            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
5916            self.emit(Opcode::Dup, &[]);
5917            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5918            self.emit(Opcode::SetHomeObject, &[]);
5919            self.emit(Opcode::CallMethod, &[Op::Int(0)]);
5920            self.emit(Opcode::Drop, &[]);
5921        }
5922        // The body is over, and with it this class's private names.
5923        let _ = self.private_scopes.pop();
5924        self.emit_scope_leave(key);
5925        self.state().current_block = parent_block;
5926        if keep {
5927            // A class *expression* is its own value; the class-scope binding was only
5928            // ever an alias for it.
5929            return Ok(());
5930        }
5931        // A declaration stores into the binding the enclosing statement declared.
5932        self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
5933        Ok(())
5934    }
5935
5936    fn push_this(&mut self) {
5937        self.emit(Opcode::PushThis, &[]);
5938    }
5939
5940    /// `this`, which an arrow does not have of its own.
5941    ///
5942    /// The reference gives the enclosing function a local named `this`, initialised from
5943    /// `push_this` at the top of its body, and the arrow then reads it as a captured
5944    /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
5945    /// the arrow is called with none.
5946    fn this_expression(&mut self) {
5947        // In a class constructor `this` is a local: a derived constructor only gets one
5948        // when `super()` returns, and reading the raw receiver would give the *outer*
5949        // one instead.
5950        if self.cur().ctor_kind != CtorKind::None {
5951            self.emit_var(VarAction::Get, "this");
5952            return;
5953        }
5954        if !self.cur().is_arrow {
5955            self.push_this();
5956            return;
5957        }
5958        if let Some(target) = self.enclosing_function() {
5959            self.state_at(target).needs_this_local = true;
5960            self.declare_at(target, "this");
5961        }
5962        self.emit_var(VarAction::Get, "this");
5963    }
5964
5965    /// `new.target`, which an arrow likewise does not own.
5966    fn new_target_expression(&mut self) {
5967        if !self.cur().is_arrow {
5968            self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
5969            return;
5970        }
5971        if let Some(target) = self.enclosing_function() {
5972            self.state_at(target).needs_new_target_local = true;
5973            self.declare_at(target, NEW_TARGET);
5974        }
5975        self.emit_var(VarAction::Get, NEW_TARGET);
5976    }
5977
5978    /// `this.active_func`: the function `super()` resolves against.
5979    ///
5980    /// In a constructor or a method that is the function being run, so the special object
5981    /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
5982    /// a closure variable — see [`FnState::needs_active_func_local`].
5983    fn active_func_expression(&mut self) {
5984        if !self.cur().is_arrow {
5985            self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
5986            return;
5987        }
5988        if let Some(target) = self.enclosing_function() {
5989            self.state_at(target).needs_active_func_local = true;
5990            self.declare_at(target, ACTIVE_FUNC);
5991        }
5992        self.emit_var(VarAction::Get, ACTIVE_FUNC);
5993    }
5994
5995    /// Give the function a local `<active_func>`, for an arrow inside it to capture.
5996    fn provide_active_func_local(&mut self) {
5997        let current = self.stack.len() - 1;
5998        if !self.stack[current].needs_active_func_local {
5999            return;
6000        }
6001        if !self.stack[current]
6002            .vars
6003            .iter()
6004            .any(|var| var.name == ACTIVE_FUNC)
6005        {
6006            self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
6007        }
6008        self.prepend_initialiser(
6009            ACTIVE_FUNC,
6010            Insn::Fixed {
6011                op: Opcode::SpecialObject,
6012                operands: vec![Op::Int(2)],
6013            },
6014        );
6015    }
6016
6017    /// Give the function a local `new.target`, for an arrow inside it to capture.
6018    fn provide_new_target_local(&mut self) {
6019        let current = self.stack.len() - 1;
6020        if !self.stack[current].needs_new_target_local {
6021            return;
6022        }
6023        if !self.stack[current]
6024            .vars
6025            .iter()
6026            .any(|var| var.name == NEW_TARGET)
6027        {
6028            self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
6029        }
6030        self.prepend_initialiser(
6031            NEW_TARGET,
6032            Insn::Fixed {
6033                op: Opcode::SpecialObject,
6034                operands: vec![Op::Int(3)],
6035            },
6036        );
6037    }
6038
6039    /// `arguments` reached from an arrow, which likewise belongs to the enclosing
6040    /// function.
6041    fn ensure_enclosing_arguments(&mut self) {
6042        // An arrow created in a parameter list needs the *parameter* scope's
6043        // `arguments`, not the body's: the two are separate bindings and the arrow was
6044        // born before the body existed.
6045        let from_params = self.cur().created_in_params;
6046        if let Some(target) = self.enclosing_function() {
6047            self.state_at(target).needs_arguments_local = true;
6048            if from_params {
6049                self.state_at(target).needs_param_arguments = true;
6050                // Declare it now, not at the enclosing function's `finish_current`: the
6051                // arrow resolves its own `arguments` before that runs, and a binding that
6052                // does not exist yet resolves as a global.
6053                declare_param_var_at(&mut self.stack[target], "arguments");
6054            }
6055            self.declare_at(target, "arguments");
6056        }
6057    }
6058
6059    /// The innermost enclosing frame that is a real function — an arrow inherits from it
6060    /// rather than starting a scope of its own.
6061    fn enclosing_function(&self) -> Option<usize> {
6062        (0..self.stack.len())
6063            .rev()
6064            .find(|index| !self.stack[*index].is_arrow && !self.stack[*index].is_script)
6065    }
6066
6067    fn state_at(&mut self, index: usize) -> &mut FnState {
6068        &mut self.stack[index]
6069    }
6070
6071    /// Declare a `var` binding directly in a specific frame.
6072    fn declare_at(&mut self, index: usize, name: &str) {
6073        let state = &mut self.stack[index];
6074        if state.vars.iter().any(|var| var.name == name) {
6075            return;
6076        }
6077        state.var_block.push(FUNCTION_SCOPE);
6078        state.vars.push(VarDef::var(name));
6079    }
6080
6081    /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
6082    /// the reference calls a `special_object` gets initialised on entry.
6083    fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
6084        let current = self.stack.len() - 1;
6085        let init = [
6086            producer,
6087            Insn::Var {
6088                action: VarAction::Put,
6089                name: name.to_string(),
6090                block: 0,
6091                // A prologue initialiser runs before the body proper, but it is body
6092                // code: `this` and `arguments` are provided for it, not by it.
6093                in_params: false,
6094            },
6095        ];
6096        let inserted = init.len();
6097        for (index, instruction) in init.into_iter().enumerate() {
6098            self.stack[current].insns.insert(index, instruction);
6099        }
6100        for placed in self.stack[current].labels.iter_mut().flatten() {
6101            *placed += inserted;
6102        }
6103        self.stack[current].label_since_insn = true;
6104    }
6105
6106    fn push_constant(&mut self, constant: Constant) -> u32 {
6107        let state = self.state();
6108        let index = state.cpool.len() as u32;
6109        state.cpool.push(constant);
6110        index
6111    }
6112
6113    /// Compile `a && b`, `a || b`, `a ?? b`.
6114    ///
6115    /// A run of the *same* operator shares one end label, so `a || b || c` tests
6116    /// `a` once and jumps past everything when it is truthy, instead of falling
6117    /// into `b`'s test. The parser builds such a run left-associated —
6118    /// `((a || b) || c)` — so the operands are collected off the left spine.
6119    ///
6120    /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
6121    /// `||`'s label, because the inner chain really does end before `&&` begins.
6122    fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
6123        let mut operands = Vec::new();
6124        collect_same_operator(op, left, &mut operands);
6125        operands.push(right);
6126
6127        let end = self.new_label();
6128        // Every operand but the last decides whether the chain stops here.
6129        let last = operands.pop().expect("the right operand is always present");
6130        for operand in operands {
6131            self.expr(operand)?;
6132            self.emit(Opcode::Dup, &[]);
6133            match op {
6134                LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
6135                LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
6136                // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
6137                // `0 || b` is `b`. The dedicated test keeps the value unless it is
6138                // null-ish, so the jump is taken on `false`.
6139                LogicalOp::Coalesce => {
6140                    self.emit(Opcode::IsUndefinedOrNull, &[]);
6141                    self.emit_jump(Opcode::IfFalse, end, &[]);
6142                }
6143            }
6144            self.emit(Opcode::Drop, &[]);
6145        }
6146        self.expr(last)?;
6147        self.place_label(end);
6148        Ok(())
6149    }
6150
6151    fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
6152        match op {
6153            UnaryOp::Typeof => {
6154                // `typeof x` must not throw on an undeclared name.
6155                if let ExprKind::Ident(name) = &argument.kind {
6156                    self.emit_var(VarAction::GetUndef, &name.name);
6157                } else {
6158                    self.expr(argument)?;
6159                }
6160                self.emit(Opcode::Typeof, &[]);
6161            }
6162            UnaryOp::Delete => {
6163                // `delete obj.prop` really deletes, and answers whether it could.
6164                // Deleting a *binding* is always `false`: a local, an argument and a
6165                // declared global are all non-configurable, which the reference encodes
6166                // as a constant `push_false` rather than a runtime check. Only a
6167                // property access has anything to do at run time.
6168                // `delete super.x` is not a delete at all: the spec refuses it, and the
6169                // reference encodes the refusal as a `throw_error`. The receiver and the
6170                // key are still evaluated first, which is what keeps the evaluation order
6171                // of the operand intact.
6172                // `delete z?.b.c` answers `true` when the chain short-circuits: there is
6173                // nothing to delete, and a failed delete is not the same as a skipped
6174                // one. The reference emits the guards so they land on a `drop; push_true`
6175                // tail, which is what this reproduces.
6176                if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
6177                    && let ExprKind::Member {
6178                        object, property, ..
6179                    } = &inner.unparen().kind
6180                {
6181                    let end = self.new_label();
6182                    let done = self.new_label();
6183                    self.chain_link(object, end)?;
6184                    match property {
6185                        MemberProp::Ident(name) => self.emit(
6186                            Opcode::PushAtomValue,
6187                            &[Op::Atom(Atom::from_text(&name.name))],
6188                        ),
6189                        MemberProp::Computed(index) => self.expr(index)?,
6190                        MemberProp::Private(_) => {
6191                            return Err(SyntaxError::new(
6192                                "deleting a private field is not allowed",
6193                                argument.span,
6194                            ));
6195                        }
6196                    }
6197                    self.emit(Opcode::Delete, &[]);
6198                    self.emit_jump(Opcode::Goto, done, &[]);
6199                    self.place_label(end);
6200                    self.emit(Opcode::Drop, &[]);
6201                    self.emit(Opcode::PushTrue, &[]);
6202                    self.place_label(done);
6203                    return Ok(());
6204                }
6205                if let ExprKind::Member { object, .. } = &argument.unparen().kind
6206                    && matches!(object.unparen().kind, ExprKind::SuperProp)
6207                {
6208                    self.super_base();
6209                    self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
6210                    return Ok(());
6211                }
6212                match &argument.kind {
6213                    ExprKind::Member {
6214                        object, property, ..
6215                    } => {
6216                        self.expr(object)?;
6217                        match property {
6218                            MemberProp::Ident(name) => {
6219                                self.emit(
6220                                    Opcode::PushAtomValue,
6221                                    &[Op::Atom(Atom::from_text(&name.name))],
6222                                );
6223                            }
6224                            MemberProp::Computed(index) => self.expr(index)?,
6225                            MemberProp::Private(_) => {
6226                                return Err(SyntaxError::new(
6227                                    "deleting a private field is not allowed",
6228                                    argument.span,
6229                                ));
6230                            }
6231                        }
6232                        self.emit(Opcode::Delete, &[]);
6233                    }
6234                    ExprKind::Ident(name) => {
6235                        // `delete name`: a declared global, a local and an argument all
6236                        // answer `false`, but an *implicit* global (`x = 1` with no
6237                        // declaration) is a configurable property of the global object
6238                        // and really goes away. Which of those a name is only the
6239                        // resolver knows, so the decision waits for it.
6240                        let pos = self.cur().cur_pos;
6241                        self.state().insns.push(Insn::DeleteVar {
6242                            name: name.name.clone(),
6243                        });
6244                        self.state().insn_pos.push(pos);
6245                    }
6246                    _ => self.emit(Opcode::PushFalse, &[]),
6247                }
6248            }
6249            UnaryOp::Void => {
6250                self.expr(argument)?;
6251                self.emit(Opcode::Drop, &[]);
6252                self.emit(Opcode::Undefined, &[]);
6253            }
6254            UnaryOp::Minus => {
6255                self.expr(argument)?;
6256                self.emit(Opcode::Neg, &[]);
6257            }
6258            UnaryOp::Plus => {
6259                self.expr(argument)?;
6260                self.emit(Opcode::Plus, &[]);
6261            }
6262            UnaryOp::Not => {
6263                self.expr(argument)?;
6264                self.emit(Opcode::Lnot, &[]);
6265            }
6266            UnaryOp::BitNot => {
6267                self.expr(argument)?;
6268                self.emit(Opcode::Not, &[]);
6269            }
6270        }
6271        Ok(())
6272    }
6273
6274    /// Compile an assignment.
6275    ///
6276    /// Three operator families, three shapes:
6277    ///
6278    /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
6279    ///   the value is kept, because `put_field`/`put_array_el` consume both the
6280    ///   object and the value: `insert2` is `obj a -> a obj a`, so the store sees
6281    ///   the pair it wants and leaves a copy on top.
6282    /// * **compound** `+=` … — read the place, apply the operator, store. A member
6283    ///   reads through `get_field2`/`get_array_el3`, which leave the object (and
6284    ///   index) underneath the value precisely so the store can follow.
6285    /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
6286    ///   right-hand side. The test *keeps* the current value and skips the store
6287    ///   entirely, which is the whole point: `a ||= b` must not evaluate `b` when
6288    ///   `a` is already truthy.
6289    fn assign(&mut self, op: AssignOp, target: &Pattern, value: &Expr) -> Result<(), SyntaxError> {
6290        // Reading the flag clears it: only the outermost assignment of an
6291        // expression statement may drop its value.
6292        let keep = !std::mem::take(&mut self.state().discard_value);
6293        match &target.kind {
6294            PatternKind::Ident(name) => {
6295                // A *simple* store is blamed on the identifier, not on the `=`: a
6296                // strict-mode `not_def = 1` raises when the name is written, which the
6297                // reference reports at the name's column. A compound store is blamed on
6298                // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
6299                // which the reference reports at the `+=`), so only the simple case
6300                // moves the position.
6301                let saved = self.cur().cur_pos;
6302                let name_pos = Some(name.span.start);
6303                if matches!(op, AssignOp::Assign) {
6304                    self.state().cur_pos = name_pos;
6305                }
6306                // A *compound* store reads the binding before it combines, and that read
6307                // is blamed on the identifier: `not_def += 2` fails while reading
6308                // `not_def`, so the position is the name's, not the `+=`'s. The
6309                // combination that follows is blamed on the operator, which is why
6310                // `cur_pos` is put back to the operator position before it is emitted.
6311                self.state().cur_pos = name_pos;
6312                match op {
6313                    AssignOp::Assign => {
6314                        self.expr(value)?;
6315                        self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
6316                        // A discarded store to a *slot* consumes its value, so no copy
6317                        // is needed. A global store goes through `put_var`, which the
6318                        // reference always pairs with a `dup` — matching it keeps the
6319                        // bytecode identical. Getting this wrong is not only an extra
6320                        // instruction: a stray copy gives the peephole a chance to fold
6321                        // the store into an unrelated later read.
6322                        let slot = self.is_slot(&name.name);
6323                        if keep || !slot {
6324                            self.emit(Opcode::Dup, &[]);
6325                        }
6326                        self.state().no_value = !keep && slot;
6327                        self.emit_var(VarAction::Put, &name.name);
6328                    }
6329                    AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6330                        let end = self.new_label();
6331                        self.emit_var(VarAction::Get, &name.name);
6332                        self.state().cur_pos = saved;
6333                        self.emit(Opcode::Dup, &[]);
6334                        self.emit_logical_test(op);
6335                        self.emit_jump(logical_jump(op), end, &[]);
6336                        self.emit(Opcode::Drop, &[]);
6337                        self.expr(value)?;
6338                        self.emit(Opcode::Dup, &[]);
6339                        self.emit_var(VarAction::Put, &name.name);
6340                        self.place_label(end);
6341                    }
6342                    _ => {
6343                        self.emit_var(VarAction::Get, &name.name);
6344                        self.expr(value)?;
6345                        self.state().cur_pos = saved;
6346                        self.emit(compound_opcode(op), &[]);
6347                        self.emit(Opcode::Dup, &[]);
6348                        self.emit_var(VarAction::Put, &name.name);
6349                    }
6350                }
6351                self.state().cur_pos = saved;
6352                Ok(())
6353            }
6354            PatternKind::Member(member) => {
6355                // `super.x = v` is not a store through a value: it starts at the home
6356                // object's prototype but writes to `this`, so it goes through
6357                // `put_super_value` rather than `put_field`. The receiver, prototype, key
6358                // and value are handed over together.
6359                if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
6360                    return self.assign_super(member, op, value);
6361                }
6362                // A store is blamed on the selector punctuator (`.` or `[`), the same
6363                // token a load is blamed on — the reference records `put_field obj.a`
6364                // at the `.`, so a setter that throws reports that column and not the
6365                // `=` of the assignment it sits in. The inner expressions restore their
6366                // own positions, so the selector's sticks for the store instructions.
6367                let saved = self.cur().cur_pos;
6368                self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6369                self.expr(&member.object)?;
6370                match &member.property {
6371                    MemberProp::Ident(property) => {
6372                        let atom = Atom::from_text(&property.name);
6373                        match op {
6374                            AssignOp::Assign => {
6375                                self.expr(value)?;
6376                                // `put_field` consumes the object and the value, so
6377                                // without `insert2` nothing is left over for the
6378                                // statement to drop.
6379                                self.state().no_value = !keep;
6380                                if keep {
6381                                    self.emit(Opcode::Insert2, &[]);
6382                                }
6383                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6384                            }
6385                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6386                                // `get_field2` leaves the object under the value, so
6387                                // the keep path has an object to dispose of. The store
6388                                // path must jump *over* that cleanup: falling into it
6389                                // would `nip` a stack that only holds the value.
6390                                let (keep_label, end) = (self.new_label(), self.new_label());
6391                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6392                                self.emit(Opcode::Dup, &[]);
6393                                self.emit_logical_test(op);
6394                                self.emit_jump(logical_jump(op), keep_label, &[]);
6395                                self.emit(Opcode::Drop, &[]);
6396                                self.expr(value)?;
6397                                self.emit(Opcode::Insert2, &[]);
6398                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6399                                self.emit_jump(Opcode::Goto, end, &[]);
6400                                self.place_label(keep_label);
6401                                self.emit(Opcode::Nip, &[]);
6402                                self.place_label(end);
6403                            }
6404                            _ => {
6405                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6406                                self.expr(value)?;
6407                                self.emit(compound_opcode(op), &[]);
6408                                self.state().no_value = !keep;
6409                                if keep {
6410                                    self.emit(Opcode::Insert2, &[]);
6411                                }
6412                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6413                            }
6414                        }
6415                    }
6416                    MemberProp::Computed(index) => {
6417                        self.expr(index)?;
6418                        match op {
6419                            AssignOp::Assign => {
6420                                self.expr(value)?;
6421                                self.state().no_value = !keep;
6422                                if keep {
6423                                    self.emit(Opcode::Insert3, &[]);
6424                                }
6425                                self.emit(Opcode::PutArrayEl, &[]);
6426                            }
6427                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6428                                let (keep_label, end) = (self.new_label(), self.new_label());
6429                                self.emit(Opcode::GetArrayEl3, &[]);
6430                                self.emit(Opcode::Dup, &[]);
6431                                self.emit_logical_test(op);
6432                                self.emit_jump(logical_jump(op), keep_label, &[]);
6433                                self.emit(Opcode::Drop, &[]);
6434                                self.expr(value)?;
6435                                self.emit(Opcode::Insert3, &[]);
6436                                self.emit(Opcode::PutArrayEl, &[]);
6437                                self.emit_jump(Opcode::Goto, end, &[]);
6438                                self.place_label(keep_label);
6439                                // Both the object and the index are left over.
6440                                self.emit(Opcode::Nip, &[]);
6441                                self.emit(Opcode::Nip, &[]);
6442                                self.place_label(end);
6443                            }
6444                            _ => {
6445                                self.emit(Opcode::GetArrayEl3, &[]);
6446                                self.expr(value)?;
6447                                self.emit(compound_opcode(op), &[]);
6448                                self.state().no_value = !keep;
6449                                if keep {
6450                                    self.emit(Opcode::Insert3, &[]);
6451                                }
6452                                self.emit(Opcode::PutArrayEl, &[]);
6453                            }
6454                        }
6455                    }
6456                    MemberProp::Private(name) => {
6457                        // `obj value` is on the stack, and every private store wants exactly
6458                        // that. A top-level private name cannot be assigned (the parser rejects
6459                        // `#x = 1`), so the only way here is `this.#x = …` inside the class.
6460                        //
6461                        // The reference emits `insert2` whether or not the value is wanted,
6462                        // so this does too: the copy left behind is the assignment expression's
6463                        // value, and a discarded one is simply never read.
6464                        let binding = format!("#{}", name.name);
6465                        let (kind, setter) = self.private_use(&binding, member.span)?;
6466                        match op {
6467                            AssignOp::Assign => {
6468                                self.expr(value)?;
6469                                if keep {
6470                                    self.emit(Opcode::Insert2, &[]);
6471                                }
6472                                self.private_store(&binding, kind, setter.as_deref())?;
6473                                self.state().no_value = !keep;
6474                            }
6475                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6476                                let (keep_label, end) = (self.new_label(), self.new_label());
6477                                self.emit(Opcode::Dup, &[]);
6478                                self.private_load(&binding, kind, member.span)?;
6479                                self.emit(Opcode::Dup, &[]);
6480                                self.emit_logical_test(op);
6481                                self.emit_jump(logical_jump(op), keep_label, &[]);
6482                                self.emit(Opcode::Drop, &[]);
6483                                self.expr(value)?;
6484                                self.emit(Opcode::Insert2, &[]);
6485                                self.private_store(&binding, kind, setter.as_deref())?;
6486                                self.emit_jump(Opcode::Goto, end, &[]);
6487                                self.place_label(keep_label);
6488                                self.emit(Opcode::Nip, &[]);
6489                                self.place_label(end);
6490                            }
6491                            _ => {
6492                                self.emit(Opcode::Dup, &[]);
6493                                self.private_load(&binding, kind, member.span)?;
6494                                self.expr(value)?;
6495                                self.emit(compound_opcode(op), &[]);
6496                                self.emit(Opcode::Insert2, &[]);
6497                                self.private_store(&binding, kind, setter.as_deref())?;
6498                            }
6499                        }
6500                    }
6501                }
6502                self.state().cur_pos = saved;
6503                Ok(())
6504            }
6505            // A destructuring assignment: the right-hand side is the expression's own
6506            // value, so it is evaluated once and kept under the pattern's stores.
6507            PatternKind::Array { .. } | PatternKind::Object { .. } => {
6508                self.expr(value)?;
6509                if keep {
6510                    self.emit(Opcode::Dup, &[]);
6511                }
6512                self.destructure(target, None)?;
6513                self.state().no_value = !keep;
6514                Ok(())
6515            }
6516            _ => Err(SyntaxError::new(
6517                "this assignment target is not supported by the compiler yet",
6518                target.span,
6519            )),
6520        }
6521    }
6522
6523    /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
6524    ///
6525    /// The stack has to carry four values — receiver, prototype, key, value — because
6526    /// `put_super_value` takes them together; the receiver is what makes a setter found on
6527    /// the prototype run with `this`, and the key has to survive until the store, which is
6528    /// why a compound form converts it to a property key once and `dup3`s rather than
6529    /// evaluating it twice.
6530    fn assign_super(
6531        &mut self,
6532        member: &MemberPattern,
6533        op: AssignOp,
6534        value: &Expr,
6535    ) -> Result<(), SyntaxError> {
6536        let saved = self.cur().cur_pos;
6537        self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6538        self.super_base();
6539        match &member.property {
6540            MemberProp::Ident(property) => self.emit(
6541                Opcode::PushAtomValue,
6542                &[Op::Atom(Atom::from_text(&property.name))],
6543            ),
6544            MemberProp::Computed(index) => self.expr(index)?,
6545            MemberProp::Private(_) => {
6546                return Err(SyntaxError::new(
6547                    "private fields are not supported by the compiler yet",
6548                    member.span,
6549                ));
6550            }
6551        }
6552        match op {
6553            AssignOp::Assign => {
6554                // The key is only converted once, by `put_super_value` itself, so a
6555                // computed key's `toString` runs exactly once.
6556                self.expr(value)?;
6557                self.emit(Opcode::Insert4, &[]);
6558                self.emit(Opcode::PutSuperValue, &[]);
6559            }
6560            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6561                let (keep_label, end) = (self.new_label(), self.new_label());
6562                self.emit(Opcode::ToPropkey, &[]);
6563                self.emit(Opcode::Dup3, &[]);
6564                self.emit(Opcode::GetSuperValue, &[]);
6565                self.emit(Opcode::Dup, &[]);
6566                self.emit_logical_test(op);
6567                self.emit_jump(logical_jump(op), keep_label, &[]);
6568                self.emit(Opcode::Drop, &[]);
6569                self.expr(value)?;
6570                self.emit(Opcode::Insert4, &[]);
6571                self.emit(Opcode::PutSuperValue, &[]);
6572                self.emit_jump(Opcode::Goto, end, &[]);
6573                self.place_label(keep_label);
6574                // The prototype and the key are still under the value that was read.
6575                self.emit(Opcode::Nip, &[]);
6576                self.emit(Opcode::Nip, &[]);
6577                self.emit(Opcode::Nip, &[]);
6578                self.place_label(end);
6579            }
6580            _ => {
6581                self.emit(Opcode::ToPropkey, &[]);
6582                self.emit(Opcode::Dup3, &[]);
6583                self.emit(Opcode::GetSuperValue, &[]);
6584                self.expr(value)?;
6585                self.emit(compound_opcode(op), &[]);
6586                self.emit(Opcode::Insert4, &[]);
6587                self.emit(Opcode::PutSuperValue, &[]);
6588            }
6589        }
6590        // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
6591        // is still on the stack when the store finishes, and the expression statement is
6592        // what disposes of it — the same arrangement as `put_field`, reached from the other
6593        // side: there the store consumes the value (`no_value`), here it leaves it
6594        // (`keep` already false, so nothing tells the statement otherwise).
6595        self.state().cur_pos = saved;
6596        Ok(())
6597    }
6598
6599    /// The test a logical assignment applies to the current value.
6600    ///
6601    /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
6602    /// assign, while `0 ||= b` must not.
6603    fn emit_logical_test(&mut self, op: AssignOp) {
6604        if op == AssignOp::Coalesce {
6605            self.emit(Opcode::IsUndefinedOrNull, &[]);
6606        }
6607    }
6608
6609    /// The private name `#name` this use site resolves against.
6610    ///
6611    /// The parser has already rejected a name no enclosing class declares, so a miss here
6612    /// means the compiler lost track of a class scope — which is worth a real error rather
6613    /// than an `unwrap`.
6614    fn private_use(
6615        &self,
6616        binding: &str,
6617        span: Span,
6618    ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
6619        ClassPlan::find(self, binding)
6620            .map(|use_| (use_.kind, use_.setter.clone()))
6621            .ok_or_else(|| {
6622                SyntaxError::new(
6623                    format!("the private name '{binding}' is out of scope here"),
6624                    span,
6625                )
6626            })
6627    }
6628
6629    /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
6630    ///
6631    /// The three readable kinds take three different instructions, because a private name
6632    /// holds three different things — a symbol, a method function, a getter function — and
6633    /// only the first one is a property read at all.
6634    fn private_load(
6635        &mut self,
6636        binding: &str,
6637        kind: PrivateKind,
6638        span: Span,
6639    ) -> Result<(), SyntaxError> {
6640        match kind {
6641            PrivateKind::Field => {
6642                self.emit_var(VarAction::Get, binding);
6643                self.emit(Opcode::GetPrivateField, &[]);
6644            }
6645            PrivateKind::Method => {
6646                self.emit_var(VarAction::Get, binding);
6647                self.emit(Opcode::CheckBrand, &[]);
6648                // `check_brand` reads `obj func` and leaves both; the method itself is what
6649                // `this.#m` evaluates to.
6650                self.emit(Opcode::Nip, &[]);
6651            }
6652            PrivateKind::Getter => {
6653                self.emit_var(VarAction::Get, binding);
6654                self.emit(Opcode::CheckBrand, &[]);
6655                self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6656            }
6657            // `#a` is declared but never filled when only a setter exists, so reading it is
6658            // the same refusal as assigning to a `const`. The reference reports it with the
6659            // generic read-only wording and leaves the better message as a `XXX`.
6660            PrivateKind::Setter => self.emit(
6661                Opcode::ThrowError,
6662                &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
6663            ),
6664        }
6665        let _ = span;
6666        Ok(())
6667    }
6668
6669    /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
6670    fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
6671        match kind {
6672            // A method *is* the callee, so only the check goes in between.
6673            PrivateKind::Method => {
6674                self.emit_var(VarAction::Get, binding);
6675                self.emit(Opcode::CheckBrand, &[]);
6676            }
6677            _ => self.private_load(binding, kind, Span::default())?,
6678        }
6679        Ok(())
6680    }
6681
6682    /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
6683    /// wanted back.
6684    ///
6685    /// A getter/setter pair is a *method call*, not a property store: the reference reads
6686    /// the setter out of its own binding and calls it with the receiver, which is why the
6687    /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
6688    /// keeps the assignment's value for an expression context.
6689    fn private_store(
6690        &mut self,
6691        binding: &str,
6692        kind: PrivateKind,
6693        setter: Option<&str>,
6694    ) -> Result<(), SyntaxError> {
6695        match kind {
6696            PrivateKind::Field => {
6697                self.emit_var(VarAction::Get, binding);
6698                self.emit(Opcode::PutPrivateField, &[]);
6699            }
6700            PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
6701                Some(setter) => {
6702                    self.emit_var(VarAction::Get, setter);
6703                    // `obj func value` -> `value obj func` for the check, and back again for
6704                    // the call, which wants `obj func arg`.
6705                    self.emit(Opcode::Swap, &[]);
6706                    self.emit(Opcode::Rot3r, &[]);
6707                    self.emit(Opcode::CheckBrand, &[]);
6708                    self.emit(Opcode::Rot3l, &[]);
6709                    self.emit(Opcode::CallMethod, &[Op::Int(1)]);
6710                    // The setter's return value is discarded; the assignment's own value is
6711                    // whatever the caller left underneath.
6712                    self.emit(Opcode::Drop, &[]);
6713                }
6714                None => self.emit(
6715                    Opcode::ThrowError,
6716                    &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
6717                ),
6718            },
6719        }
6720        Ok(())
6721    }
6722
6723    fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
6724        let instruction = match (op, prefix) {
6725            (UpdateOp::Increment, true) => Opcode::Inc,
6726            (UpdateOp::Increment, false) => Opcode::PostInc,
6727            (UpdateOp::Decrement, true) => Opcode::Dec,
6728            (UpdateOp::Decrement, false) => Opcode::PostDec,
6729        };
6730        if let ExprKind::Member {
6731            object,
6732            property,
6733            optional: _,
6734        } = &argument.kind
6735        {
6736            // `o.x++` needs the receiver twice, so the last link is read with the
6737            // `get_*2`/`get_*3` form that keeps it, and the update is written back
6738            // with `put_field`/`put_array_el`. The reordering in between is what puts
6739            // the old value below the receiver for a postfix update and the new one
6740            // above it for a prefix one:
6741            //
6742            //   `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
6743            //   `obj val` → `inc`      → `obj new new` → `insert2` → `new obj new`
6744            //
6745            // This mirrors the reference instruction for instruction.
6746            self.expr(object)?;
6747            match property {
6748                MemberProp::Ident(name) => {
6749                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
6750                    self.emit(instruction, &[]);
6751                    self.emit(
6752                        if prefix {
6753                            Opcode::Insert2
6754                        } else {
6755                            Opcode::Perm3
6756                        },
6757                        &[],
6758                    );
6759                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
6760                }
6761                MemberProp::Computed(index) => {
6762                    self.expr(index)?;
6763                    self.emit(Opcode::GetArrayEl3, &[]);
6764                    self.emit(instruction, &[]);
6765                    self.emit(
6766                        if prefix {
6767                            Opcode::Insert3
6768                        } else {
6769                            Opcode::Perm4
6770                        },
6771                        &[],
6772                    );
6773                    self.emit(Opcode::PutArrayEl, &[]);
6774                }
6775                MemberProp::Private(name) => {
6776                    // The receiver is duplicated and the read keeps it, exactly as `get_field2`
6777                    // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
6778                    // `perm3` -> `old obj new` -> store.
6779                    let binding = format!("#{}", name.name);
6780                    let (kind, setter) = self.private_use(&binding, argument.span)?;
6781                    self.emit(Opcode::Dup, &[]);
6782                    self.private_load(&binding, kind, argument.span)?;
6783                    self.emit(instruction, &[]);
6784                    self.emit(
6785                        if prefix {
6786                            Opcode::Insert2
6787                        } else {
6788                            Opcode::Perm3
6789                        },
6790                        &[],
6791                    );
6792                    self.private_store(&binding, kind, setter.as_deref())?;
6793                }
6794            }
6795            return Ok(());
6796        }
6797        let ExprKind::Ident(name) = &argument.kind else {
6798            return Err(SyntaxError::new(
6799                "increment of a non-variable is not supported by the compiler yet",
6800                argument.span,
6801            ));
6802        };
6803        // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
6804        // reference's `inc_loc` folds those three into one, but it does so only in some
6805        // positions (a `for` update and not a bare statement, and never for a lexical
6806        // binding), so emitting it unconditionally would move *away* from its output.
6807        // The instruction is equivalent either way; matching the reference matters more
6808        // than saving two instructions.
6809        let _ = !std::mem::take(&mut self.state().discard_value);
6810        self.emit_var(VarAction::Get, &name.name);
6811        self.emit(instruction, &[]);
6812        if prefix {
6813            self.emit(Opcode::Dup, &[]);
6814        }
6815        self.emit_var(VarAction::Put, &name.name);
6816        Ok(())
6817    }
6818
6819    /// Compile an array literal.
6820    ///
6821    /// The reference splits this into three phases, and the split is load-bearing
6822    /// rather than an optimisation detail:
6823    ///
6824    /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
6825    ///    the array in one instruction.
6826    /// 2. **Everything up to the first spread** is appended with explicit indices
6827    ///    (`define_field <index>`), because a hole has no element to pass to
6828    ///    `array_from`. A hole here is what makes `length` need fixing up: an
6829    ///    explicit index does not extend the array the way a pushed element does.
6830    /// 3. **From the first spread on** the index lives on the stack, so `append` and
6831    ///    `define_array_el` can consume it and `inc` advances it.
6832    ///
6833    /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
6834    /// forces phase 2, and `[...a]` forces phase 3.
6835    fn array_literal(
6836        &mut self,
6837        elements: &[Option<ArrayElement>],
6838        span: Span,
6839    ) -> Result<(), SyntaxError> {
6840        let _ = span;
6841        let mut index: u32 = 0;
6842        let mut cursor = 0usize;
6843
6844        // Phase 1: a leading run of plain elements, at most 32 of them.
6845        while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
6846            if index >= 32 {
6847                break;
6848            }
6849            self.expr(element)?;
6850            index += 1;
6851            cursor += 1;
6852        }
6853        self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
6854
6855        // Phase 2: explicit indices, up to the first spread.
6856        let mut need_length = false;
6857        while let Some(element) = elements.get(cursor) {
6858            if matches!(element, Some(ArrayElement::Spread(_))) {
6859                break;
6860            }
6861            need_length = true;
6862            if let Some(ArrayElement::Expr(expression)) = element {
6863                self.expr(expression)?;
6864                self.emit_define_index(index);
6865                need_length = false;
6866            }
6867            index += 1;
6868            cursor += 1;
6869        }
6870
6871        if cursor >= elements.len() {
6872            if need_length {
6873                // `define_field` cannot set `length`, which is not configurable.
6874                self.emit(Opcode::Dup, &[]);
6875                self.push_number(index as f64);
6876                self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
6877            }
6878            return Ok(());
6879        }
6880
6881        // Phase 3: the index moves onto the stack for the spreading tail.
6882        //
6883        // `need_length` deliberately carries over from phase 2: a hole before the
6884        // first spread still has to be reflected in `length`, and only the final
6885        // check can do it because the array is not finished until the tail is
6886        // appended.
6887        self.push_number(index as f64);
6888        while let Some(element) = elements.get(cursor) {
6889            match element {
6890                Some(ArrayElement::Spread(expression)) => {
6891                    // `append` copies an iterable and leaves the next index behind,
6892                    // so no `inc` is needed here.
6893                    self.expr(spread_argument(expression))?;
6894                    self.emit(Opcode::Append, &[]);
6895                }
6896                None | Some(ArrayElement::Expr(_)) => {
6897                    need_length = true;
6898                    if let Some(ArrayElement::Expr(expression)) = element {
6899                        self.expr(expression)?;
6900                        self.emit(Opcode::DefineArrayEl, &[]);
6901                        need_length = false;
6902                    }
6903                    self.emit(Opcode::Inc, &[]);
6904                }
6905            }
6906            cursor += 1;
6907        }
6908        if need_length {
6909            self.emit(Opcode::Dup1, &[]);
6910            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
6911        } else {
6912            self.emit(Opcode::Drop, &[]);
6913        }
6914        Ok(())
6915    }
6916
6917    /// `define_field` with an array-index atom, which is how phase 2 stores elements.
6918    fn emit_define_index(&mut self, index: u32) {
6919        self.emit(
6920            Opcode::DefineField,
6921            &[Op::Atom(Atom::from_text(&index.to_string()))],
6922        );
6923    }
6924
6925    // -- functions ---------------------------------------------------------
6926
6927    fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
6928        self.compile_function_with_name(func, false)
6929    }
6930
6931    /// Compile a function, recording whether it is a *named function expression*.
6932    ///
6933    /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
6934    /// must not leak outside. The reference does that by declaring `g` as a local of
6935    /// the function itself and initialising it with `special_object 2` (the current
6936    /// function), which is why this has to be known at compile time.
6937    fn compile_function_with_name(
6938        &mut self,
6939        func: &ast::Function,
6940        is_expression: bool,
6941    ) -> Result<CompiledFunction, SyntaxError> {
6942        let kind = match (func.is_generator, func.is_async) {
6943            (false, false) => FunctionKind::Normal,
6944            (true, false) => FunctionKind::Generator,
6945            (false, true) => FunctionKind::Async,
6946            (true, true) => FunctionKind::AsyncGenerator,
6947        };
6948        let mut state = FnState::new(
6949            func.name
6950                .as_ref()
6951                .map(|n| n.name.clone())
6952                .unwrap_or_default(),
6953            kind,
6954        );
6955        // The function's own mode, recorded by the parser. Inheriting the enclosing
6956        // function's instead let a nested `"use strict"` directive be ignored, so the
6957        // body ran with sloppy `this`, sloppy `arguments` and no const checks.
6958        state.strict = func.strict;
6959        // A function defined inside a `with` block keeps seeing that object: the guard
6960        // chain names the enclosing `<with>` locals, which resolve outward into closure
6961        // variables exactly like any other captured binding.
6962        state.with_names = self.cur().with_names.clone();
6963        state.is_arrow = func.is_arrow;
6964        state.created_in_block = self.cur().current_block;
6965        // A default anywhere in the parameter list is what gives the function two
6966        // variable environments. The reference decides this the same way: it scans the
6967        // parenthesis for a top-level `=`, so a destructured name without a default
6968        // stays a plain function-scope binding.
6969        state.in_params = false;
6970        // The reference scans the parenthesis for *any* `=`, including one nested inside
6971        // a pattern, so `function f({a = 1})` has parameter expressions even though the
6972        // parameter itself carries no initialiser.
6973        state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
6974        // A function born inside a parameter list inherits the prohibition: it must not
6975        // see the body bindings of the function it was created in.
6976        state.created_in_params = self.cur().in_params || self.cur().created_in_params;
6977        // A class constructor knows what it is only because the class told it.
6978        if let Some(kind) = self.cur().class_ctor_pending {
6979            state.ctor_kind = kind;
6980        }
6981        // A named *expression* binds its own name; a declaration's name is already
6982        // bound in the enclosing scope.
6983        state.self_name = if is_expression && !func.is_arrow {
6984            func.name.as_ref().map(|n| n.name.clone())
6985        } else {
6986            None
6987        };
6988        state.line = func.span.start.line;
6989        state.column = func.span.start.column;
6990        // A function body has no hidden `<ret>` local; the value comes back on
6991        // the stack. Only a script keeps one.
6992        // Parameters are positional, so even a pattern occupies one argument slot. A
6993        // simple name is that slot itself; anything else (a pattern, a default, a rest
6994        // parameter) takes an anonymous slot and is unpicked into locals at the top of
6995        // the body, which is the only way one argument can bind several names.
6996        let mut prologue: Vec<(usize, Pattern)> = Vec::new();
6997        // `.length` stops at the first parameter that can be substituted: a default
6998        // fills a missing argument in, and a rest parameter absorbs the rest.
6999        let mut defined_args = func.params.len() as u32;
7000        for (index, param) in func.params.iter().enumerate() {
7001            match simple_parameter(param) {
7002                Some(name) => state.args.push(VarDef::var(name.name.clone())),
7003                None => {
7004                    state.args.push(VarDef::var(ANONYMOUS_BINDING));
7005                    prologue.push((index, param.clone()));
7006                }
7007            }
7008        }
7009        // A default anywhere before the end also ends the count, which the loop above
7010        // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
7011        for (position, param) in func.params.iter().enumerate() {
7012            if matches!(
7013                param.kind,
7014                PatternKind::Assign { .. } | PatternKind::Rest(_)
7015            ) {
7016                defined_args = position as u32;
7017                break;
7018            }
7019        }
7020        state.defined_args = defined_args;
7021        state.param_prologue = prologue;
7022        let depth = self.stack.len();
7023        self.stack.push(state);
7024        let result = self.compile_function_body(func);
7025        if result.is_err() {
7026            // A failed compile must not leave its `FnState` behind. Every caller
7027            // reads `self.state()` as "the function being compiled", so a leftover
7028            // frame silently retargets all later bookkeeping at a dead function.
7029            self.stack.truncate(depth);
7030        }
7031        result
7032    }
7033
7034    /// The body of a function, with its frame already pushed.
7035    fn compile_function_body(
7036        &mut self,
7037        func: &ast::Function,
7038    ) -> Result<CompiledFunction, SyntaxError> {
7039        let body_key = func.params_span.end.offset as u64;
7040        // Where the body begins, in source order. The runtime needs this to tell a
7041        // closure created by a default expression from one the body creates — the two see
7042        // different variable environments — and a bytecode offset would not survive the
7043        // instruction shuffling that building the frame does. Positions are in source
7044        // order, so a comparison answers it.
7045        self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
7046        self.push_block(body_key, NO_PARENT);
7047        self.state().body_block = body_key;
7048        // An arrow with an expression body has no statements; the expression is
7049        // its `return`. Building the statement here keeps one code path below, and
7050        // matters for correctness beyond convenience: returning early with the new
7051        // `FnState` still on the stack would leave the compiler looking at the
7052        // wrong function, which surfaces as an unrelated underflow later.
7053        let concise = match &func.body {
7054            js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
7055                StmtKind::Return(Some(Box::new((**value).clone()))),
7056                value.span,
7057            )),
7058            js_parse::ast::FunctionBody::Block(_) => None,
7059        };
7060        let body: &[Stmt] = match &concise {
7061            Some(stmt) => std::slice::from_ref(stmt),
7062            None => func
7063                .body
7064                .statements()
7065                .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
7066        };
7067        let prologue = std::mem::take(&mut self.state().param_prologue);
7068        let has_param_scope = self.cur().has_parameter_expressions;
7069        // The parameter scope's own bindings, declared in source order.
7070        //
7071        // With parameter expressions the list gets a variable environment of its own, and
7072        // every name it binds is a `let` there. That is what puts the *list* in the
7073        // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
7074        // and `function f(x = y, y){}` does the same, where a single shared environment
7075        // would answer `undefined` to both.
7076        if has_param_scope {
7077            let mut declared: Vec<String> = Vec::new();
7078            for param in &func.params {
7079                let mut names = Vec::new();
7080                param.bound_names(&mut names);
7081                for name in names {
7082                    if declared.contains(&name.name) {
7083                        continue;
7084                    }
7085                    declared.push(name.name.clone());
7086                    self.declare_param_binding(&name.name);
7087                }
7088            }
7089        }
7090        // A pattern parameter binds its names as function-scope locals, so they have to
7091        // exist — and be unpicked from the argument — before the body runs. With a
7092        // parameter scope these are the *second* environment: the pattern fills the
7093        // parameter's copy, and the body's binding is filled from it afterwards.
7094        for (_, pattern) in &prologue {
7095            let mut names = Vec::new();
7096            pattern.bound_names(&mut names);
7097            for name in names {
7098                self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
7099            }
7100        }
7101        self.hoist(body, body_key)?;
7102        // A constructor's prologue is not a parameter unpacking but the `this` binding:
7103        // a base constructor takes the receiver, a derived one starts in the dead zone
7104        // because only `super()` may produce it.
7105        match self.cur().ctor_kind {
7106            CtorKind::None => {}
7107            CtorKind::Base => {
7108                self.begin_this_local();
7109                self.emit(Opcode::CheckCtor, &[]);
7110                // Instance fields are installed at the top of a base constructor's body,
7111                // before any statement — `class C { x = 1; constructor() { this.x } }` sees
7112                // `1`. This used to be emitted at the *tail*, which made every field read
7113                // `undefined` inside the constructor that declared it.
7114                self.call_field_initialiser();
7115            }
7116            CtorKind::Derived => {
7117                self.declare("this", VarDef::lexical("this"));
7118                let slot = self.cur().vars.len() as u32 - 1;
7119                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7120                self.emit(Opcode::CheckCtor, &[]);
7121            }
7122        }
7123        // Entering the parameter list: everything it binds starts in the dead zone.
7124        // The order is the reference's — it walks the scope chain, which is prepended, so
7125        // the bindings come out newest first.
7126        for name in self.param_binding_names().into_iter().rev() {
7127            if let Some(slot) = self.param_binding_slot(&name) {
7128                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7129            }
7130        }
7131        // The whole parameter list is one scope, and nothing in the body exists yet, so
7132        // every name it mentions resolves against the parameter bindings and outward.
7133        self.state().in_params = has_param_scope;
7134        for (index, param) in func.params.iter().enumerate() {
7135            if let Some(pattern) = prologue_pattern(&prologue, index) {
7136                // A destructuring parameter *initialises* its bindings: with a parameter
7137                // scope they are the list's own `let`s, which is why the stores skip the
7138                // dead-zone check, and why the reference reads their properties with
7139                // `get_field2` — a `let` needs no reference.
7140                let kind = if has_param_scope {
7141                    VarDeclKind::Let
7142                } else {
7143                    VarDeclKind::Var
7144                };
7145                match &pattern.kind {
7146                    // `...rest` collects what is left rather than reading one slot.
7147                    PatternKind::Rest(inner) => {
7148                        self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7149                        self.destructure(inner, Some(kind))?;
7150                    }
7151                    _ => {
7152                        self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7153                        self.destructure(pattern, Some(kind))?;
7154                    }
7155                }
7156                continue;
7157            }
7158            // A plain name binds straight from its argument slot. With a parameter scope
7159            // the slot is also copied into the parameter binding, which is what a later
7160            // default (or a closure made among the defaults) reads.
7161            let Some(name) = simple_parameter(param) else {
7162                continue;
7163            };
7164            let target = self.param_binding_slot(&name.name);
7165            if matches!(param.kind, PatternKind::Rest(_)) {
7166                self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7167                if let Some(slot) = target {
7168                    self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
7169                }
7170                // `put_arg` rather than `set_arg`: the array is the last thing on the
7171                // stack and nothing keeps it. Named by hand because a name in the
7172                // parameter list resolves to the parameter binding, and this store has to
7173                // reach the *argument* — that is what the body reads.
7174                self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
7175                continue;
7176            }
7177            if let PatternKind::Assign { default, .. } = &param.kind {
7178                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7179                let has_value = self.new_label();
7180                self.emit(Opcode::Dup, &[]);
7181                self.emit(Opcode::IsUndefined, &[]);
7182                self.emit_jump(Opcode::IfFalse, has_value, &[]);
7183                self.emit(Opcode::Drop, &[]);
7184                self.expr(default)?;
7185                self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
7186                // The argument slot keeps the substituted value, because the *body* reads
7187                // the slot rather than the parameter binding — so this store is named
7188                // explicitly, like the rest parameter's.
7189                self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7190                self.place_label(has_value);
7191                if let Some(slot) = target {
7192                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7193                }
7194                continue;
7195            }
7196            if let Some(slot) = target {
7197                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7198                self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7199            }
7200        }
7201        // Copy the parameter scope into the body. A plain parameter needs nothing: the
7202        // body reads its argument slot, and the list kept the two in step. A name a
7203        // pattern bound has no argument slot of its own, so the body gets a `var` filled
7204        // from the parameter's copy — and *that* is why an assignment inside a default
7205        // does not reach the body.
7206        if has_param_scope {
7207            for (_, pattern) in &prologue {
7208                let mut names = Vec::new();
7209                pattern.bound_names(&mut names);
7210                for name in names {
7211                    let Some(slot) = self.param_binding_slot(&name.name) else {
7212                        continue;
7213                    };
7214                    let Some(body) = self.body_var_slot(&name.name) else {
7215                        continue;
7216                    };
7217                    self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
7218                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
7219                }
7220            }
7221        }
7222        // The parameter list is over; from here on a direct `eval` belongs to the body.
7223        self.state().in_params = false;
7224        // Entering the body's own scope comes *after* the parameter list: the body's
7225        // `let`s are not in existence while the defaults run, and the reference emits
7226        // their `set_loc_uninitialized` only once the parameters are bound.
7227        self.emit_scope_enter(body_key);
7228        // A generator starts suspended: `initial_yield` parks the body so that creating one
7229        // runs no body code until the first `next()`.
7230        //
7231        // It comes *after* the parameter unpacking, not before, because a parameter
7232        // initialiser is not body code — `function* g(a = sideEffect())` must run
7233        // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
7234        // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
7235        // until the first `next()` and 29 test262 cases that check for a synchronous throw
7236        // saw none at all.
7237        //
7238        // An async function does **not** get one. Its body runs synchronously up to the
7239        // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
7240        // before its caller's next statement — so an `initial_yield` here would park the
7241        // body before it started, which is not fixable at run time: the suspension looks
7242        // exactly like a real `await`.
7243        if self.cur().kind.is_generator() {
7244            self.emit(Opcode::InitialYield, &[]);
7245        }
7246        // Through `stmts`: the body is a block, and a `using` declaration in it is a
7247        // disposal region.
7248        self.stmts(body)?;
7249        // The implicit return only exists if control can actually get here: an
7250        // infinite loop never falls off the end.
7251        if self.end_is_reachable() {
7252            if self.cur().is_suspending() {
7253                // Falling off the end finishes the generator with `undefined`, and the
7254                // value is what tells the resume machinery "completed" rather than
7255                // "suspended".
7256                self.emit(Opcode::Undefined, &[]);
7257                self.emit(Opcode::ReturnAsync, &[]);
7258            } else {
7259                self.emit_class_constructor_tail();
7260            }
7261        }
7262        // Resolution runs while this function is still on the stack: capturing a
7263        // variable from an enclosing function means reaching into that
7264        // function's state, which requires the whole chain to be present.
7265        Ok(self.finish_current())
7266    }
7267
7268    /// Put every binding of a function that contains a direct `eval` into a cell.
7269    ///
7270    /// A direct eval can name any binding in scope, and any closure it creates has to
7271    /// keep sharing that binding after the function returns — `for (let i …)
7272    /// eval("push(() => i)")` collects one closure per iteration and each must read its
7273    /// own `i`. A copy in a side table would freeze the value, so the binding has to be
7274    /// a cell. Doing this unconditionally for such functions is the cheap, honest
7275    /// answer: the alternative is knowing at compile time which names a string will
7276    /// mention.
7277    fn capture_everything_for_eval(&mut self) {
7278        let current = self.stack.len() - 1;
7279        if !self.stack[current].has_direct_eval {
7280            return;
7281        }
7282        for arg in &mut self.stack[current].args {
7283            arg.is_captured = true;
7284        }
7285        for var in &mut self.stack[current].vars {
7286            var.is_captured = true;
7287        }
7288    }
7289
7290    /// Whether the current position in the instruction stream can be reached.
7291    ///
7292    /// A walk over the control-flow graph, using labels as instruction indices.
7293    /// The reference does the same thing to decide whether an implicit
7294    /// `return_undef` is needed.
7295    fn end_is_reachable(&self) -> bool {
7296        let state = self.cur();
7297        reachable_instructions(state, state.insns.len())[state.insns.len()]
7298    }
7299
7300    /// Resolve and assemble the function on top of the compiler stack, then pop
7301    /// it.
7302    fn finish_current(&mut self) -> CompiledFunction {
7303        self.provide_param_arguments();
7304        self.provide_arguments();
7305        self.provide_this_local();
7306        self.provide_new_target_local();
7307        self.provide_home_object_local();
7308        self.provide_active_func_local();
7309        self.provide_self_name();
7310        self.materialize_eval_sites();
7311        self.capture_everything_for_eval();
7312        let (mut resolved, resolved_pos) = resolve(&mut self.stack);
7313        // Captured bindings need a reference cell; the count goes in the header so
7314        // the runtime knows how many cells to allocate on entry.
7315        let current = self.stack.len() - 1;
7316        let captured = self.stack[current]
7317            .args
7318            .iter()
7319            .filter(|a| a.is_captured)
7320            .count()
7321            + self.stack[current]
7322                .vars
7323                .iter()
7324                .filter(|v| v.is_captured)
7325                .count();
7326        self.stack[current].var_ref_count = captured as u32;
7327        // The scope chain is only final now that every binding is known.
7328        rebuild_scope_chain(&mut self.stack[current]);
7329        let (code, stack_size, positions) =
7330            assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
7331        let _ = &mut resolved;
7332        let mut state = self.stack.pop().expect("a function is being compiled");
7333        CompiledFunction {
7334            name: state.name,
7335            kind: state.kind,
7336            strict: state.strict,
7337            is_arrow: state.is_arrow,
7338            has_parameter_expressions: state.has_parameter_expressions,
7339            body_start: state.body_start,
7340            args: state.args,
7341            defined_args: state.defined_args,
7342            vars: state.vars,
7343            closure_vars: state.closure_vars,
7344            cpool: state.cpool,
7345            atoms: state.atoms,
7346            code,
7347            stack_size,
7348            var_ref_count: state.var_ref_count,
7349            positions,
7350            source: None,
7351            line: state.line,
7352            column: state.column,
7353            filename: None,
7354            eval_sites: state.eval_sites,
7355            module: state.module.take().map(Box::new),
7356        }
7357    }
7358}
7359
7360/// Assign each binding a scope level and rebuild the scope chains.
7361///
7362/// Levels are numbered in the order the blocks appear, with 0 reserved for the
7363/// function scope where `var` and hoisted functions live. Every binding outside
7364/// level 0 gets a `scope_next` link to the next binding visible from the same
7365/// point, so walking a block's chain enumerates exactly the bindings live there.
7366///
7367/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
7368/// point at `b`, which is declared later in the source but earlier in the chain.
7369fn rebuild_scope_chain(state: &mut FnState) {
7370    // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
7371    // real block that happens to start at offset zero keeps its own level instead of
7372    // being merged into the function scope.
7373    let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
7374    for block in &state.blocks {
7375        if !levels.contains(&block.key) {
7376            levels.push(block.key);
7377        }
7378    }
7379    let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
7380    let parent_level = |level: usize| -> usize {
7381        if level == 0 {
7382            return 0;
7383        }
7384        let key = levels[level];
7385        let parent = state
7386            .blocks
7387            .iter()
7388            .find(|b| b.key == key)
7389            .map(|b| b.parent)
7390            .unwrap_or(FUNCTION_SCOPE);
7391        level_of(parent)
7392    };
7393
7394    // Own bindings per level, in declaration order.
7395    let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
7396    let keys: Vec<u64> = (0..state.vars.len())
7397        .map(|index| {
7398            state
7399                .var_block
7400                .get(index)
7401                .copied()
7402                .unwrap_or(FUNCTION_SCOPE)
7403        })
7404        .collect();
7405    for (index, key) in keys.into_iter().enumerate() {
7406        // The parameter scope is not a block: it is a level of its own with no parent,
7407        // assigned below. Letting it land in level 0 would chain the body's bindings onto
7408        // it, which the reference does not do — the two environments are siblings.
7409        if key == PARAM_SCOPE {
7410            continue;
7411        }
7412        let level = level_of(key);
7413        state.vars[index].scope_level = level as u32;
7414        // A `catch` parameter is part of the runtime scope chain even though it is
7415        // not lexical: the handler's own bindings chain on to it, which is why the
7416        // reference prints `let y [next:1]` with `e` at 1.
7417        if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
7418        {
7419            own[level].push(index);
7420        }
7421    }
7422
7423    // A scope's chain is its own bindings in reverse declaration order followed
7424    // by the enclosing scope's chain.
7425    let mut head = vec![-1i32; levels.len()];
7426    for level in 0..levels.len() {
7427        let inherited = if level == 0 {
7428            -1
7429        } else {
7430            head[parent_level(level)]
7431        };
7432        let chain: Vec<usize> = own[level].iter().rev().copied().collect();
7433        head[level] = chain.first().map_or(inherited, |first| *first as i32);
7434        for (position, &index) in chain.iter().enumerate() {
7435            let next = chain
7436                .get(position + 1)
7437                .map_or(inherited, |next| *next as i32);
7438            state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
7439        }
7440    }
7441    state.block_heads = head;
7442
7443    // The parameter list is a scope of its own, and it has no parent: the reference pops
7444    // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
7445    // the `-1` a block uses. A level past every real block keeps it out of the walk above
7446    // — nothing but the dump reads it — and the links run newest-to-oldest through the
7447    // bindings themselves, which is the order `set_loc_uninitialized` walks.
7448    let param_level = levels.len() as u32;
7449    let mut previous: Option<usize> = None;
7450    for index in 0..state.vars.len() {
7451        if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
7452        {
7453            continue;
7454        }
7455        state.vars[index].scope_level = param_level;
7456        state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
7457        previous = Some(index);
7458    }
7459}
7460
7461/// This is where names become slots and where the temporal dead zone shows up in
7462/// the instruction stream: a read of a `let`/`const` binding compiles to
7463/// `get_loc_check`, which throws if the binding is still uninitialised.
7464///
7465/// The peephole pass from the reference implementation is applied at the end,
7466/// for the same reason it is applied to resolved bytecode there: the patterns are
7467/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
7468/// resolution. Deleted instructions stay in the list as `None` so that label
7469/// indices remain valid; [`Assembler`] maps them to byte offsets.
7470/// A resolved instruction and the source position it came from.
7471type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
7472
7473/// A resolved instruction paired with its position, which is what `assemble` consumes.
7474type PositionedInsn = (Opcode, Vec<Op>);
7475
7476fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
7477    let current = stack.len() - 1;
7478    // Dead-code elimination, on the symbolic form where labels are still
7479    // instruction indices. A `break` inside a loop leaves the trailing `goto`
7480    // unreachable, and a `return` leaves everything after it unreachable; the
7481    // reference drops both. Doing it here means the emitter never has to think
7482    // about reachability.
7483    strip_empty_gosubs(stack, current);
7484    eliminate_dead_code(stack, current);
7485    let insns = std::mem::take(&mut stack[current].insns);
7486    // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
7487    // `insns`, and every arm below pushes exactly one instruction, so the positions
7488    // stay aligned with `out`.
7489    let positions = std::mem::take(&mut stack[current].insn_pos);
7490    let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
7491    let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
7492    for (index, insn) in insns.iter().enumerate() {
7493        let pos = positions.get(index).copied().flatten();
7494        out_pos.push(pos);
7495        match insn {
7496            Insn::Fixed { op, operands } => {
7497                let operands = operands
7498                    .iter()
7499                    .map(|operand| match operand {
7500                        Op::Atom(atom) => {
7501                            Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
7502                        }
7503                        other => other.clone(),
7504                    })
7505                    .collect();
7506                out.push(Some((*op, operands)));
7507            }
7508            Insn::Var {
7509                action,
7510                name,
7511                block,
7512                in_params,
7513            } => {
7514                // Both reads and writes in the parameter list address the parameter
7515                // scope. That is what puts the list in the temporal dead zone — a read of
7516                // a later parameter is `get_loc_check` on an uninitialised slot — and it
7517                // is also what keeps an assignment made inside a default away from the
7518                // body, which sees a separate environment.
7519                let slot = resolve_slot(stack, current, name, *block, *in_params);
7520                // A store to the name of a named function expression is special: the
7521                // reference drops it in sloppy mode and throws in strict mode, because
7522                // the binding is immutable but only *checked* when the body is strict.
7523                // The same rule applies when the name is reached through a closure:
7524                // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
7525                // the store in the arrow too, not just in the function that owns the
7526                // binding. Reaching the owner means walking the chain of closure
7527                // entries, which is what `self_name_binding` does.
7528                let self_name = matches!(action, VarAction::Put | VarAction::Set)
7529                    .then(|| {
7530                        // A local of this function is the common case and needs no
7531                        // chain walk; only an access that resolves elsewhere can be
7532                        // pointing at an enclosing function's name binding.
7533                        if let Slot::Loc(index) = slot {
7534                            stack[current]
7535                                .vars
7536                                .get(index as usize)
7537                                .filter(|var| var.kind == VarKind::FunctionName)
7538                                .map(|var| var.is_const)
7539                        } else {
7540                            self_name_binding(stack, current, name, *block)
7541                        }
7542                    })
7543                    .flatten();
7544                if let Some(is_const) = self_name {
7545                    out.push(Some(if is_const {
7546                        (
7547                            Opcode::ThrowError,
7548                            vec![
7549                                Op::AtomId(intern_atom(&mut stack[current], name)),
7550                                Op::Int(0),
7551                            ],
7552                        )
7553                    } else {
7554                        (Opcode::Drop, Vec::new())
7555                    }));
7556                    continue;
7557                }
7558                out.push(Some(variable_instruction(stack, current, *action, slot)));
7559            }
7560            Insn::CloseCaptured { name, block } => {
7561                // The block matters: a loop variable is scoped to the `for` head's own
7562                // block, so resolving it against block 0 would miss it entirely and
7563                // silently emit nothing.
7564                let slot = resolve_slot(stack, current, name, *block, false);
7565                // Only a local with a reference cell has anything to close. A global
7566                // or a never-captured local resolves to no instruction at all, which
7567                // keeps the bytecode identical to the reference's.
7568                if let Slot::Loc(index) = slot
7569                    && stack[current]
7570                        .vars
7571                        .get(index as usize)
7572                        .is_some_and(|v| v.is_captured)
7573                {
7574                    out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
7575                } else {
7576                    out.push(None);
7577                }
7578            }
7579            Insn::DeleteVar { name } => {
7580                // A binding — a local, an argument, or a declared global — cannot be
7581                // deleted, and the reference encodes that as a constant `push_false`.
7582                // Only an implicit global needs the runtime lookup.
7583                if matches!(
7584                    resolve_slot(stack, current, name, 0, false),
7585                    Slot::Global(_)
7586                ) {
7587                    let atom = intern_atom(&mut stack[current], name);
7588                    out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
7589                } else {
7590                    out.push(Some((Opcode::PushFalse, Vec::new())));
7591                }
7592            }
7593            Insn::Dead => out.push(None),
7594        }
7595    }
7596    // Which label (if any) sits on each instruction, so the jump patterns can
7597    // tell whether they would cross a jump target.
7598    let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
7599    for (id, placed) in stack[current].labels.iter().enumerate() {
7600        if let Some(index) = *placed
7601            && index < label_at.len()
7602            && label_at[index].is_none()
7603        {
7604            label_at[index] = Some(id as u32);
7605        }
7606    }
7607    if std::env::var_os("QJS_DEBUG").is_some() {
7608        eprintln!("--- peephole entry ---");
7609        for (i, e) in out.iter().enumerate() {
7610            eprintln!("{i}: {e:?}");
7611        }
7612        eprintln!("label_at: {label_at:?}");
7613    }
7614    peephole(&mut out, &label_at, &stack[current].labels);
7615    (out, out_pos)
7616}
7617
7618/// Find where `name` lives, capturing it in an enclosing function when needed.
7619///
7620/// The search runs outward through the enclosing functions' states, which are
7621/// still on the compiler stack while a nested function is resolved. Finding the
7622/// name in an enclosing function is what creates a closure reference, and every
7623/// function in between has to forward it — a function can only reach its own
7624/// parent's frame.
7625///
7626/// A name declared nowhere is a global. The reference does *not* look it up by
7627/// name from the inner function: the top-level function gets one `[global]`
7628/// entry and every nested function gets a `[global_ref<n>]` pointing at its
7629/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
7630/// rather than `[global]`.
7631/// The lexical blocks enclosing `block`, innermost first.
7632fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
7633    let mut chain = Vec::new();
7634    let mut current = Some(block);
7635    while let Some(key) = current {
7636        // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
7637        // explicitly (rather than on "no block with this key") is what keeps a block
7638        // that happens to sit at offset zero from being mistaken for the terminator.
7639        if key == NO_PARENT || chain.contains(&key) {
7640            break;
7641        }
7642        chain.push(key);
7643        current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
7644    }
7645    chain
7646}
7647
7648/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
7649///
7650/// The binding may be several functions away: an arrow nested in `function myfunc`
7651/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
7652/// means following `Ref` entries down and then reading the owning function's var table.
7653fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
7654    let state = stack.get(current)?;
7655    // A parameter shadows everything and is never a function-expression name.
7656    if state.args.iter().any(|arg| arg.name == name) {
7657        return None;
7658    }
7659    // A local of this very function: the answer is in its var table.
7660    if let Some(index) = local_slot_index(state, name, block) {
7661        let var = state.vars.get(index)?;
7662        return (var.kind == VarKind::FunctionName).then_some(var.is_const);
7663    }
7664    // Otherwise the name lives further out, and the closure entry says how to get
7665    // there. `Local` names the owner's slot directly; `Ref` names the next level's
7666    // closure entry, so the walk continues downwards.
7667    let mut level = current;
7668    let mut index = state
7669        .closure_vars
7670        .iter()
7671        .position(|closure| closure.name == name)?;
7672    loop {
7673        let state = stack.get(level)?;
7674        let closure = state.closure_vars.get(index)?;
7675        match closure.closure_type {
7676            ClosureType::Local => {
7677                let owner = stack.get(level.checked_sub(1)?)?;
7678                let var = owner.vars.get(closure.var_idx as usize)?;
7679                return (var.kind == VarKind::FunctionName).then_some(var.is_const);
7680            }
7681            ClosureType::Arg => return None,
7682            ClosureType::Ref => {
7683                level -= 1;
7684                index = closure.var_idx as usize;
7685            }
7686            // A global is never a function-expression name.
7687            ClosureType::Global
7688            | ClosureType::GlobalDecl
7689            | ClosureType::GlobalRef
7690            | ClosureType::ModuleDecl
7691            | ClosureType::ModuleImport => return None,
7692        }
7693    }
7694}
7695
7696/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
7697fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
7698    block_chain(state, block).into_iter().find_map(|scope| {
7699        state.vars.iter().enumerate().find_map(|(index, var)| {
7700            (var.name == name && state.var_block.get(index).copied() == Some(scope))
7701                .then_some(index)
7702        })
7703    })
7704}
7705
7706/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
7707fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
7708    if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
7709        var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
7710    }) {
7711        return index as u32;
7712    }
7713    state.var_block.push(PARAM_SCOPE);
7714    state.vars.push(VarDef::var(name));
7715    state.vars.len() as u32 - 1
7716}
7717
7718/// The name a parameter binds straight from its argument slot, if it has one.
7719///
7720/// A plain name does — with or without a default, and with or without `...`. Everything
7721/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
7722/// reference names the argument in the first case and leaves it `<null>` in the second,
7723/// so both the dump and the closures that capture the argument depend on this.
7724fn simple_parameter(param: &Pattern) -> Option<&Ident> {
7725    match &param.kind {
7726        PatternKind::Ident(name) => Some(name),
7727        PatternKind::Assign { target, .. } => match &target.kind {
7728            PatternKind::Ident(name) => Some(name),
7729            _ => None,
7730        },
7731        PatternKind::Rest(inner) => match &inner.kind {
7732            PatternKind::Ident(name) => Some(name),
7733            _ => None,
7734        },
7735        _ => None,
7736    }
7737}
7738
7739/// The pattern a parameter list has to unpick, if `index` is one of them.
7740fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
7741    prologue
7742        .iter()
7743        .find(|(at, _)| *at == index)
7744        .map(|(_, pattern)| pattern)
7745}
7746
7747/// Whether a parameter pattern contains a default anywhere, at any depth.
7748///
7749/// The reference decides "this function has parameter expressions" by scanning the
7750/// parenthesis for a top-level `=`, which a default buried in a pattern still counts as —
7751/// `function f({a = 1})` has a parameter scope just like `function f(a = 1)`.
7752fn pattern_has_default(pattern: &Pattern) -> bool {
7753    match &pattern.kind {
7754        PatternKind::Assign { .. } => true,
7755        PatternKind::Rest(inner) => pattern_has_default(inner),
7756        PatternKind::Array { elements, rest } => {
7757            elements.iter().flatten().any(element_has_default)
7758                || rest.as_deref().is_some_and(rest_has_default)
7759        }
7760        PatternKind::Object { properties, rest } => {
7761            properties.iter().flatten().any(element_has_default)
7762                || rest.as_deref().is_some_and(rest_has_default)
7763        }
7764        _ => false,
7765    }
7766}
7767
7768fn element_has_default(element: &PatternElement) -> bool {
7769    match element {
7770        PatternElement::Pattern(pattern) => pattern_has_default(pattern),
7771        PatternElement::Property { value, .. } => pattern_has_default(value),
7772    }
7773}
7774
7775fn rest_has_default(rest: &RestElement) -> bool {
7776    match rest {
7777        RestElement::Pattern(pattern) => pattern_has_default(pattern),
7778        RestElement::Member(_) => false,
7779    }
7780}
7781
7782/// Whether a function-scope binding is visible to the parameter list.
7783///
7784/// The parameter list runs before the body, so the body's `var`s and function
7785/// declarations do not exist yet — a name that only the body declares has to resolve
7786/// outward instead. What *does* exist by then is the compiler's own prologue: the
7787/// self-name of a named function expression (bound by `special_object 2` before anything
7788/// else), `this` and `new.target`. Those stay visible, which is what makes
7789/// `function f(a = this)` and `var f = function f(a = f)` work.
7790///
7791/// `arguments` is handled separately, as a binding of the parameter scope itself: with
7792/// parameter expressions the reference creates two of them, and the one the parameter
7793/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
7794fn visible_in_params(var: &VarDef) -> bool {
7795    var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
7796}
7797
7798fn resolve_slot(
7799    stack: &mut [FnState],
7800    current: usize,
7801    name: &str,
7802    block: u64,
7803    in_params: bool,
7804) -> Slot {
7805    // The parameter list's own bindings. They are consulted first because they shadow
7806    // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
7807    // `a` in the parameter scope, so a closure made there reads the parameter even after
7808    // the body assigns to its own `a`.
7809    if in_params
7810        && let Some(index) = stack[current]
7811            .vars
7812            .iter()
7813            .enumerate()
7814            .position(|(index, var)| {
7815                var.name == name
7816                    && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
7817            })
7818    {
7819        return Slot::Loc(index as u32);
7820    }
7821    // A name can be bound more than once: two `catch` parameters in nested
7822    // handlers are two slots. The binding that wins is the one whose scope encloses
7823    // the access, and among those the innermost — so the blocks are walked outward
7824    // and the first binding found on the way is the one that counts. A binding in
7825    // no block (`var`) is reachable from anywhere, which is why the function scope
7826    // is the end of the walk.
7827    //
7828    // The block walk comes *before* the argument slots, because a block may shadow a
7829    // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
7830    // slot is only the answer once nothing nearer claims the name.
7831    let chain = block_chain(&stack[current], block);
7832    for scope in &chain {
7833        let found = stack[current]
7834            .vars
7835            .iter()
7836            .enumerate()
7837            .find(|(index, var)| {
7838                var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
7839            })
7840            .map(|(index, _)| index);
7841        if let Some(index) = found {
7842            return Slot::Loc(index as u32);
7843        }
7844    }
7845    // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
7846    // its own slot, and `var` of the same name in the body is the same binding.
7847    if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
7848        return Slot::Arg(index as u32);
7849    }
7850    // Function-scope bindings — `var` and function declarations — are recorded with
7851    // the sentinel block `0`, which no real scope uses, so the walk above cannot see
7852    // them. They are reachable from anywhere in the function, which is exactly what
7853    // the sentinel means.
7854    //
7855    // This pass is *only* for those. A lexical binding has to be found through the
7856    // chain or not at all, and looking a name up without its block is precisely how
7857    // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
7858    // block leaked out of it.
7859    let function_scoped = stack[current]
7860        .vars
7861        .iter()
7862        .enumerate()
7863        .find(|(index, var)| {
7864            var.name == name
7865                && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
7866                && (!in_params || visible_in_params(var))
7867        })
7868        .map(|(index, _)| index);
7869    if let Some(index) = function_scoped {
7870        return Slot::Loc(index as u32);
7871    }
7872    if let Some(index) = stack[current]
7873        .closure_vars
7874        .iter()
7875        .position(|c| c.name == name)
7876    {
7877        return slot_for_closure(&stack[current].closure_vars[index], index as u32);
7878    }
7879
7880    for owner in (0..current).rev() {
7881        // The nested function was created inside one of this frame's blocks, and the
7882        // outermost visible binding is the innermost block on that chain — not whatever
7883        // comes first in the variable table. `function f(){ class S{} }` has two `S`
7884        // bindings: the `let S` inside `f` and the `const S` inside the class body, and
7885        // the class body is the one a method may see.
7886        let entry = stack
7887            .get(owner + 1)
7888            .map(|s| s.created_in_block)
7889            .unwrap_or(0);
7890        let lexical = block_chain(&stack[owner], entry)
7891            .into_iter()
7892            .find_map(|scope| {
7893                stack[owner]
7894                    .vars
7895                    .iter()
7896                    .enumerate()
7897                    .find(|(index, var)| {
7898                        var.name == name
7899                            && stack[owner].var_block.get(*index).copied() == Some(scope)
7900                    })
7901                    .map(|(index, _)| index)
7902            });
7903        // A function born in a parameter list sees that list's bindings, not the body's:
7904        // the parameter scope is the environment it was created in.
7905        let in_param_scope = stack
7906            .get(owner + 1)
7907            .is_some_and(|child| child.created_in_params)
7908            .then(|| {
7909                stack[owner]
7910                    .vars
7911                    .iter()
7912                    .enumerate()
7913                    .position(|(index, var)| {
7914                        var.name == name
7915                            && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
7916                    })
7917            })
7918            .flatten();
7919        let found = if let Some(index) = in_param_scope {
7920            let var = &stack[owner].vars[index];
7921            Some(Found::Local(
7922                ClosureType::Local,
7923                index as u32,
7924                var.is_const,
7925                var.needs_check(),
7926            ))
7927        } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
7928            Some(Found::Local(ClosureType::Arg, index as u32, false, false))
7929        } else if let Some(index) = lexical {
7930            let var = &stack[owner].vars[index];
7931            Some(Found::Local(
7932                ClosureType::Local,
7933                index as u32,
7934                var.is_const,
7935                var.needs_check(),
7936            ))
7937        } else if let Some(index) = stack[owner]
7938            .vars
7939            .iter()
7940            .enumerate()
7941            .find_map(|(index, var)| {
7942                // A function created inside a parameter list must not see the body of the
7943                // function it was born in; see [`FnState::created_in_params`].
7944                let hidden = stack
7945                    .get(owner + 1)
7946                    .is_some_and(|child| child.created_in_params);
7947                (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
7948            })
7949        {
7950            let var = &stack[owner].vars[index];
7951            Some(Found::Local(
7952                ClosureType::Local,
7953                index as u32,
7954                var.is_const,
7955                var.needs_check(),
7956            ))
7957        } else if stack[owner].self_name.as_deref() == Some(name) {
7958            // A named function expression's own name. The reference declares it here,
7959            // on the first lookup that fails, rather than up front — and that is what
7960            // makes it reachable from a *nested* function: the nested lookup is what
7961            // walks out and creates the binding. A direct reference in the body is
7962            // caught the same way, which is why `provide_self_name` only has to add
7963            // the prologue.
7964            let strict = stack[owner].strict;
7965            stack[owner].var_block.push(FUNCTION_SCOPE);
7966            stack[owner].vars.push(VarDef {
7967                kind: VarKind::FunctionName,
7968                // In strict mode the name is immutable, so a store raises; sloppy
7969                // mode drops the store instead (see `variable_instruction`).
7970                is_const: strict,
7971                ..VarDef::var(name)
7972            });
7973            let index = stack[owner].vars.len() as u32 - 1;
7974            Some(Found::Local(ClosureType::Local, index, strict, false))
7975        } else if let Some(index) = stack[owner]
7976            .closure_vars
7977            .iter()
7978            .position(|c| c.name == name)
7979        {
7980            let closure = &stack[owner].closure_vars[index];
7981            Some(match closure.closure_type {
7982                // `GlobalRef` belongs here too: it is a *global* reached through this
7983                // frame's reference table, so treating it as a `Ref` to a local cell makes
7984                // the reader look for a cell no frame ever fills. That is how a second
7985                // function using `eval` in its parameter list read `undefined` after a
7986                // sibling had already made `eval` a closure entry.
7987                ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
7988                    Found::Global(index as u32)
7989                }
7990                // A module variable is a cell in the *module's* environment, which is
7991                // the module body's parent as far as a nested function is concerned — so
7992                // it is captured as a plain reference, not looked up as a global.
7993                ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
7994                    ClosureType::Ref,
7995                    index as u32,
7996                    closure.is_const,
7997                    closure.is_lexical,
7998                ),
7999                _ => Found::Local(
8000                    ClosureType::Ref,
8001                    index as u32,
8002                    closure.is_const,
8003                    closure.is_lexical,
8004                ),
8005            })
8006        } else {
8007            None
8008        };
8009        let Some(found) = found else { continue };
8010
8011        let (is_const, is_lexical) = match found {
8012            Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
8013            Found::Global(_) => (false, false),
8014        };
8015        // Mark the owner's binding as captured so it moves into a reference cell.
8016        if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
8017            let slot = match found {
8018                Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
8019                _ => &mut stack[owner].vars[index as usize],
8020            };
8021            slot.is_captured = true;
8022        }
8023        // Forward the reference through every function in between.
8024        let mut previous = match found {
8025            Found::Local(kind, index, _, _) => (kind, index),
8026            Found::Global(index) => (ClosureType::Global, index),
8027        };
8028        for level in owner + 1..=current {
8029            let kind = match (previous.0, level) {
8030                // A global stays a global at *every* level. Without `GlobalRef` in
8031                // this arm the second nested function over the same global got a
8032                // `Ref` to a cell no frame ever held, so the innermost closure read
8033                // `undefined` — which is how a two-deep getter lost its outer
8034                // variable.
8035                (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
8036                    ClosureType::GlobalRef
8037                }
8038                (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
8039                _ => ClosureType::Ref,
8040            };
8041            let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
8042            previous = (kind, index);
8043        }
8044        let index = previous.1;
8045        return slot_for_closure(&stack[current].closure_vars[index as usize], index);
8046    }
8047
8048    // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
8049    // creating a property. The top-level function holds the entry.
8050    let mut previous = (
8051        ClosureType::Global,
8052        ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
8053    );
8054    for level in 1..=current {
8055        let index = ensure_closure(
8056            stack,
8057            level,
8058            name,
8059            false,
8060            false,
8061            ClosureType::GlobalRef,
8062            previous.1,
8063        );
8064        previous = (ClosureType::GlobalRef, index);
8065    }
8066    Slot::Global(previous.1)
8067}
8068
8069/// What an outward search turned up.
8070#[derive(Debug, Clone, Copy)]
8071enum Found {
8072    /// A binding in an enclosing function, reachable through a closure of this
8073    /// type, with its const/lexical flags.
8074    Local(ClosureType, u32, bool, bool),
8075    /// A global, reached through the enclosing function's closure entry.
8076    Global(u32),
8077}
8078
8079/// Add a closure entry to `level` if it is not there yet.
8080fn ensure_closure(
8081    stack: &mut [FnState],
8082    level: usize,
8083    name: &str,
8084    is_const: bool,
8085    is_lexical: bool,
8086    closure_type: ClosureType,
8087    var_idx: u32,
8088) -> u32 {
8089    if let Some(index) = stack[level]
8090        .closure_vars
8091        .iter()
8092        .position(|c| c.name == name)
8093    {
8094        return index as u32;
8095    }
8096    stack[level].closure_vars.push(ClosureVar {
8097        name: name.to_string(),
8098        is_const,
8099        is_lexical,
8100        closure_type,
8101        var_idx: var_idx as u16,
8102    });
8103    stack[level].closure_vars.len() as u32 - 1
8104}
8105
8106fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
8107    match closure.closure_type {
8108        // A `global_ref` only says *how* the binding is found (through the
8109        // parent's closure table); the access itself is an ordinary global one.
8110        ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
8111        ClosureType::GlobalDecl => Slot::GlobalDecl(index),
8112        // A module variable is a real cell in the module's environment, so it is reached
8113        // exactly like a captured local — the host, not the global object, is what fills
8114        // the slot.
8115        ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
8116        _ => Slot::VarRef(index),
8117    }
8118}
8119
8120/// Pick the opcode for one variable access.
8121///
8122/// The `_check` variants are what enforce the temporal dead zone. They are used
8123/// for every access to a `let`/`const` binding except its own initialisation —
8124/// which is exactly the operation that takes the binding out of the dead zone.
8125fn variable_instruction(
8126    stack: &[FnState],
8127    current: usize,
8128    action: VarAction,
8129    slot: Slot,
8130) -> (Opcode, Vec<Op>) {
8131    let lexical = match slot {
8132        Slot::Loc(index) => stack[current]
8133            .vars
8134            .get(index as usize)
8135            .is_some_and(|v| v.needs_check()),
8136        Slot::VarRef(index) => stack[current]
8137            .closure_vars
8138            .get(index as usize)
8139            .is_some_and(|c| c.is_lexical),
8140        _ => false,
8141    };
8142    let operand = vec![Op::Slot(slot)];
8143    match (action, slot) {
8144        (VarAction::Get, Slot::Loc(index)) => (
8145            if lexical {
8146                Opcode::GetLocCheck
8147            } else {
8148                Opcode::GetLoc
8149            },
8150            vec![Op::Slot(Slot::Loc(index))],
8151        ),
8152        (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
8153        (VarAction::Get, Slot::VarRef(index)) => (
8154            if lexical {
8155                Opcode::GetVarRefCheck
8156            } else {
8157                Opcode::GetVarRef
8158            },
8159            vec![Op::Slot(Slot::VarRef(index))],
8160        ),
8161        (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
8162        (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
8163        (VarAction::GetUndef, Slot::Loc(_)) => (Opcode::GetLoc, operand),
8164        (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
8165        (VarAction::GetUndef, Slot::VarRef(_)) => (Opcode::GetVarRef, operand),
8166        (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8167            (Opcode::GetVarUndef, operand)
8168        }
8169
8170        (VarAction::Put, Slot::Loc(_)) => (
8171            if lexical {
8172                Opcode::PutLocCheck
8173            } else {
8174                Opcode::PutLoc
8175            },
8176            operand,
8177        ),
8178        (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
8179        (VarAction::Put, Slot::VarRef(_)) => (
8180            if lexical {
8181                Opcode::PutVarRefCheck
8182            } else {
8183                Opcode::PutVarRef
8184            },
8185            operand,
8186        ),
8187        (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
8188        (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8189        // Initialisation is what ends the dead zone, so it never checks.
8190        (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8191        (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
8192        // `this` in a derived constructor is always a local, so these cannot happen;
8193        // routing them to the ordinary forms keeps the match total without inventing
8194        // opcodes the reference does not have.
8195        (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
8196        (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8197        (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8198            (Opcode::PutVarInit, operand)
8199        }
8200        (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
8201        (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8202        (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8203            (Opcode::PutVarInit, operand)
8204        }
8205        (VarAction::Set, Slot::Loc(_)) => (
8206            if lexical {
8207                Opcode::SetLocCheck
8208            } else {
8209                Opcode::SetLoc
8210            },
8211            operand,
8212        ),
8213        (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
8214        (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
8215        (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8216        (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8217        (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
8218        (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8219        (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
8220        (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
8221        (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8222        (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
8223        (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8224        (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
8225    }
8226}
8227
8228/// The instruction-rewriting pass.
8229///
8230/// These are the reference implementation's patterns, restricted to the ones the
8231/// constructs this compiler supports can produce. Each entry is a comment on the
8232/// bytecode it removes, because the whole point is that the result is one
8233/// instruction shorter than the literal translation of the AST.
8234fn peephole(
8235    insns: &mut [Option<(Opcode, Vec<Op>)>],
8236    label_at: &[Option<u32>],
8237    placed: &[Option<usize>],
8238) {
8239    fold_dup_patterns(insns, label_at);
8240
8241    // `drop` before `return_undef` is dead: the return discards the whole frame
8242    // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
8243    // consumes its own `drop`; removing the drop first would leave the `dup` and
8244    // produce a `set_` where the reference has a `put_`.
8245    for index in 0..insns.len() {
8246        if opcode_at(insns, index) != Some(Opcode::Drop) {
8247            continue;
8248        }
8249        // Skip over a run of drops, but stop at a jump target: removing code on
8250        // one side of a label would silently retarget the jump.
8251        let mut next = index + 1;
8252        while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
8253            next += 1;
8254        }
8255        if is_label_at(label_at, next) {
8256            continue;
8257        }
8258        if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
8259            for entry in &mut insns[index..next] {
8260                *entry = None;
8261            }
8262        }
8263    }
8264
8265    // The rewrites below all decide against one fixed snapshot, which is what the
8266    // reference sees: `code_match` reads the bytecode buffer as it was on entry to
8267    // the pass, so a rule never observes what an earlier rule removed. Gathering
8268    // every deletion first and applying them together reproduces that.
8269    let snapshot: Vec<Option<Opcode>> = insns
8270        .iter()
8271        .map(|entry| entry.as_ref().map(|(op, _)| *op))
8272        .collect();
8273    // The next instruction that is still there. Holes left by dead-code
8274    // elimination are not instructions, so a rule looks past them.
8275    let next_op = |index: usize| -> Option<usize> {
8276        (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
8277    };
8278
8279    let mut doomed = vec![false; insns.len()];
8280    for index in 0..insns.len() {
8281        // A constant pushed only to be dropped does nothing at all. This is what a
8282        // comma expression with a literal left operand compiles to — `(0, f)()` — and
8283        // the reference removes the pair rather than making the reader step over it.
8284        let constant = matches!(
8285            snapshot[index],
8286            Some(
8287                Opcode::Undefined
8288                    | Opcode::Null
8289                    | Opcode::PushMinus1
8290                    | Opcode::Push0
8291                    | Opcode::Push1
8292                    | Opcode::Push2
8293                    | Opcode::Push3
8294                    | Opcode::Push4
8295                    | Opcode::Push5
8296                    | Opcode::Push6
8297                    | Opcode::Push7
8298                    | Opcode::PushTrue
8299                    | Opcode::PushFalse
8300                    | Opcode::PushI32
8301            )
8302        );
8303        if constant
8304            && let Some(next) = next_op(index)
8305            && snapshot[next] == Some(Opcode::Drop)
8306        {
8307            doomed[index] = true;
8308            doomed[next] = true;
8309        }
8310    }
8311    for (index, entry) in insns.iter_mut().enumerate() {
8312        if doomed[index] {
8313            *entry = None;
8314        }
8315    }
8316
8317    // A conditional whose destination is the very next instruction just pops its
8318    // condition, so it becomes a plain `drop`. This is what an empty `case` clause
8319    // compiles to.
8320    //
8321    // Order matters, and it is the reference's order: this runs *before* the
8322    // folding below, on the instruction the conditional originally had. Folding
8323    // moves a conditional's destination, and the reference never re-examines it
8324    // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
8325    // a conditional even though folding leaves it pointing at the next
8326    // instruction.
8327    for (index, entry) in insns.iter_mut().enumerate() {
8328        let Some((op, operands)) = entry.clone() else {
8329            continue;
8330        };
8331        if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
8332            continue;
8333        }
8334        let Some(id) = label_id(&operands) else {
8335            continue;
8336        };
8337        if placed.get(id as usize).copied().flatten() == Some(index + 1) {
8338            *entry = Some((Opcode::Drop, Vec::new()));
8339        }
8340    }
8341
8342    // A constant condition is decided here rather than at run time.
8343    fold_constant_conditions(insns);
8344    // The conditional folding below is about pairs of *real* branches, so it runs
8345    // before a jump to the next instruction is dropped: `do { … if (c) continue }
8346    // while (t)` puts `continue` exactly on the condition, and the reference inverts
8347    // the branch first and only then notices the jump goes nowhere.
8348    fold_conditional_jumps(insns, label_at, placed);
8349
8350    // A jump whose destination is the very next instruction does nothing, which is
8351    // what constant folding leaves behind for `while (1) { … }`.
8352    remove_jump_to_next(insns, placed);
8353
8354    // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
8355    // a use of the same variable boils down to.
8356    for index in 0..insns.len() {
8357        let Some((put_op, _)) = insns[index].clone() else {
8358            continue;
8359        };
8360        if !is_foldable_put(put_op) {
8361            continue;
8362        }
8363        if is_label_at(label_at, index + 1) {
8364            continue;
8365        }
8366        let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
8367            continue;
8368        };
8369        if get_op != get_form_of(put_op) {
8370            continue;
8371        }
8372        let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
8373        if put_slot.is_none() || put_slot != get_operands.first().cloned() {
8374            continue;
8375        }
8376        insns[index] = Some((set_form_of(put_op), get_operands));
8377        insns[index + 1] = None;
8378    }
8379}
8380
8381/// Drop `gosub`s that call an empty subroutine.
8382///
8383/// A `gosub` whose target starts with `ret` returns immediately, so the reference
8384/// drops the call. This is how `try`/`catch` without a `finally` loses its
8385/// finalizer plumbing: the finalizer block is empty, its first instruction is
8386/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
8387/// [`eliminate_dead_code`] then removes.
8388fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
8389    let state = &stack[current];
8390    let mut targets = Vec::new();
8391    for insn in &state.insns {
8392        if let Insn::Fixed { op, operands } = insn
8393            && *op == Opcode::Gosub
8394            && let Some(id) = label_id(operands)
8395            && let Some(target) = state.labels.get(id as usize).copied().flatten()
8396        {
8397            targets.push(target);
8398        }
8399    }
8400    let empty: Vec<usize> = targets
8401        .into_iter()
8402        .filter(|target| {
8403            stack[current]
8404                .insns
8405                .get(*target)
8406                .map(|insn| {
8407                    matches!(
8408                        insn,
8409                        Insn::Fixed {
8410                            op: Opcode::Ret,
8411                            ..
8412                        }
8413                    )
8414                })
8415                .unwrap_or(false)
8416        })
8417        .collect();
8418    if empty.is_empty() {
8419        return;
8420    }
8421    for insn in stack[current].insns.iter_mut() {
8422        if let Insn::Fixed { op, operands } = insn
8423            && *op == Opcode::Gosub
8424            && let Some(id) = label_id(operands)
8425            && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
8426            && empty.contains(&target)
8427        {
8428            *insn = Insn::Dead;
8429        }
8430    }
8431}
8432
8433/// Replace unreachable instructions with [`Insn::Dead`].
8434fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
8435    let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
8436    for (index, insn) in stack[current].insns.iter_mut().enumerate() {
8437        if !reachable[index] {
8438            *insn = Insn::Dead;
8439        }
8440    }
8441}
8442
8443/// Mark every instruction index reachable from the entry, plus the index one past
8444/// the last instruction.
8445///
8446/// `seen[len]` answers "can control reach the end of this function", and the
8447/// entries before it identify dead code. Both DCE and the implicit-return decision
8448/// read the same result, which keeps them from disagreeing.
8449fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
8450    let mut seen = vec![false; count + 1];
8451    let mut worklist = vec![0usize];
8452    while let Some(index) = worklist.pop() {
8453        if index > count || seen[index] {
8454            continue;
8455        }
8456        seen[index] = true;
8457        if index == count {
8458            continue;
8459        }
8460        let (op, operands) = match &state.insns[index] {
8461            Insn::Fixed { op, operands } => (*op, operands.as_slice()),
8462            // A variable access never transfers control, and a removed
8463            // instruction is only reachable if it is already marked.
8464            Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
8465                worklist.push(index + 1);
8466                continue;
8467            }
8468        };
8469        match op {
8470            // A return, a throw and a `ret` all leave this instruction stream: the
8471            // first two give control to the caller or the handler, and `ret`
8472            // returns to a `gosub` elsewhere.
8473            // A tail call leaves the function too: the callee's result becomes this
8474            // function's result, so nothing after it runs.
8475            Opcode::Return
8476            | Opcode::ReturnUndef
8477            | Opcode::ReturnAsync
8478            | Opcode::TailCall
8479            | Opcode::TailCallMethod
8480            | Opcode::Throw
8481            | Opcode::ThrowError
8482            | Opcode::Ret => {}
8483            // A `catch` records where exceptions from the code that follows go.
8484            // That code is not reachable through normal control flow, but it is
8485            // reachable — through the exception edge — so the walk has to follow
8486            // it, or dead-code elimination would delete every handler.
8487            Opcode::Catch => {
8488                if let Some(target) = placed_label(state, operands) {
8489                    worklist.push(target);
8490                }
8491                worklist.push(index + 1);
8492            }
8493            // A `gosub` calls a subroutine and then continues, so both edges count.
8494            Opcode::Gosub => {
8495                if let Some(target) = placed_label(state, operands) {
8496                    worklist.push(target);
8497                }
8498                worklist.push(index + 1);
8499            }
8500            Opcode::Goto => {
8501                if let Some(target) = placed_label(state, operands) {
8502                    worklist.push(target);
8503                }
8504            }
8505            Opcode::IfTrue | Opcode::IfFalse => {
8506                if let Some(target) = placed_label(state, operands) {
8507                    worklist.push(target);
8508                }
8509                worklist.push(index + 1);
8510            }
8511            _ => worklist.push(index + 1),
8512        }
8513    }
8514    seen
8515}
8516
8517/// The instruction index a jump operand points at, resolved through the label
8518/// placement table.
8519fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
8520    let id = label_id(operands)?;
8521    state.labels.get(id as usize).copied().flatten()
8522}
8523
8524/// The label an instruction refers to.
8525fn label_id(operands: &[Op]) -> Option<u32> {
8526    operands.iter().find_map(|operand| match operand {
8527        Op::Label(label) => Some(label.0),
8528        _ => None,
8529    })
8530}
8531
8532/// Turn `if_false L; goto M; L:` into `if_true M`.
8533///
8534/// A conditional whose alternate branch is an unconditional jump needs one jump,
8535/// not two. This is the shape `if (c) break;` produces, so folding it removes an
8536/// instruction and a label from every conditional `break`.
8537/// The boolean a constant-push instruction produces, or `None` if it is not one.
8538///
8539/// Only the operators whose truthiness is decided by the opcode are covered; a
8540/// constant that needs the constant pool (a string) is left alone, because reading it
8541/// would mean threading the pool through the peephole for a case the reference also
8542/// skips.
8543fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
8544    match op {
8545        // `push_0` returns -1 for zero, `push_1` 1, and so on.
8546        Opcode::PushMinus1 => Some(true),
8547        Opcode::Push0 => Some(false),
8548        Opcode::Push1
8549        | Opcode::Push2
8550        | Opcode::Push3
8551        | Opcode::Push4
8552        | Opcode::Push5
8553        | Opcode::Push6
8554        | Opcode::Push7 => Some(true),
8555        Opcode::PushTrue => Some(true),
8556        Opcode::PushFalse => Some(false),
8557        Opcode::Undefined | Opcode::Null => Some(false),
8558        Opcode::PushI32 => match operands.first() {
8559            Some(Op::Int(value)) => Some(*value != 0),
8560            _ => None,
8561        },
8562        _ => None,
8563    }
8564}
8565
8566/// Fold a branch on a constant condition.
8567///
8568/// `if (0) a() else b()` must not test anything at run time, and the reference
8569/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
8570/// which is why the bytecode for a `while (1)` loop has no condition at all.
8571///
8572/// Two instructions become one, so the slot the test occupied is left empty rather
8573/// than shifting everything after it: labels have already been resolved to indices.
8574fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>]) {
8575    for index in 0..insns.len() {
8576        let Some((push_op, push_operands)) = insns[index].clone() else {
8577            continue;
8578        };
8579        let Some(truth) = constant_truth(push_op, &push_operands) else {
8580            continue;
8581        };
8582        let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
8583            continue;
8584        };
8585        let (destination, taken) = match branch_op {
8586            Opcode::IfTrue => (branch_operands.first().cloned(), truth),
8587            Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
8588            _ => continue,
8589        };
8590        let Some(destination) = destination else {
8591            continue;
8592        };
8593        insns[index] = if taken {
8594            // The branch is always taken, so it becomes an unconditional jump.
8595            Some((Opcode::Goto, vec![destination]))
8596        } else {
8597            // The branch never runs: both instructions disappear and control falls
8598            // through to what came after.
8599            None
8600        };
8601        insns[index + 1] = None;
8602    }
8603}
8604
8605/// Remove a jump whose destination is the instruction right after it.
8606///
8607/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
8608/// its test into nothing, and the loop-end jump then points at the following
8609/// instruction. The reference drops them, so `stack_size` and the listing agree.
8610fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
8611    for index in 0..insns.len() {
8612        let Some((op, operands)) = insns[index].clone() else {
8613            continue;
8614        };
8615        if !is_goto(op) {
8616            continue;
8617        }
8618        let Some(id) = label_id(&operands) else {
8619            continue;
8620        };
8621        // The next instruction that still exists, which is what "the instruction
8622        // after this jump" means once earlier folds have punched holes.
8623        let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
8624        if placed.get(id as usize).copied().flatten() == next {
8625            insns[index] = None;
8626        }
8627    }
8628}
8629
8630fn fold_conditional_jumps(
8631    insns: &mut [Option<(Opcode, Vec<Op>)>],
8632    label_at: &[Option<u32>],
8633    placed: &[Option<usize>],
8634) {
8635    for index in 0..insns.len() {
8636        let Some((op, operands)) = insns[index].clone() else {
8637            continue;
8638        };
8639        let inverted = match op {
8640            Opcode::IfFalse => Opcode::IfTrue,
8641            Opcode::IfTrue => Opcode::IfFalse,
8642            _ => continue,
8643        };
8644        // Next must be an unconditional jump that is not itself a target, and the
8645        // instruction after it must be exactly where the conditional goes.
8646        let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
8647            continue;
8648        };
8649        if !is_goto(next_op) || is_label_at(label_at, index + 1) {
8650            continue;
8651        }
8652        // The conditional must land on the instruction *after* the jump. Several
8653        // labels can share a position, so this asks where *this* label was put
8654        // rather than what label happens to sit there.
8655        let Some(taken) = label_id(&operands) else {
8656            continue;
8657        };
8658        if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
8659            continue;
8660        }
8661        let Some(destination) = next_operands.first().cloned() else {
8662            continue;
8663        };
8664        insns[index] = Some((inverted, vec![destination]));
8665        insns[index + 1] = None;
8666    }
8667}
8668
8669/// Whether a jump target is placed at this instruction index.
8670fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
8671    label_at.get(index).copied().flatten().is_some()
8672}
8673
8674fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
8675    // `dup put_x(n)` -> `set_x(n)`
8676    // `dup put_x(n) drop` -> `put_x(n)`
8677    // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
8678    for index in 0..insns.len() {
8679        if opcode_at(insns, index) != Some(Opcode::Dup) {
8680            continue;
8681        }
8682        if is_label_at(label_at, index + 1) {
8683            continue;
8684        }
8685        let Some((put_op, put_operands)) = insns[index + 1].clone() else {
8686            continue;
8687        };
8688        if !is_foldable_put(put_op) {
8689            continue;
8690        }
8691        let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
8692            continue;
8693        };
8694        let mut new_op = set_form_of(put_op);
8695        let mut end = index + 2;
8696        if is_label_at(label_at, end) {
8697            // The `put` has to stay as it is; only the `dup` can be folded.
8698            insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
8699            insns[index + 1] = None;
8700            continue;
8701        }
8702        // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
8703        // Deleting it moves the label's target onto whatever follows, and the code that
8704        // jumps there arrives with a different stack than the fall-through path: that is
8705        // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
8706        // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
8707        // an empty stack. The store had already consumed the value it was supposed to
8708        // leave behind.
8709        if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
8710            new_op = put_op;
8711            end += 1;
8712            if opcode_at(insns, end) == Some(get_form_of(put_op))
8713                && !is_label_at(label_at, end)
8714                && insns[end]
8715                    .as_ref()
8716                    .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
8717            {
8718                new_op = set_form_of(put_op);
8719                end += 1;
8720            }
8721        }
8722        insns[index] = Some((new_op, vec![Op::Slot(slot)]));
8723        for entry in &mut insns[index + 1..end] {
8724            *entry = None;
8725        }
8726    }
8727}
8728
8729fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
8730    insns
8731        .get(index)
8732        .and_then(|entry| entry.as_ref())
8733        .map(|(op, _)| *op)
8734}
8735
8736/// The four `put_` families that have a `set_` twin. Deliberately not including
8737/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
8738/// these, and folding the others would produce instructions that do not exist.
8739fn is_foldable_put(op: Opcode) -> bool {
8740    matches!(
8741        op,
8742        Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
8743    )
8744}
8745
8746fn set_form_of(op: Opcode) -> Opcode {
8747    match op {
8748        Opcode::PutLoc => Opcode::SetLoc,
8749        Opcode::PutLocCheck => Opcode::SetLocCheck,
8750        Opcode::PutArg => Opcode::SetArg,
8751        Opcode::PutVarRef => Opcode::SetVarRef,
8752        other => other,
8753    }
8754}
8755
8756fn get_form_of(op: Opcode) -> Opcode {
8757    match op {
8758        Opcode::PutLoc => Opcode::GetLoc,
8759        Opcode::PutLocCheck => Opcode::GetLocCheck,
8760        Opcode::PutArg => Opcode::GetArg,
8761        Opcode::PutVarRef => Opcode::GetVarRef,
8762        other => other,
8763    }
8764}
8765
8766/// Atom interning, per function.
8767///
8768/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
8769/// identifiers, so the array-index rule applies here rather than at the handful of
8770/// call sites that build property keys.
8771fn intern_atom(state: &mut FnState, name: &str) -> u32 {
8772    intern_atom_value(state, Atom::from_text(name))
8773}
8774
8775/// [`intern_atom`] for an operand that is already an [`Atom`].
8776///
8777/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
8778/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
8779/// would have looked up.
8780fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
8781    if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
8782        return index as u32;
8783    }
8784    state.atoms.push(atom);
8785    state.atoms.len() as u32 - 1
8786}
8787
8788fn binary_opcode(op: BinaryOp) -> Opcode {
8789    match op {
8790        BinaryOp::Add => Opcode::Add,
8791        BinaryOp::Sub => Opcode::Sub,
8792        BinaryOp::Mul => Opcode::Mul,
8793        BinaryOp::Div => Opcode::Div,
8794        BinaryOp::Mod => Opcode::Mod,
8795        BinaryOp::Pow => Opcode::Pow,
8796        BinaryOp::BitOr => Opcode::Or,
8797        BinaryOp::BitXor => Opcode::Xor,
8798        BinaryOp::BitAnd => Opcode::And,
8799        BinaryOp::Shl => Opcode::Shl,
8800        BinaryOp::Shr => Opcode::Sar,
8801        BinaryOp::UShr => Opcode::Shr,
8802        BinaryOp::Lt => Opcode::Lt,
8803        BinaryOp::LtEq => Opcode::Lte,
8804        BinaryOp::Gt => Opcode::Gt,
8805        BinaryOp::GtEq => Opcode::Gte,
8806        BinaryOp::Eq => Opcode::Eq,
8807        BinaryOp::NotEq => Opcode::Neq,
8808        BinaryOp::StrictEq => Opcode::StrictEq,
8809        BinaryOp::StrictNotEq => Opcode::StrictNeq,
8810        BinaryOp::In => Opcode::In,
8811        BinaryOp::Instanceof => Opcode::Instanceof,
8812    }
8813}
8814
8815fn compound_opcode(op: AssignOp) -> Opcode {
8816    match op {
8817        AssignOp::Add => Opcode::Add,
8818        AssignOp::Sub => Opcode::Sub,
8819        AssignOp::Mul => Opcode::Mul,
8820        AssignOp::Div => Opcode::Div,
8821        AssignOp::Mod => Opcode::Mod,
8822        AssignOp::Pow => Opcode::Pow,
8823        AssignOp::Shl => Opcode::Shl,
8824        AssignOp::Shr => Opcode::Sar,
8825        AssignOp::UShr => Opcode::Shr,
8826        AssignOp::BitOr => Opcode::Or,
8827        AssignOp::BitXor => Opcode::Xor,
8828        AssignOp::BitAnd => Opcode::And,
8829        AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
8830    }
8831}
8832
8833/// Encode the resolved instruction stream, choosing short forms where possible.
8834///
8835/// The peephole pass leaves holes in the instruction list so that label indices
8836/// stay valid. A label names an *instruction index*, and an index that was
8837/// deleted has to resolve to the next surviving instruction, which is what
8838/// [`resolve_label`] does before the byte offsets are known.
8839fn assemble(
8840    insns: &mut [Option<(Opcode, Vec<Op>)>],
8841    insn_pos: &[Option<Position>],
8842    state: &mut FnState,
8843) -> (Vec<u8>, u32, Vec<LineCol>) {
8844    // Compaction: surviving instructions in order, plus the index mapping.
8845    //
8846    // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
8847    // point below where instructions are removed — otherwise a stack trace would point
8848    // at the wrong source line as soon as dead-code elimination kicked in.
8849    let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
8850    let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
8851    let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
8852    for (original, entry) in insns.iter_mut().enumerate() {
8853        if let Some((op, operands)) = entry.take() {
8854            original_to_kept[original] = Some(kept.len());
8855            kept.push((op, operands));
8856            spans.push(insn_pos.get(original).copied().flatten());
8857        }
8858    }
8859
8860    if std::env::var_os("QJS_DEBUG").is_some() {
8861        eprintln!("--- assemble entry --- {kept:?}");
8862    }
8863    // How many labels are real, as opposed to the per-instruction ones allocated
8864    // just below. Only a real label marks a spot in the source program.
8865    let real_labels = state.labels.len();
8866
8867    // Give every surviving instruction a label of its own. Jump cleanup below
8868    // redirects jumps to arbitrary instructions, and a jump target has to be a
8869    // label; pre-allocating one per index means a redirect never has to invent
8870    // anything.
8871    let existing = state.labels.len();
8872    let base = kept.len();
8873    let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
8874    for offset in 0..=kept.len() {
8875        state.labels.push(Some(0));
8876        index_label.push(Label((existing + offset) as u32));
8877    }
8878    // Point each pre-allocated label at its instruction, reusing the count from
8879    // `original_to_kept` so the mapping survives compaction.
8880    let place_index_labels = |state: &mut FnState,
8881                              original_to_kept: &[Option<usize>],
8882                              kept_len: usize,
8883                              index_label: &[Label]| {
8884        for (original, mapped) in original_to_kept.iter().enumerate() {
8885            if let Some(kept_index) = mapped {
8886                let label = index_label[*kept_index].0 as usize;
8887                state.labels[label] = Some(original);
8888            }
8889        }
8890        state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
8891    };
8892    place_index_labels(state, &original_to_kept, base, &index_label);
8893
8894    // Resolve every label to a kept index once; the placement table maps labels
8895    // to original indices, so a second hop lands in kept space.
8896    let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
8897    for (id, placed) in state.labels.iter().enumerate() {
8898        let Some(original) = placed else { continue };
8899        label_kept[id] = if *original == usize::MAX {
8900            Some(base)
8901        } else {
8902            (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
8903        };
8904    }
8905
8906    // Code after an unconditional transfer is unreachable, and the reference drops it
8907    // as it walks past the transfer — the `skip_dead_code` in its first pass. It
8908    // scans forward until it finds a label something still jumps to, so a run of
8909    // dead instructions between a `throw` and the next live target disappears.
8910    //
8911    // The scan repeats because dropping a jump lowers the reference count of the
8912    // label it pointed at, which can strand what follows. Only a real label keeps an
8913    // instruction alive here; the per-instruction labels allocated above belong to
8914    // this pass, not to the program.
8915    loop {
8916        let mut references = vec![false; kept.len() + 1];
8917        for (_, operands) in &kept {
8918            if let Some(target) = target_kept_index(operands, &label_kept)
8919                && target < references.len()
8920            {
8921                references[target] = true;
8922            }
8923        }
8924        let mut doomed = vec![false; kept.len()];
8925        let mut any = false;
8926        for (index, (op, _)) in kept.iter().enumerate() {
8927            if !is_transfer(*op) {
8928                continue;
8929            }
8930            for next in index + 1..kept.len() {
8931                if references[next] {
8932                    break;
8933                }
8934                doomed[next] = true;
8935                any = true;
8936            }
8937        }
8938        if !any {
8939            break;
8940        }
8941        (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
8942    }
8943
8944    // A label that lands on an unconditional jump stands for wherever that jump
8945    // goes, so retarget it once and every jump to the label follows for free.
8946    // This is what makes `continue` in a `for` head reach the loop top instead of
8947    // stopping at the update's trailing jump.
8948    let folded: Vec<Option<usize>> = label_kept
8949        .iter()
8950        .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
8951        .collect();
8952    label_kept = folded;
8953
8954    // Jump cleanup, in compacted index space. Two rewrites the reference also
8955    // applies while it resolves labels:
8956    //   * a jump whose destination is the very next instruction does nothing;
8957    //   * a jump to a jump is redirected to its final destination.
8958    // The second can expose the first, so this repeats until it settles.
8959    loop {
8960        let mut delete = vec![false; kept.len()];
8961        let mut changed = false;
8962        for index in 0..kept.len() {
8963            let (op, operands) = &kept[index];
8964            if !is_goto(*op) {
8965                continue;
8966            }
8967            let Some(immediate) = target_kept_index(operands, &label_kept) else {
8968                continue;
8969            };
8970            let target = follow_jump_chain(&kept, &label_kept, immediate);
8971            if target == index + 1 {
8972                delete[index] = true;
8973                changed = true;
8974            } else if matches!(
8975                kept.get(target).map(|(op, _)| *op),
8976                Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
8977            ) {
8978                // Jumping straight to a return or throw is the same as doing it
8979                // here, so the jump becomes that instruction.
8980                kept[index] = (kept[target].0, Vec::new());
8981                changed = true;
8982            } else if target != immediate {
8983                // Redirect to the end of the chain.
8984                let label = index_label[target];
8985                kept[index].1 = vec![Op::Label(label)];
8986                changed = true;
8987            }
8988        }
8989        if !changed {
8990            break;
8991        }
8992        if !delete.iter().any(|deleted| *deleted) {
8993            break;
8994        }
8995        // Drop the deleted instructions and renumber everything.
8996        let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
8997        let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
8998        let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
8999        for (old, entry) in kept.into_iter().enumerate() {
9000            if delete[old] {
9001                continue;
9002            }
9003            moved[old] = Some(next.len());
9004            next.push(entry);
9005            next_spans.push(spans[old]);
9006        }
9007        for (id, slot) in label_kept.iter_mut().enumerate() {
9008            let Some(old) = *slot else { continue };
9009            *slot = match moved.get(old).copied().flatten() {
9010                Some(new) => Some(new),
9011                // The target was deleted: the jump now lands on whatever follows.
9012                None => (old..moved.len())
9013                    .find_map(|i| moved[i])
9014                    .or(Some(next.len())),
9015            };
9016            let _ = id;
9017        }
9018        kept = next;
9019        spans = next_spans;
9020    }
9021
9022    // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
9023    // jump to the next instruction and is deleted, leaving the label at the end with
9024    // nothing pointing at it. If that also strands the last instruction, it goes
9025    // too — which is how a `try` whose body always returns ends on its `ret` rather
9026    // than an implicit `return_undef`.
9027    // Which instructions something still jumps to. Reading the surviving jumps is
9028    // what the reference's reference counts amount to: once a jump has been folded
9029    // away the label it named is unreferenced, even though the program still has a
9030    // label there.
9031    let mut references = vec![false; kept.len() + 1];
9032    let _ = real_labels;
9033    for (_, operands) in &kept {
9034        if let Some(target) = target_kept_index(operands, &label_kept)
9035            && target < references.len()
9036        {
9037            references[target] = true;
9038        }
9039    }
9040    let mut end = kept.len();
9041    while end > 0 {
9042        let last = end - 1;
9043        let reachable = references[last] || end < kept.len();
9044        if reachable {
9045            break;
9046        }
9047        let after_transfer = last
9048            .checked_sub(1)
9049            .map(|previous| {
9050                matches!(
9051                    kept[previous].0,
9052                    Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
9053                )
9054            })
9055            .unwrap_or(false);
9056        if !after_transfer {
9057            break;
9058        }
9059        end = last;
9060    }
9061    kept.truncate(end);
9062    spans.truncate(end);
9063
9064    // Choose an opcode for each instruction and its size, so label offsets can be
9065    // computed.
9066    let chosen = choose_opcodes(&kept, &label_kept);
9067    let offsets = instruction_offsets(&chosen);
9068    let offset = *offsets.last().unwrap_or(&0);
9069
9070    let mut code = Vec::with_capacity(offset);
9071    for (position, (_, operands)) in kept.iter().enumerate() {
9072        let op = chosen[position];
9073        code.push(op as u8);
9074        let operands = retarget_labels(operands, &label_kept, kept.len());
9075        encode_operands(&mut code, op, &operands, offsets[position], &offsets);
9076    }
9077    let stack_size = compute_stack_size(&code);
9078    // Keep only the offsets where the position actually changes: a run of
9079    // instructions on one line is one table entry, and the runtime binary searches
9080    // the table for the frame's pc.
9081    //
9082    // The table always starts at pc 0 with the *function's own* position, because the
9083    // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
9084    // last_line_num)` from `fd->source_pos`, the token the function definition starts at
9085    // (`function`, `async`, a method's property name). An instruction before the first
9086    // recorded operator therefore reports the function's own start, which is what makes a
9087    // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
9088    let mut positions: Vec<LineCol> = vec![LineCol {
9089        pc: 0,
9090        line: state.line,
9091        column: state.column,
9092    }];
9093    let mut last: Option<Position> = None;
9094    for (index, span) in spans.iter().enumerate() {
9095        let Some(pos) = *span else { continue };
9096        if last == Some(pos) {
9097            continue;
9098        }
9099        last = Some(pos);
9100        if pos.line == state.line && pos.column == state.column {
9101            // Already the seed entry above.
9102            continue;
9103        }
9104        positions.push(LineCol {
9105            pc: offsets[index] as u32,
9106            line: pos.line,
9107            column: pos.column,
9108        });
9109    }
9110    (code, stack_size, positions)
9111}
9112
9113/// Whether an instruction always transfers control away, so anything after it in the
9114/// same stream is unreachable.
9115fn is_transfer(op: Opcode) -> bool {
9116    matches!(
9117        op,
9118        Opcode::Goto
9119            | Opcode::Goto8
9120            | Opcode::Goto16
9121            | Opcode::Return
9122            | Opcode::ReturnUndef
9123            | Opcode::Throw
9124            | Opcode::ThrowError
9125            | Opcode::Ret
9126    )
9127}
9128
9129/// Remove the marked instructions and renumber the label table so it keeps pointing
9130/// at the same instructions. A label whose instruction went away moves to whatever
9131/// follows it, since a jump is never left with nowhere to land.
9132fn drop_instructions(
9133    kept: Vec<(Opcode, Vec<Op>)>,
9134    spans: Vec<Option<Position>>,
9135    label_kept: &mut [Option<usize>],
9136    doomed: &[bool],
9137) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
9138    let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9139    let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9140    let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9141    for (old, entry) in kept.into_iter().enumerate() {
9142        if doomed.get(old).copied().unwrap_or(false) {
9143            continue;
9144        }
9145        moved[old] = Some(result.len());
9146        result.push(entry);
9147        result_spans.push(spans[old]);
9148    }
9149    for slot in label_kept.iter_mut() {
9150        let Some(old) = *slot else { continue };
9151        *slot = match moved.get(old).copied().flatten() {
9152            Some(new) => Some(new),
9153            None => (old..moved.len())
9154                .find_map(|i| moved[i])
9155                .or(Some(result.len())),
9156        };
9157    }
9158    (result, result_spans)
9159}
9160
9161fn is_goto(op: Opcode) -> bool {
9162    matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
9163}
9164
9165/// The kept index a jump operand points at.
9166fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
9167    let id = label_id(operands)?;
9168    label_kept.get(id as usize).copied().flatten()
9169}
9170
9171/// Follow a chain of unconditional jumps to its first real destination.
9172fn follow_jump_chain(
9173    kept: &[(Opcode, Vec<Op>)],
9174    label_kept: &[Option<usize>],
9175    start: usize,
9176) -> usize {
9177    let mut current = start;
9178    // `for(;;)` jumps to itself, so the walk has to be bounded.
9179    for _ in 0..kept.len() {
9180        let Some((op, operands)) = kept.get(current) else {
9181            return current;
9182        };
9183        if !is_goto(*op) {
9184            return current;
9185        }
9186        let Some(next) = target_kept_index(operands, label_kept) else {
9187            return current;
9188        };
9189        if next == current {
9190            return current;
9191        }
9192        current = next;
9193    }
9194    current
9195}
9196
9197/// Rewrite label operands from label ids to kept instruction indices.
9198fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
9199    operands
9200        .iter()
9201        .map(|operand| match operand {
9202            Op::Label(label) => {
9203                let target = label_kept
9204                    .get(label.0 as usize)
9205                    .copied()
9206                    .flatten()
9207                    .unwrap_or(kept_len);
9208                Op::Label(Label(target as u32))
9209            }
9210            other => other.clone(),
9211        })
9212        .collect()
9213}
9214
9215/// Encode the resolved instruction stream, choosing short forms where possible.
9216///
9217/// Compute the maximum value-stack depth by exploring the control-flow graph.
9218///
9219/// This is a breadth-first walk from the first instruction, tracking the stack
9220/// depth on entry to each instruction. Every instruction has at most two
9221/// successors (fall through, and a jump target), so a worklist over byte offsets
9222/// is enough. The reference does the same thing in `compute_stack_size`, which is
9223/// why the resulting numbers match exactly.
9224///
9225/// Instructions that pop a variable number of values (`call`, `array_from`, …)
9226/// encode that count in their operand, which is added to the static `n_pop`.
9227fn compute_stack_size(code: &[u8]) -> u32 {
9228    let mut depth_at = vec![u16::MAX; code.len()];
9229    // Each entry carries the enclosing `catch` levels, innermost last, because
9230    // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
9231    // offset and forgets that level.
9232    let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
9233    let mut max_depth = 0u32;
9234
9235    while let Some((pc, depth, catch_levels)) = worklist.pop() {
9236        if pc >= code.len() {
9237            continue;
9238        }
9239        if depth_at[pc] != u16::MAX {
9240            continue;
9241        }
9242        force_depth(&mut depth_at, pc, depth);
9243
9244        let Some(op) = Opcode::from_u8(code[pc]) else {
9245            break;
9246        };
9247        let info = op.info();
9248        let next = pc + info.size as usize;
9249        if next > code.len() {
9250            break;
9251        }
9252        let mut n_pop = info.n_pop as u32;
9253        let mut n_push = info.n_push as u32;
9254        // Variable-length forms carry their count in the operand.
9255        match info.format {
9256            crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
9257                n_pop += read_u16(code, pc + 1) as u32;
9258            }
9259            crate::opcode::OpFormat::Npopx => {
9260                n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
9261            }
9262            _ => {}
9263        }
9264        // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
9265        // are the `set_` variant; the table already records that, so nothing to
9266        // adjust here.
9267        let _ = &mut n_push;
9268
9269        // The depth before this instruction's own push, which is what a `catch`
9270        // records as its level.
9271        let depth_before = depth;
9272        let mut depth = depth.saturating_sub(n_pop) + n_push;
9273        let mut catch_levels = catch_levels;
9274        if op == Opcode::NipCatch {
9275            // Discard everything above the innermost catch offset, keeping the value
9276            // on top: the frame the code after this sees is the same shape it would
9277            // have had if the `try` were not there.
9278            if let Some(base) = catch_levels.pop() {
9279                depth = base + 1;
9280            }
9281        }
9282        max_depth = max_depth.max(depth);
9283
9284        // Successors.
9285        let target = jump_target_of(code, pc, op);
9286        match op {
9287            Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9288                if let Some(target) = target {
9289                    worklist.push((target, depth, catch_levels));
9290                }
9291            }
9292            Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
9293                if let Some(target) = target {
9294                    worklist.push((target, depth, catch_levels.clone()));
9295                }
9296                worklist.push((next, depth, catch_levels));
9297            }
9298            // A `catch` records an exception edge to the handler. The handler is
9299            // entered with the thrown value on top of the stack, in the slot the
9300            // catch offset occupies on the normal path — which is why the handler's
9301            // first instruction can `put_loc` the exception away, and why the depth
9302            // is the same on both paths.
9303            Opcode::Catch => {
9304                if let Some(target) = target {
9305                    // The handler is protected by the *enclosing* catch, not by this
9306                    // one: an error raised inside it is what the handler's own
9307                    // `catch` catches.
9308                    worklist.push((target, depth, catch_levels.clone()));
9309                }
9310                catch_levels.push(depth_before);
9311                worklist.push((next, depth, catch_levels));
9312            }
9313            // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
9314            // rewind past it too. Its level sits one slot higher than a `catch`'s:
9315            // the iterator and next-method slots occupy the offset's place.
9316            Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
9317                if let Some(target) = target {
9318                    worklist.push((target, depth, catch_levels.clone()));
9319                }
9320                catch_levels.push(depth_before + 1);
9321                worklist.push((next, depth, catch_levels));
9322            }
9323            // `gosub` calls a subroutine with the return address on top. The opcode
9324            // table records no push for it — `ret` is what pops the slot — so the
9325            // extra one is added here, where the depth of the subroutine's first
9326            // instruction is being computed.
9327            Opcode::Gosub => {
9328                if let Some(target) = target {
9329                    worklist.push((target, depth + 1, catch_levels.clone()));
9330                }
9331                worklist.push((next, depth, catch_levels));
9332            }
9333            // `ret` goes back to a `gosub`; nothing here follows it.
9334            Opcode::Ret
9335            | Opcode::Return
9336            | Opcode::ReturnUndef
9337            | Opcode::Throw
9338            | Opcode::ThrowError => {}
9339            _ => worklist.push((next, depth, catch_levels)),
9340        }
9341    }
9342    max_depth
9343}
9344
9345/// Record the stack depth on entry to `pc`, keeping the deeper value if the
9346/// instruction is reachable more than once.
9347fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
9348    let clamped = depth.min(u16::MAX as u32 - 1) as u16;
9349    if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
9350        depth_at[pc] = clamped;
9351    }
9352}
9353
9354fn read_u16(code: &[u8], at: usize) -> u16 {
9355    let mut value = 0u16;
9356    for i in 0..2 {
9357        value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
9358    }
9359    value
9360}
9361
9362/// The absolute target of a jump instruction, if it has one.
9363fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
9364    let info = op.info();
9365    let position = pc + 1;
9366    match info.format {
9367        crate::opcode::OpFormat::Label8 => {
9368            let offset = *code.get(position)? as i8 as i64;
9369            Some((position as i64 + offset) as usize)
9370        }
9371        crate::opcode::OpFormat::Label16 => {
9372            let offset = read_u16(code, position) as i16 as i64;
9373            Some((position as i64 + offset) as usize)
9374        }
9375        crate::opcode::OpFormat::Label => {
9376            let mut offset = 0i32;
9377            for i in 0..4 {
9378                offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
9379            }
9380            Some((position as i64 + offset as i64) as usize)
9381        }
9382        _ => None,
9383    }
9384}
9385
9386fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
9387    use Opcode::*;
9388    match (op, operands.first()) {
9389        (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
9390            op.short_form(*value as u32).unwrap_or(op)
9391        }
9392        (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
9393        (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
9394        (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
9395        | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
9396        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
9397        // A declared global is reached through its reference cell, so it shares
9398        // the `var_ref` encodings, short forms included.
9399        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
9400            op.short_form(*index).unwrap_or(op)
9401        }
9402        (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
9403            op.short_form(*count as u32).unwrap_or(op)
9404        }
9405        _ => op,
9406    }
9407}
9408
9409/// The byte offset each instruction will start at, plus the total code size.
9410fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
9411    let mut offsets = Vec::with_capacity(chosen.len() + 1);
9412    let mut offset = 0usize;
9413    for op in chosen {
9414        offsets.push(offset);
9415        offset += op.size() as usize;
9416    }
9417    offsets.push(offset);
9418    offsets
9419}
9420
9421/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
9422/// the offset actually fits.
9423///
9424/// The choice is circular: an instruction's size decides the offsets of everything after
9425/// it, and the offsets decide whether a jump may be short. So this starts with every jump
9426/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
9427/// Shrinking only ever *shortens* distances, so the loop converges.
9428///
9429/// Doing it in one pass instead — which is what this used to do — silently truncated any
9430/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
9431/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
9432/// with four closures in its body simply stopped, with no error and no output past the
9433/// first iteration.
9434fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
9435    let mut chosen: Vec<Opcode> = kept
9436        .iter()
9437        .map(|(op, operands)| choose_short_form(*op, operands))
9438        .collect();
9439    // A jump the compiler emitted in its widest form, and the forms it may shrink to.
9440    let candidates = |op: Opcode| match op {
9441        Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
9442        Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
9443        Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
9444        _ => None,
9445    };
9446    loop {
9447        let offsets = instruction_offsets(&chosen);
9448        let mut changed = false;
9449        for index in 0..kept.len() {
9450            let (op, operands) = &kept[index];
9451            let Some((short, medium, has_medium)) = candidates(*op) else {
9452                continue;
9453            };
9454            if chosen[index] == short {
9455                continue;
9456            }
9457            let Some(target) = target_kept_index(operands, label_kept) else {
9458                continue;
9459            };
9460            let Some(&target_offset) = offsets.get(target) else {
9461                continue;
9462            };
9463            // A jump is relative to the byte after its opcode, which is the convention
9464            // `jump_target_of` decodes with.
9465            let relative = target_offset as i64 - (offsets[index] as i64 + 1);
9466            if (-128..=127).contains(&relative) {
9467                chosen[index] = short;
9468                changed = true;
9469            } else if has_medium
9470                && chosen[index] == Opcode::Goto
9471                && (-32_768..=32_767).contains(&relative)
9472            {
9473                // Too far for 8 bits and close enough for 16. Only `goto` has a medium
9474                // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
9475                // the reference encodes them.
9476                chosen[index] = medium;
9477                changed = true;
9478            }
9479        }
9480        if !changed {
9481            return chosen;
9482        }
9483    }
9484}
9485
9486fn encode_operands(
9487    code: &mut Vec<u8>,
9488    op: Opcode,
9489    operands: &[Op],
9490    position: usize,
9491    offsets: &[usize],
9492) {
9493    use crate::opcode::OpFormat::*;
9494    let info = op.info();
9495    let write_slot = |code: &mut Vec<u8>, slot: Slot| {
9496        let index = match slot {
9497            Slot::Arg(i)
9498            | Slot::Loc(i)
9499            | Slot::VarRef(i)
9500            | Slot::Global(i)
9501            | Slot::GlobalDecl(i) => i,
9502        };
9503        code.extend_from_slice(&(index as u16).to_be_bytes());
9504    };
9505    match info.format {
9506        None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
9507        U8 | Const8 => {
9508            if let Some(value) = operands.first().and_then(operand_uint) {
9509                code.push(value as u8);
9510            }
9511        }
9512        // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
9513        // like their wide counterparts, only one byte wide.
9514        Loc8 => {
9515            if let Some(Op::Slot(slot)) = operands.first() {
9516                let index = match slot {
9517                    Slot::Arg(i)
9518                    | Slot::Loc(i)
9519                    | Slot::VarRef(i)
9520                    | Slot::Global(i)
9521                    | Slot::GlobalDecl(i) => *i,
9522                };
9523                code.push(index as u8);
9524            }
9525        }
9526        I8 => {
9527            if let Some(value) = operands.first().and_then(operand_int) {
9528                code.push(value as i8 as u8);
9529            }
9530        }
9531        U16 | Npop => {
9532            if let Some(value) = operands.first().and_then(operand_int) {
9533                code.extend_from_slice(&(value as u16).to_be_bytes());
9534            }
9535        }
9536        I16 => {
9537            if let Some(value) = operands.first().and_then(operand_int) {
9538                code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
9539            }
9540        }
9541        I32 => {
9542            if let Some(value) = operands.first().and_then(operand_int) {
9543                code.extend_from_slice(&value.to_be_bytes());
9544            }
9545        }
9546        U32 | Const => {
9547            if let Some(value) = operands.first().and_then(operand_uint) {
9548                code.extend_from_slice(&value.to_be_bytes());
9549            }
9550        }
9551        Loc | Arg | VarRef => {
9552            if let Some(Op::Slot(slot)) = operands.first() {
9553                write_slot(code, *slot);
9554            }
9555        }
9556        Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
9557            if let Some(Op::AtomId(index)) = operands.first() {
9558                code.extend_from_slice(&index.to_be_bytes());
9559            }
9560            // The trailing immediate means different things per format, and the
9561            // atom forms that carry a *label* have to resolve it like any other
9562            // jump, so they cannot share the `U8`/`U16` arms above.
9563            match info.format {
9564                AtomU8 | AtomLabelU8 => {
9565                    if let Some(value) = operands.get(1).and_then(operand_uint) {
9566                        code.push(value as u8);
9567                    }
9568                }
9569                AtomU16 | AtomLabelU16 => {
9570                    if let Some(value) = operands.get(1).and_then(operand_uint) {
9571                        code.extend_from_slice(&(value as u16).to_be_bytes());
9572                    }
9573                }
9574                _ => {}
9575            }
9576        }
9577        NpopU16 => {
9578            for operand in operands.iter().take(2) {
9579                if let Some(value) = operand_uint(operand) {
9580                    code.extend_from_slice(&(value as u16).to_be_bytes());
9581                }
9582            }
9583        }
9584        Label | Label8 | Label16 | LabelU16 => {
9585            if let Some(Op::Label(label)) = operands.first() {
9586                // Labels were already remapped to kept-instruction indices.
9587                let Some(&target) = offsets.get(label.0 as usize) else {
9588                    debug_assert!(false, "label {} is past the end", label.0);
9589                    return;
9590                };
9591                let relative = target as i64 - (position as i64 + 1);
9592                match info.format {
9593                    Label8 => code.push(relative as i8 as u8),
9594                    Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
9595                    // `label_u16` stores the target followed by an unrelated u16.
9596                    LabelU16 => {
9597                        code.extend_from_slice(&(relative as i32).to_be_bytes());
9598                        if let Some(value) = operands.get(1).and_then(operand_uint) {
9599                            code.extend_from_slice(&(value as u16).to_be_bytes());
9600                        }
9601                    }
9602                    _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
9603                }
9604            }
9605        }
9606    }
9607}
9608
9609fn operand_int(op: &Op) -> Option<i32> {
9610    match op {
9611        Op::Int(value) => Some(*value),
9612        _ => None,
9613    }
9614}
9615
9616fn operand_uint(op: &Op) -> Option<u32> {
9617    match op {
9618        Op::Const(value) | Op::AtomId(value) => Some(*value),
9619        Op::Int(value) => Some(*value as u32),
9620        _ => None,
9621    }
9622}
9623
9624/// Disassemble a compiled function.
9625pub fn disassemble(function: &CompiledFunction) -> String {
9626    disasm::disassemble_program(function)
9627}