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
3539        // The reference marks the body with its own label here. Nothing jumps to it
3540        // once the loop is laid out, but it is not decoration: a label between the
3541        // store and the body is why `put_loc v; get_loc v` does *not* fold into
3542        // `set_loc v` when the body starts by reading the loop variable.
3543        let body_label = self.new_label();
3544        self.place_label(body_label);
3545        // `for (using x of …)` disposes once per iteration, so the body is a disposal
3546        // region rather than the whole loop: the resource is the element that this
3547        // iteration produced.
3548        let using_slot = match left {
3549            ForHead::VarDecl(decl) if decl.kind.is_using() => {
3550                decl.declarators
3551                    .first()
3552                    .and_then(|declarator| match &declarator.target.kind {
3553                        PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
3554                        _ => None,
3555                    })
3556            }
3557            _ => None,
3558        };
3559        match using_slot {
3560            Some(slot) => {
3561                let live = !Self::terminates(body);
3562                self.using_region_around(slot, live, |compiler| compiler.stmt(body))?;
3563            }
3564            None => self.stmt(body)?,
3565        }
3566
3567        // §14.7.5.6 `ForIn/OfBodyEvaluation` step 6: a `let`/`const` head gets a **fresh
3568        // binding each iteration**, so a closure the body creates keeps that iteration's
3569        // value. `CloseCaptured` is the same instruction the C-style `for` uses: it swaps in
3570        // a new reference cell holding the current value.
3571        //
3572        // The position is the *end* of the body, not the start: closing before the body
3573        // would leave the closures pointing at the cell the next `put_loc` overwrites, and
3574        // `for (const x of [1,2,3]) fs.push(() => x)` answered `2,3,3` instead of `1,2,3`.
3575        for name in Self::loop_binding_names(left) {
3576            let pos = self.cur().cur_pos;
3577            self.state().insns.push(Insn::CloseCaptured {
3578                name,
3579                block: loop_key,
3580            });
3581            self.state().insn_pos.push(pos);
3582        }
3583        self.place_label(test);
3584        match kind {
3585            ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
3586            ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
3587            ForLoopKind::AwaitOf => {
3588                // The reference's shape: step, `await` the result, then unpack it.
3589                self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
3590                self.emit(Opcode::Await, &[]);
3591                self.state().has_await = true;
3592                self.emit(Opcode::IteratorGetValueDone, &[]);
3593            }
3594        }
3595        self.emit_jump(Opcode::IfFalse, next, &[]);
3596        // The loop is finished; `for_xx_next` left an `undefined` behind.
3597        self.emit(Opcode::Drop, &[]);
3598
3599        self.pop_jump_target();
3600        self.place_label(break_target);
3601        if has_iterator {
3602            // A loop that ran to completion finds its iterator slot already cleared (see
3603            // `iterator_get_value_done`), so this closes only an iterator abandoned by a
3604            // `break` that jumped here.
3605            self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
3606        } else {
3607            self.emit(Opcode::Drop, &[]);
3608        }
3609
3610        self.emit_scope_leave(loop_key);
3611        self.state().current_block = loop_parent;
3612        Ok(())
3613    }
3614
3615    /// The names a `for (let … of/in …)` head declares, which need a fresh cell per
3616    /// iteration. An assignment head (`for (x of …)`) declares nothing, so it is empty.
3617    fn loop_binding_names(left: &ForHead) -> Vec<String> {
3618        let ForHead::VarDecl(decl) = left else {
3619            return Vec::new();
3620        };
3621        if decl.kind == VarDeclKind::Var {
3622            return Vec::new();
3623        }
3624        let mut names = Vec::new();
3625        for declarator in &decl.declarators {
3626            let mut idents = Vec::new();
3627            declarator.target.bound_names(&mut idents);
3628            names.extend(idents.into_iter().map(|ident| ident.name));
3629        }
3630        names
3631    }
3632
3633    /// Store the value `for_xx_next` left on the stack into the loop variable.
3634    fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
3635        // A declaration *initialises* the binding, which is what takes a `let` out of
3636        // the temporal dead zone, so the store is the unchecked form. Assigning to a
3637        // binding declared elsewhere is an ordinary write and keeps its check.
3638        let (pattern, action) = match left {
3639            ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
3640            ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
3641        };
3642        match &pattern.kind {
3643            PatternKind::Ident(name) => {
3644                // `for (using x of …)` validates and snapshots each iteration's value
3645                // before the body runs, which is what makes a non-disposable element fail
3646                // on the iteration that produced it rather than at the end of the loop.
3647                if let ForHead::VarDecl(decl) = left
3648                    && decl.kind.is_using()
3649                {
3650                    let method_slot = self
3651                        .using_method_slot(&name.name)
3652                        .expect("a using binding was declared during hoisting");
3653                    self.emit(
3654                        Opcode::UsingCheck,
3655                        &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3656                    );
3657                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3658                }
3659                self.emit_var(action, &name.name);
3660                Ok(())
3661            }
3662            // Every other target stores through the same path an assignment pattern
3663            // uses, which is what makes `for (a[0] in obj)` write each key into the
3664            // property instead of refusing the loop outright.
3665            _ => self.destructure(
3666                pattern,
3667                match left {
3668                    ForHead::VarDecl(decl) => Some(decl.kind),
3669                    ForHead::Assign(_) => None,
3670                },
3671            ),
3672        }
3673    }
3674
3675    fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
3676        for declarator in &decl.declarators {
3677            let Some(init) = &declarator.init else {
3678                // `var x;` stays `undefined`. A lexical binding is different: it
3679                // has to be *initialised* to leave the temporal dead zone, so the
3680                // compiler supplies an explicit `undefined`.
3681                if decl.kind.is_lexical() {
3682                    // A lexical binding has to be *initialised* to leave the temporal
3683                    // dead zone, and a destructuring one is no different — `let {a}`
3684                    // with no initialiser is a syntax error, but `let [a] = []` still
3685                    // needs `a` to be initialised from an empty source, which the
3686                    // pattern does on its own.
3687                    self.emit(Opcode::Undefined, &[]);
3688                    self.destructure(&declarator.target, Some(decl.kind))?;
3689                }
3690                continue;
3691            };
3692            match &declarator.target.kind {
3693                PatternKind::Ident(name) => {
3694                    self.expr(init)?;
3695                    self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
3696                    if decl.kind.is_using() {
3697                        // `using_check` validates the value and snapshots its dispose
3698                        // method: `value -> value, method`. The snapshot is what makes a
3699                        // later change to `Symbol.dispose` irrelevant, and validating here
3700                        // is what keeps the body from running at all when the value is not
3701                        // disposable.
3702                        let method_slot = self
3703                            .using_method_slot(&name.name)
3704                            .expect("a using binding was declared during hoisting");
3705                        self.emit(
3706                            Opcode::UsingCheck,
3707                            &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3708                        );
3709                        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3710                        self.emit_var(VarAction::PutInit, &name.name);
3711                        continue;
3712                    }
3713                    // A declaration statement produces no value, so nothing is
3714                    // duplicated onto the stack.
3715                    match decl.kind {
3716                        VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
3717                        _ => self.emit_var(VarAction::PutInit, &name.name),
3718                    }
3719                }
3720                _ => {
3721                    // A destructuring declaration keeps nothing on the stack: the
3722                    // pattern consumes the initialiser.
3723                    self.expr(init)?;
3724                    self.destructure(&declarator.target, Some(decl.kind))?;
3725                }
3726            }
3727        }
3728        Ok(())
3729    }
3730
3731    /// Bind a destructuring pattern from the value on top of the stack.
3732    ///
3733    /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
3734    /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
3735    /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
3736    /// *assignment*, where a member expression is a legal target and the store is an
3737    /// ordinary property write.
3738    ///
3739    /// The value is consumed. An assignment expression's own result is the right-hand
3740    /// side, which the caller keeps separately — the spec does not make the pattern's
3741    /// last store produce it.
3742    fn destructure(
3743        &mut self,
3744        pattern: &Pattern,
3745        decl: Option<VarDeclKind>,
3746    ) -> Result<(), SyntaxError> {
3747        match &pattern.kind {
3748            PatternKind::Ident(name) => {
3749                match decl {
3750                    Some(VarDeclKind::Var) | None => {
3751                        self.emit_var(VarAction::Put, &name.name);
3752                    }
3753                    Some(_) => self.emit_var(VarAction::PutInit, &name.name),
3754                }
3755                Ok(())
3756            }
3757            PatternKind::Assign { target, default } => {
3758                // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
3759                // keeps `null`.
3760                //
3761                // The shape is the reference's: test for `undefined`, and when the value is
3762                // present fall **through** to a single store both paths share. The
3763                // alternatives — branching to the store on each side — need a second store
3764                // and a jump between them, which is what the dump used to show.
3765                let has_value = self.new_label();
3766                self.emit(Opcode::Dup, &[]);
3767                self.emit(Opcode::IsUndefined, &[]);
3768                self.emit_jump(Opcode::IfFalse, has_value, &[]);
3769                self.emit(Opcode::Drop, &[]);
3770                self.expr(default)?;
3771                // `var {f = function(){}} = {}` names the function `f`, like a plain
3772                // `var f = function(){}` does. Both pattern forms do it:
3773                // `BindingInitialization` names the value for a *binding* target, and since
3774                // ES2018 `DestructuringAssignmentEvaluation` does the same, so
3775                // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
3776                // no name to give, which is why only an identifier qualifies.
3777                if let PatternKind::Ident(name) = &target.kind {
3778                    self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
3779                }
3780                self.place_label(has_value);
3781                self.destructure(target, decl)
3782            }
3783            PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
3784            PatternKind::Object { properties, rest } => {
3785                self.destructure_object(properties, rest, decl, pattern)
3786            }
3787            PatternKind::Member(member) if decl.is_none() => {
3788                // An assignment pattern may store into a property. The value is on the
3789                // stack, so the receiver and the key go above it and `rot3l`/`swap2`
3790                // put the three in the order `put_array_el`/`put_field` expect.
3791                self.expr(&member.object)?;
3792                match &member.property {
3793                    MemberProp::Ident(name) => {
3794                        // `value obj` -> `obj value`, the order `put_field` takes.
3795                        // Nothing needs to be left behind: a pattern element's value is
3796                        // consumed by its own store.
3797                        self.emit(Opcode::Swap, &[]);
3798                        self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
3799                    }
3800                    MemberProp::Computed(index) => {
3801                        self.expr(index)?;
3802                        // `value obj key` -> `obj key value`.
3803                        self.emit(Opcode::Rot3l, &[]);
3804                        self.emit(Opcode::PutArrayEl, &[]);
3805                    }
3806                    MemberProp::Private(name) => {
3807                        // `value obj` -> `obj value`, and the store half of the assignment is
3808                        // the same one `obj.#x = value` uses — only without `insert2`,
3809                        // because a pattern element's value is not wanted back.
3810                        let binding = format!("#{}", name.name);
3811                        let (kind, setter) = self.private_use(&binding, member.span)?;
3812                        self.emit(Opcode::Swap, &[]);
3813                        self.private_store(&binding, kind, setter.as_deref())?;
3814                    }
3815                }
3816                Ok(())
3817            }
3818            PatternKind::Rest(inner) => self.destructure(inner, decl),
3819            PatternKind::Invalid(expr) => {
3820                Err(SyntaxError::new("invalid assignment target", expr.span))
3821            }
3822            _ => Err(SyntaxError::new(
3823                "this destructuring target is not supported by the compiler yet",
3824                pattern.span,
3825            )),
3826        }
3827    }
3828
3829    /// `[…]` on the left: drain an iterator, binding one target per element.
3830    fn destructure_array(
3831        &mut self,
3832        elements: &[Option<PatternElement>],
3833        rest: &Option<Box<RestElement>>,
3834        decl: Option<VarDeclKind>,
3835    ) -> Result<(), SyntaxError> {
3836        // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
3837        // pattern accepts any iterable and closes the iterator when the pattern ends
3838        // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
3839        // first because it is on top.
3840        self.emit(Opcode::ForOfStart, &[]);
3841        for element in elements {
3842            self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
3843            self.emit(Opcode::Drop, &[]);
3844            match element {
3845                Some(PatternElement::Pattern(pattern)) => self.destructure(pattern, decl)?,
3846                Some(PatternElement::Property { span, .. }) => {
3847                    return Err(SyntaxError::new(
3848                        "a property pattern is not a valid array element",
3849                        *span,
3850                    ));
3851                }
3852                // An elision skips the value, which is already on the stack.
3853                None => self.emit(Opcode::Drop, &[]),
3854            }
3855        }
3856        if let Some(rest) = rest {
3857            // The remaining values go into a fresh array. The target and its running
3858            // index stay on the stack above the iterator, which is what the operand of
3859            // `for_of_next` accounts for: two values sit above the iterator triple.
3860            self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
3861            self.emit(Opcode::Push0, &[]);
3862            let top = self.new_label();
3863            self.place_label(top);
3864            self.emit(Opcode::ForOfNext, &[Op::Int(2)]);
3865            let done = self.new_label();
3866            self.emit_jump(Opcode::IfTrue, done, &[]);
3867            self.emit(Opcode::DefineArrayEl, &[]);
3868            self.emit(Opcode::Inc, &[]);
3869            self.emit_jump(Opcode::Goto, top, &[]);
3870            self.place_label(done);
3871            self.emit(Opcode::Drop, &[]);
3872            self.emit(Opcode::Drop, &[]);
3873            self.destructure_rest(rest, decl)?;
3874        }
3875        self.emit(Opcode::IteratorClose, &[]);
3876        Ok(())
3877    }
3878
3879    /// `{…}` on the left: read properties off one boxed source object.
3880    fn destructure_object(
3881        &mut self,
3882        properties: &[Option<PatternElement>],
3883        rest: &Option<Box<RestElement>>,
3884        decl: Option<VarDeclKind>,
3885        pattern: &Pattern,
3886    ) -> Result<(), SyntaxError> {
3887        // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
3888        // aside for the rest element below.
3889        self.emit(Opcode::ToObject, &[]);
3890        let mut taken: Vec<Wtf8> = Vec::new();
3891        // Whether any key was computed, which a rest element cannot exclude.
3892        let mut computed = false;
3893        for property in properties {
3894            let Some(PatternElement::Property {
3895                key, value, span, ..
3896            }) = property
3897            else {
3898                return Err(SyntaxError::new(
3899                    "a bare pattern is not a valid object property",
3900                    properties
3901                        .iter()
3902                        .flatten()
3903                        .map(|element| match element {
3904                            PatternElement::Pattern(pattern) => pattern.span,
3905                            PatternElement::Property { span, .. } => *span,
3906                        })
3907                        .next()
3908                        .unwrap_or(pattern.span),
3909                ));
3910            };
3911            // Every read needs the source twice: to read from, and to keep for the next
3912            // property. `get_field2` is that duplicate-and-read in one instruction, but it
3913            // leaves the copy *under* the value, so it is only usable when whatever
3914            // consumes the value tolerates that. See [`reads_with_get_field2`].
3915            let nested = reads_with_get_field2(decl, value);
3916            if !nested {
3917                self.emit(Opcode::Dup, &[]);
3918            }
3919            match key {
3920                PropName::Literal(literal) => {
3921                    let name = self.property_key_text(literal, *span)?;
3922                    taken.push(name.clone());
3923                    self.emit(
3924                        if nested {
3925                            Opcode::GetField2
3926                        } else {
3927                            Opcode::GetField
3928                        },
3929                        &[Op::Atom(Atom::from_wtf8(&name))],
3930                    );
3931                }
3932                PropName::Computed(index) => {
3933                    // A computed key has no name to exclude ahead of time, so a rest
3934                    // element that has to skip it is refused below rather than silently
3935                    // copying the property into the rest object.
3936                    computed = true;
3937                    self.expr(index)?;
3938                    self.emit(Opcode::GetArrayEl, &[]);
3939                }
3940                PropName::Private(_) => {
3941                    return Err(SyntaxError::new(
3942                        "private fields are not supported by the compiler yet",
3943                        value.span,
3944                    ));
3945                }
3946            }
3947            self.destructure(value, decl)?;
3948        }
3949        match rest {
3950            Some(rest) => {
3951                if computed {
3952                    return Err(SyntaxError::new(
3953                        "a computed key with a rest element is not supported by the compiler yet",
3954                        Self::rest_span(rest),
3955                    ));
3956                }
3957                // `target src exclude`: the exclusion list is an array of the keys the
3958                // literal part already took, so the rest object gets only the others.
3959                self.emit(Opcode::Object, &[]);
3960                self.emit(Opcode::Swap, &[]);
3961                for name in &taken {
3962                    self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
3963                }
3964                self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
3965                self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
3966                self.emit(Opcode::Drop, &[]);
3967                self.emit(Opcode::Drop, &[]);
3968                self.destructure_rest(rest, decl)?;
3969            }
3970            // The source was only kept for a rest element.
3971            None => self.emit(Opcode::Drop, &[]),
3972        }
3973        Ok(())
3974    }
3975
3976    /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
3977    fn destructure_rest(
3978        &mut self,
3979        rest: &RestElement,
3980        decl: Option<VarDeclKind>,
3981    ) -> Result<(), SyntaxError> {
3982        match rest {
3983            RestElement::Pattern(pattern) => self.destructure(pattern, decl),
3984            // `[...a.b] = c` stores into a property.
3985            RestElement::Member(member) => {
3986                let pattern = Pattern {
3987                    kind: PatternKind::Member(member.clone()),
3988                    span: member.span,
3989                };
3990                self.destructure(&pattern, decl)
3991            }
3992        }
3993    }
3994
3995    /// The source range of a rest element, for error messages.
3996    fn rest_span(rest: &RestElement) -> Span {
3997        match rest {
3998            RestElement::Pattern(pattern) => pattern.span,
3999            RestElement::Member(member) => member.span,
4000        }
4001    }
4002
4003    /// Compile a function declaration and queue it for instantiation at scope
4004    /// entry.
4005    ///
4006    /// A declaration is visible before the statement that declares it, so the
4007    /// code that creates the function object belongs at the top of the enclosing
4008    /// scope, not at the declaration.
4009    fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
4010        let name = func.name.as_ref().expect("a declaration has a name");
4011        let function = self.compile_function(func)?;
4012        let pool_index = self.push_constant(Constant::Function(Box::new(function)));
4013        let target = self.hoist_target(&name.name);
4014        let block = self.cur().current_block;
4015        self.state().hoisted.push((block, target, pool_index));
4016        Ok(())
4017    }
4018
4019    /// Where a name lives, for a hoisted declaration.
4020    fn hoist_target(&self, name: &str) -> HoistTarget {
4021        let state = self.cur();
4022        if let Some(index) = state.args.iter().position(|a| a.name == name) {
4023            return HoistTarget::Arg(index as u32);
4024        }
4025        if let Some(index) = state.vars.iter().position(|v| v.name == name) {
4026            return HoistTarget::Loc(index as u32);
4027        }
4028        // A global function declaration is not a slot at all.
4029        HoistTarget::Global(name.to_string())
4030    }
4031
4032    // -- expressions -------------------------------------------------------
4033
4034    /// Compile one expression, recording where its instructions sit.
4035    ///
4036    /// The position is the node's operator when it has one and its first token
4037    /// otherwise, and it is restored on the way out so a parent's own instructions —
4038    /// which are emitted *after* its children — are blamed on the parent. Without the
4039    /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4040    fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4041        let saved = self.cur().cur_pos;
4042        // Only the node kinds the reference calls `emit_source_pos` for record a position:
4043        // the operator a node exists for, and a variable *read*, which the reference
4044        // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4045        // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4046        // start, a parenthesised group, an anonymous function expression — leaves the
4047        // previous position in place, because a table entry the reference never writes is
4048        // one we must not write either: the instruction that inherits a position (the
4049        // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4050        // report a more recent token than the reference does.
4051        let pos = expr.op_pos.or(match &expr.kind {
4052            ExprKind::Ident(ident) => Some(ident.span.start),
4053            _ => None,
4054        });
4055        match pos {
4056            Some(pos) => self.state().cur_pos = Some(pos),
4057            // A node the reference records nothing for: its own instructions stay
4058            // unpositioned, so they inherit whatever was written last — which is what an
4059            // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4060            // enclosing position instead would blame them on a token the reference has not
4061            // reached yet: a spread's `iterator_open` reports the expression it follows, and
4062            // a template's `to_propkey` the interpolation.
4063            None => self.state().cur_pos = None,
4064        }
4065        // Note a direct `eval` call before compiling it, because the *whole* function
4066        // is affected: an eval can name any binding the function declares, so every one
4067        // of them has to live in a cell for a closure it creates to capture it.
4068        if Self::is_direct_eval(expr) {
4069            // Every enclosing function is affected too: the eval sees the whole scope
4070            // chain, and a closure it creates can capture a binding of any of them.
4071            // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a
4072            // cell, because the closure the eval builds outlives the loop iteration.
4073            for state in &mut self.stack {
4074                state.has_direct_eval = true;
4075            }
4076            let block = self.cur().current_block;
4077            let in_params = self.cur().in_params;
4078            self.state()
4079                .pending_eval_sites
4080                .push((expr.span, block, in_params));
4081        }
4082        let result = self.expr_inner(expr);
4083        self.state().cur_pos = saved;
4084        result
4085    }
4086
4087    /// Record which bindings are in scope at a direct `eval` call.
4088    ///
4089    /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
4090    /// resolves names from a string at run time, so the only chance to pin down *which*
4091    /// slot a name means is here. Visibility is the lexical rule: a binding counts when
4092    /// its block is the current block, an enclosing one, or the function scope.
4093    fn materialize_eval_sites(&mut self) {
4094        let pending = std::mem::take(&mut self.state().pending_eval_sites);
4095        for (span, site_block, in_params) in pending {
4096            self.resolve_eval_site(span, site_block, in_params);
4097        }
4098    }
4099
4100    /// Resolve the bindings visible at one `eval` call.
4101    fn resolve_eval_site(&mut self, span: Span, site_block: u64, site_in_params: bool) {
4102        /// How near a binding is: function distance first, then block depth, then the
4103        /// later declaration (which shadows the earlier one in the same block).
4104        type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
4105
4106        // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
4107        // walked, innermost function first: a direct `eval` sees every enclosing
4108        // function's bindings, and none of them can be resolved at run time because the
4109        // runtime only has names to go on.
4110        let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
4111        let deepest = self.stack.len() - 1;
4112        for (level, state) in self.stack.iter().enumerate().rev() {
4113            let owner = (deepest - level) as u32;
4114            // The innermost function's block is the one the call sat in, which is not
4115            // the block the compiler is in now; the enclosing functions are still at
4116            // the point where this one was created.
4117            let here = if level == deepest {
4118                site_block
4119            } else {
4120                state.current_block
4121            };
4122            // The chain of live blocks, innermost first, with a depth for each. The walk
4123            // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
4124            // block can start at source offset zero.
4125            let mut live: Vec<(u64, usize)> = vec![(here, 0)];
4126            let mut block = here;
4127            while let Some(parent) = state
4128                .blocks
4129                .iter()
4130                .find(|candidate| candidate.key == block)
4131                .map(|candidate| candidate.parent)
4132                .filter(|parent| *parent != NO_PARENT)
4133                .filter(|parent| parent != &block)
4134            {
4135                live.push((parent, live.len()));
4136                block = parent;
4137            }
4138            let depth_of = |key: u64| {
4139                live.iter()
4140                    .find(|(candidate, _)| *candidate == key)
4141                    .map(|(_, depth)| *depth)
4142                    // The function scope is the outermost depth there is. A binding of a
4143                    // block this site is not inside lands here too, which pushes it
4144                    // behind every live one — the right answer: it is out of scope.
4145                    .unwrap_or(live.len())
4146            };
4147            for (index, arg) in state.args.iter().enumerate() {
4148                bindings.push((
4149                    (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
4150                    EvalVisible {
4151                        name: arg.name.clone(),
4152                        is_arg: true,
4153                        index: index as u32,
4154                        owner,
4155                    },
4156                ));
4157            }
4158            // A parameter list cannot see the body, so a body `var` is not a binding the
4159            // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
4160            // not let that eval write the body's `c`.
4161            let hides_body = if level == deepest {
4162                site_in_params
4163            } else {
4164                state.created_in_params
4165            };
4166            for (index, var) in state.vars.iter().enumerate() {
4167                let block = state
4168                    .var_block
4169                    .get(index)
4170                    .copied()
4171                    .unwrap_or(FUNCTION_SCOPE);
4172                if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
4173                    continue;
4174                }
4175                bindings.push((
4176                    (
4177                        owner as usize,
4178                        depth_of(block),
4179                        std::cmp::Reverse(index as u32),
4180                    ),
4181                    EvalVisible {
4182                        name: var.name.clone(),
4183                        is_arg: false,
4184                        index: index as u32,
4185                        owner,
4186                    },
4187                ));
4188            }
4189        }
4190        // Innermost function first, then innermost block, then the later declaration
4191        // (which shadows the earlier one within a block).
4192        bindings.sort_by_key(|(priority, _)| *priority);
4193        let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
4194        self.state().eval_sites.push(EvalSite {
4195            line: span.start.line,
4196            column: span.start.column,
4197            bindings,
4198        });
4199    }
4200
4201    /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
4202    ///
4203    /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
4204    /// a bare identifier callee counts.
4205    fn is_direct_eval(expr: &Expr) -> bool {
4206        matches!(
4207            &expr.kind,
4208            ExprKind::Call { callee, .. }
4209                if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
4210        )
4211    }
4212
4213    fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4214        match &expr.kind {
4215            ExprKind::Number(value) => self.push_number(*value),
4216            ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
4217            ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
4218            ExprKind::Null => self.emit(Opcode::Null, &[]),
4219            ExprKind::String(text) => self.push_string(text),
4220            ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
4221            ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
4222            ExprKind::This => self.this_expression(),
4223            ExprKind::NewTarget => self.new_target_expression(),
4224            ExprKind::Paren(inner) => self.expr(inner)?,
4225            ExprKind::Binary { op, left, right } => {
4226                self.expr(left)?;
4227                self.expr(right)?;
4228                self.emit(binary_opcode(*op), &[]);
4229            }
4230            ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
4231            ExprKind::Unary {
4232                op: UnaryOp::Minus,
4233                argument,
4234            } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
4235                let ExprKind::Number(value) = argument.unparen().kind else {
4236                    unreachable!("matched above")
4237                };
4238                // The reference folds a negative literal only when the negation is
4239                // exact in the integer range: `-1` becomes `push_minus1` and
4240                // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
4241                // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
4242                // `-Infinity`, not `Infinity` — and folding a fraction would change
4243                // which instruction the reference emits.
4244                let negated = -value;
4245                // `-2147483648` is deliberately excluded: its magnitude is one past
4246                // `i32::MAX`, so the reference sends it through the constant pool and
4247                // negates at run time instead.
4248                if value > 0.0
4249                    && negated == negated.trunc()
4250                    && negated >= -(i32::MAX as f64)
4251                    && negated < 0.0
4252                {
4253                    self.push_number(negated);
4254                } else {
4255                    self.push_number(value);
4256                    self.emit(Opcode::Neg, &[]);
4257                }
4258            }
4259            ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
4260            ExprKind::Conditional { test, cons, alt } => {
4261                let else_label = self.new_label();
4262                let end_label = self.new_label();
4263                self.expr(test)?;
4264                self.emit_jump(Opcode::IfFalse, else_label, &[]);
4265                self.expr(cons)?;
4266                self.emit_jump(Opcode::Goto, end_label, &[]);
4267                self.place_label(else_label);
4268                self.expr(alt)?;
4269                self.place_label(end_label);
4270            }
4271            ExprKind::Assign { op, target, value } => self.assign(*op, target, value)?,
4272            ExprKind::Update {
4273                op,
4274                argument,
4275                prefix,
4276            } => self.update(*op, argument, *prefix)?,
4277            ExprKind::Sequence(items) => {
4278                for (index, item) in items.iter().enumerate() {
4279                    self.expr(item)?;
4280                    if index + 1 != items.len() {
4281                        self.emit(Opcode::Drop, &[]);
4282                    }
4283                }
4284            }
4285            ExprKind::Call { .. } => self.chain_link_top(expr)?,
4286            ExprKind::Member { .. } => self.chain_link_top(expr)?,
4287            ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
4288            ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
4289            ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
4290            ExprKind::Template(template) => self.template_literal(template)?,
4291            ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
4292            ExprKind::New { callee, arguments } => {
4293                // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
4294                // The `dup` is not redundant: `call_constructor` takes the
4295                // constructor twice, once as the target and once as `new.target`,
4296                // which is what makes `new.target === C` inside the body.
4297                self.expr(callee)?;
4298                self.emit(Opcode::Dup, &[]);
4299                let args = arguments.as_deref().unwrap_or(&[]);
4300                if Self::has_spread(args) {
4301                    // `C C array`: the duplicated callee is already both the target
4302                    // and `new.target`, so no reordering is needed before `apply 1`.
4303                    self.argument_array(args)?;
4304                    self.emit(Opcode::Apply, &[Op::Int(1)]);
4305                    return Ok(());
4306                }
4307                for argument in args {
4308                    self.expr(argument)?;
4309                }
4310                self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
4311            }
4312            ExprKind::Class(class) => self.class_definition(class, true)?,
4313            ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
4314            ExprKind::Yield { argument, delegate } => {
4315                self.yield_expression(argument.as_deref(), *delegate)?
4316            }
4317            ExprKind::Await(argument) => self.await_expression(argument)?,
4318            ExprKind::RegExp { pattern, flags } => {
4319                // A literal is compiled *here*, at parse time, not when the line runs. The
4320                // spec is explicit that an invalid pattern is an early error (§12.9.4:
4321                // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
4322                // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
4323                // also validates `\p{…}` names: 163 conformance cases are patterns that have
4324                // to be rejected before any code runs.
4325                //
4326                // This is the whole reason the engine lives in its own crate rather than
4327                // inside `quickjs-pure`: the compiler could not depend on the interpreter
4328                // (`pure` depends on `compile`), but both need this.
4329                // The lexer already rejected an unknown or repeated flag, so an unparsable
4330                // flag string here would be a bug in the lexer rather than in the script;
4331                // fall back to the default flags instead of inventing a second message.
4332                let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
4333                let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
4334                    SyntaxError::new(
4335                        format!("invalid regular expression: {}", error.message),
4336                        expr.span,
4337                    )
4338                })?;
4339                // The tree is thrown away and rebuilt when the literal first runs: keeping it
4340                // would mean serialising the syntax tree into the function's constant pool,
4341                // and a literal is created once per evaluation of its expression anyway.
4342                let _ = parsed;
4343                // The pattern and its flags travel as two string constants; `regexp` builds
4344                // the object. A dedicated opcode (rather than a call to the constructor) is
4345                // what the reference does too, so that a literal never goes through the
4346                // public `RegExp` function and its string-coercion rules.
4347                self.push_string(&Wtf8::new(pattern));
4348                self.push_string(&Wtf8::new(flags));
4349                self.emit(Opcode::Regexp, &[]);
4350            }
4351            ExprKind::Arrow(func) => {
4352                let function = self.compile_function(func)?;
4353                let index = self.push_constant(Constant::Function(Box::new(function)));
4354                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4355            }
4356            ExprKind::Function(func) => {
4357                let function = self.compile_function_with_name(func, true)?;
4358                let index = self.push_constant(Constant::Function(Box::new(function)));
4359                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4360            }
4361            // `import.meta`: the host fills a per-module object at link time.
4362            ExprKind::ImportMeta => {
4363                self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
4364            }
4365            // `import("x")` compiles to a two-slot push followed by one opcode: the
4366            // specifier, then the options object (`undefined` here, since this compiler
4367            // does not accept the second argument yet).
4368            ExprKind::ImportCall(specifier) => {
4369                self.expr(specifier)?;
4370                self.emit(Opcode::Undefined, &[]);
4371                self.emit(Opcode::Import, &[]);
4372            }
4373            ExprKind::PrivateIn { name, object } => {
4374                // `#x in o`: the object, then the binding, then one opcode which decides what
4375                // to do with the second operand. A field's binding holds a symbol and the
4376                // answer is an own-property test; a method's holds a function and the answer
4377                // is a brand check — both live in `private_in`, so the compiler emits the
4378                // same instruction for either.
4379                self.expr(object)?;
4380                self.emit_var(VarAction::Get, &format!("#{}", name.name));
4381                self.emit(Opcode::PrivateIn, &[]);
4382            }
4383            _ => {
4384                return Err(SyntaxError::new(
4385                    "this expression form is not supported by the compiler yet",
4386                    expr.span,
4387                ));
4388            }
4389        }
4390        Ok(())
4391    }
4392
4393    /// Build one array holding the evaluated call arguments, which is how a call
4394    /// containing a spread is compiled: the reference does the same, building the
4395    /// list on the stack and handing it to `apply`.
4396    fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
4397        let elements: Vec<Option<ArrayElement>> = arguments
4398            .iter()
4399            .map(|argument| match &argument.unparen().kind {
4400                ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
4401                _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
4402            })
4403            .collect();
4404        self.array_literal(&elements, Span::default())
4405    }
4406
4407    /// Whether any argument is a spread, which is what selects the `apply` form.
4408    fn has_spread(arguments: &[Expr]) -> bool {
4409        arguments
4410            .iter()
4411            .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
4412    }
4413
4414    /// Compile `a${x}b`.
4415    ///
4416    /// A template is a `+` chain built left to right: the leading chunk (or an empty
4417    /// string when the template starts with a substitution), then for each
4418    /// substitution its value, `to_propkey` and `add`, then the following chunk when
4419    /// it is not empty. `to_propkey` is what makes a number or object substitute the
4420    /// way `ToString` would while leaving the result a string for `add` to
4421    /// concatenate.
4422    ///
4423    /// The chunk is an atom rather than a constant-pool string, because a non-empty
4424    /// chunk always lands where a value is pushed and `push_atom_value` is the
4425    /// instruction the reference uses for it; the empty first chunk has its own
4426    /// zero-byte form.
4427    fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
4428        let first = template.quasis.first();
4429        match first.and_then(|quasi| quasi.cooked.clone()) {
4430            Some(text) if !text.is_empty() => {
4431                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4432            }
4433            // Either the template begins with a substitution, or the chunk is
4434            // empty — in both cases the chain needs a string to start from.
4435            _ => self.emit(Opcode::PushEmptyString, &[]),
4436        }
4437        for (index, expression) in template.expressions.iter().enumerate() {
4438            self.expr(expression)?;
4439            self.emit(Opcode::ToPropkey, &[]);
4440            self.emit(Opcode::Add, &[]);
4441            if let Some(text) = template
4442                .quasis
4443                .get(index + 1)
4444                .and_then(|quasi| quasi.cooked.clone())
4445                && !text.is_empty()
4446            {
4447                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4448                self.emit(Opcode::Add, &[]);
4449            }
4450        }
4451        Ok(())
4452    }
4453
4454    /// Compile an object literal.
4455    ///
4456    /// The object is built in place: `object` pushes it, and each property leaves it
4457    /// on the stack with one field more, so no temporary is needed and later
4458    /// properties can overwrite earlier ones.
4459    ///
4460    /// The instruction depends on *how* the property was written, not on what kind
4461    /// of value it holds:
4462    ///
4463    /// | source | instruction |
4464    /// |---|---|
4465    /// | `{ a: v }` | `define_field a` |
4466    /// | `{ __proto__: v }` | `set_proto` |
4467    /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
4468    /// | `{ m() {} }` | `define_method m,4` |
4469    /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
4470    /// | `{ [k]() {} }` | `define_method_computed 4` |
4471    /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
4472    ///
4473    /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
4474    /// key itself, which is why the trailing `drop` is absent there too.
4475    /// `tag`…``: a call whose first argument is the call site's template object.
4476    ///
4477    /// The template object is a frozen array of the cooked chunks with a frozen `raw`
4478    /// array beside it, so `String.raw` can read the source text back. It is a constant
4479    /// because its contents never change; the reference builds one per call site and
4480    /// reuses it, while this builds one per evaluation, which only `tag` code that
4481    /// compares template objects across calls could tell apart.
4482    fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
4483        let cooked = quasi
4484            .quasis
4485            .iter()
4486            .map(|chunk| chunk.cooked.clone())
4487            .collect();
4488        let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
4489        let index = self.push_constant(Constant::Template { cooked, raw });
4490        let count = quasi.expressions.len() + 1;
4491        // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
4492        if let ExprKind::Member {
4493            object, property, ..
4494        } = &tag.unparen().kind
4495        {
4496            self.expr(object)?;
4497            match property {
4498                MemberProp::Ident(name) => {
4499                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
4500                }
4501                MemberProp::Computed(key) => {
4502                    self.expr(key)?;
4503                    self.emit(Opcode::GetArrayEl2, &[]);
4504                }
4505                MemberProp::Private(name) => {
4506                    let binding = format!("#{}", name.name);
4507                    let (kind, _) = self.private_use(&binding, tag.span)?;
4508                    self.private_callee(&binding, kind)?;
4509                }
4510            }
4511            self.emit(Opcode::PushConst, &[Op::Const(index)]);
4512            for expression in &quasi.expressions {
4513                self.expr(expression)?;
4514            }
4515            self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
4516            return Ok(());
4517        }
4518        self.expr(tag)?;
4519        self.emit(Opcode::PushConst, &[Op::Const(index)]);
4520        for expression in &quasi.expressions {
4521            self.expr(expression)?;
4522        }
4523        self.emit(Opcode::Call, &[Op::Int(count as i32)]);
4524        Ok(())
4525    }
4526
4527    fn object_literal(
4528        &mut self,
4529        properties: &[ObjectProperty],
4530        span: Span,
4531    ) -> Result<(), SyntaxError> {
4532        self.emit(Opcode::Object, &[]);
4533        for property in properties {
4534            match property {
4535                ObjectProperty::Spread(value) => {
4536                    // `copy_data_properties` takes the target, the source and an
4537                    // exclusion list; a literal `null` means "exclude nothing".
4538                    // Flag bit 1 copies symbols, bits 2/5 pick the source and the
4539                    // exclusion list by stack offset.
4540                    self.expr(spread_argument(value))?;
4541                    self.emit(Opcode::Null, &[]);
4542                    self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4543                    self.emit(Opcode::Drop, &[]);
4544                    self.emit(Opcode::Drop, &[]);
4545                }
4546                ObjectProperty::Property {
4547                    key,
4548                    value,
4549                    kind,
4550                    shorthand,
4551                    span: property_span,
4552                } => match key {
4553                    PropName::Computed(key_expr) => {
4554                        self.expr(key_expr)?;
4555                        match kind {
4556                            PropertyKind::Value => {
4557                                self.emit(Opcode::ToPropkey, &[]);
4558                                self.expr(value)?;
4559                                self.set_name_if_anonymous_computed(value);
4560                                self.emit(Opcode::DefineArrayEl, &[]);
4561                                // `define_array_el` leaves the object and the key;
4562                                // the key is no longer needed.
4563                                self.emit(Opcode::Drop, &[]);
4564                            }
4565                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4566                                self.emit_method_function(value)?;
4567                                self.emit(
4568                                    Opcode::DefineMethodComputed,
4569                                    &[Op::Int(define_method_flags(*kind))],
4570                                );
4571                            }
4572                        }
4573                    }
4574                    PropName::Literal(key) => {
4575                        let name = self.property_key_text(key, *property_span)?;
4576                        match kind {
4577                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4578                                self.emit_method_function(value)?;
4579                                self.emit(
4580                                    Opcode::DefineMethod,
4581                                    &[
4582                                        Op::Atom(Atom::from_wtf8(&name)),
4583                                        Op::Int(define_method_flags(*kind)),
4584                                    ],
4585                                );
4586                            }
4587                            PropertyKind::Value => {
4588                                self.expr(value)?;
4589                                // `{__proto__: x}` sets the prototype instead of
4590                                // creating a property; the shorthand `{__proto__}`
4591                                // is an ordinary property and does not.
4592                                if name == "__proto__" && !shorthand {
4593                                    self.emit(Opcode::SetProto, &[]);
4594                                } else {
4595                                    self.set_name_if_anonymous(value, &name);
4596                                    self.emit(
4597                                        Opcode::DefineField,
4598                                        &[Op::Atom(Atom::from_wtf8(&name))],
4599                                    );
4600                                }
4601                            }
4602                        }
4603                    }
4604                    PropName::Private(_) => {
4605                        return Err(SyntaxError::new(
4606                            "private names are not valid in object literals",
4607                            *property_span,
4608                        ));
4609                    }
4610                },
4611            }
4612        }
4613        let _ = span;
4614        Ok(())
4615    }
4616
4617    /// Emit the function a method/accessor property defines.
4618    fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
4619        self.expr(value)
4620    }
4621
4622    /// The name a literal property key contributes.
4623    ///
4624    /// String keys are used as written. A numeric key is converted the way
4625    /// `ToString` would convert it, because the atom is made from that spelling:
4626    /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
4627    fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
4628        match key {
4629            PropKey::Str(text) => Ok(text.clone()),
4630            PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
4631        }
4632    }
4633
4634    /// Compile an optional chain.
4635    ///
4636    /// `?.` short-circuits the *whole remaining spine*, not just its own link:
4637    /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
4638    /// `undefined`. So the chain is compiled with one end label and every guard
4639    /// jumps to it. The parser hands us the extent of that spine as an
4640    /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
4641    /// exactly the scope the label has to cover.
4642    fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
4643        let end = self.new_label();
4644        self.chain_link(inner, end)?;
4645        self.place_label(end);
4646        Ok(())
4647    }
4648
4649    /// A member access or call reached from outside any optional chain.
4650    ///
4651    /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
4652    /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
4653    /// still created because [`Self::chain_link`] takes it, and placing it at the
4654    /// end is a no-op that keeps a single code path.
4655    fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4656        let end = self.new_label();
4657        self.chain_link(expr, end)?;
4658        self.place_label(end);
4659        Ok(())
4660    }
4661
4662    /// One link of a chain, where `end` is the label a `?.` guard jumps to.
4663    fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
4664        match &expr.kind {
4665            ExprKind::Member {
4666                object,
4667                property,
4668                optional,
4669            } => {
4670                // `super.x` is not a lookup on a value: it starts at the home object's
4671                // prototype and keeps `this` as the receiver, so it cannot go through
4672                // `chain_link` and the ordinary field read.
4673                if matches!(object.unparen().kind, ExprKind::SuperProp) {
4674                    self.super_base();
4675                    match property {
4676                        MemberProp::Ident(name) => self.emit(
4677                            Opcode::PushAtomValue,
4678                            &[Op::Atom(Atom::from_text(&name.name))],
4679                        ),
4680                        MemberProp::Computed(index) => self.expr(index)?,
4681                        MemberProp::Private(_) => {
4682                            return Err(SyntaxError::new(
4683                                "private fields are not supported by the compiler yet",
4684                                expr.span,
4685                            ));
4686                        }
4687                    }
4688                    self.emit(Opcode::GetSuperValue, &[]);
4689                    return Ok(());
4690                }
4691                self.chain_link(object, end)?;
4692                if *optional {
4693                    self.optional_guard(end);
4694                }
4695                match property {
4696                    // `.length` has its own opcode. The reference emits it for every
4697                    // object, not just arrays, so a name-based rule is right and
4698                    // cheaper than the generic field read.
4699                    MemberProp::Ident(name) if name.name == "length" => {
4700                        self.emit(Opcode::GetLength, &[]);
4701                    }
4702                    MemberProp::Ident(name) => {
4703                        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
4704                    }
4705                    MemberProp::Computed(index) => {
4706                        self.expr(index)?;
4707                        self.emit(Opcode::GetArrayEl, &[]);
4708                    }
4709                    MemberProp::Private(name) => {
4710                        // The binding comes from the class scope, so a read from outside the
4711                        // class cannot name it at all. `?.` checks the object, not the field:
4712                        // `o?.#x` guards on `o` being nullish.
4713                        let binding = format!("#{}", name.name);
4714                        let (kind, _) = self.private_use(&binding, expr.span)?;
4715                        self.private_load(&binding, kind, expr.span)?;
4716                    }
4717                }
4718                Ok(())
4719            }
4720            ExprKind::Call {
4721                callee,
4722                arguments,
4723                optional,
4724            } => {
4725                // `o.m(args)` has to pass `o` as `this`, which a plain `call`
4726                // cannot: it reads the function and then calls it with no
4727                // receiver at all. The reference's answer is to keep the object
4728                // under the function value — `get_field2` reads a field and leaves
4729                // its base in place — and to use `call_method`, which takes the
4730                // receiver from the stack. Missing this does not just cost an
4731                // instruction, it loses the `this` binding.
4732                if let ExprKind::Member {
4733                    object,
4734                    property,
4735                    optional: member_optional,
4736                } = &callee.unparen().kind
4737                {
4738                    // `super.m()` reads the method off the home object's prototype but
4739                    // calls it with `this`, so the receiver goes under the read instead of
4740                    // being replaced by it.
4741                    if matches!(object.unparen().kind, ExprKind::SuperProp) {
4742                        self.super_base();
4743                        match property {
4744                            MemberProp::Ident(name) => self.emit(
4745                                Opcode::PushAtomValue,
4746                                &[Op::Atom(Atom::from_text(&name.name))],
4747                            ),
4748                            MemberProp::Computed(index) => self.expr(index)?,
4749                            MemberProp::Private(_) => {
4750                                return Err(SyntaxError::new(
4751                                    "private fields are not supported by the compiler yet",
4752                                    expr.span,
4753                                ));
4754                            }
4755                        }
4756                        // The two-output form would drop the receiver; this one replaces
4757                        // the prototype and the key, leaving `this` underneath.
4758                        self.emit(Opcode::GetArrayEl, &[]);
4759                        if Self::has_spread(arguments) {
4760                            self.argument_array(arguments)?;
4761                            self.emit(Opcode::Perm3, &[]);
4762                            self.emit(Opcode::Apply, &[Op::Int(0)]);
4763                            return Ok(());
4764                        }
4765                        for argument in arguments {
4766                            self.expr(argument)?;
4767                        }
4768                        self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4769                        return Ok(());
4770                    }
4771                    self.chain_link(object, end)?;
4772                    if *member_optional {
4773                        self.optional_guard(end);
4774                    }
4775                    match property {
4776                        MemberProp::Ident(name) => {
4777                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4778                        }
4779                        MemberProp::Computed(index) => {
4780                            self.expr(index)?;
4781                            // The key is not needed after the read, so this is the
4782                            // two-output form: object, value.
4783                            self.emit(Opcode::GetArrayEl2, &[]);
4784                        }
4785                        MemberProp::Private(name) => {
4786                            // The receiver is already under the callee, which is exactly the
4787                            // shape `call_method` and `apply` want — so nothing is dropped.
4788                            let binding = format!("#{}", name.name);
4789                            let (kind, _) = self.private_use(&binding, expr.span)?;
4790                            self.private_callee(&binding, kind)?;
4791                        }
4792                    }
4793                    if Self::has_spread(arguments) {
4794                        // Stack is `obj func`; the array goes on top, then `perm3`
4795                        // reorders to the `func this array` that `apply` wants.
4796                        self.argument_array(arguments)?;
4797                        self.emit(Opcode::Perm3, &[]);
4798                        self.emit(Opcode::Apply, &[Op::Int(0)]);
4799                        return Ok(());
4800                    }
4801                    for argument in arguments {
4802                        self.expr(argument)?;
4803                    }
4804                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4805                    return Ok(());
4806                }
4807                // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
4808                // with `get_field2` so the base stays under it, and on the short-circuit
4809                // path pushes an extra `undefined` as a placeholder receiver — the call
4810                // then throws, which is what calling a missing optional chain should do.
4811                if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
4812                    && let ExprKind::Member {
4813                        object,
4814                        property,
4815                        optional: member_optional,
4816                    } = &inner.unparen().kind
4817                {
4818                    let call = self.new_label();
4819                    // A guard target of its own: the outer `end` skips the whole
4820                    // expression, and a short-circuited receiver still has to reach the
4821                    // call so that calling it throws.
4822                    let short = self.new_label();
4823                    self.chain_link(object, end)?;
4824                    if *member_optional {
4825                        self.optional_guard(short);
4826                    }
4827                    match property {
4828                        MemberProp::Ident(name) => {
4829                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4830                        }
4831                        MemberProp::Computed(index) => {
4832                            self.expr(index)?;
4833                            self.emit(Opcode::GetArrayEl2, &[]);
4834                        }
4835                        MemberProp::Private(name) => {
4836                            let binding = format!("#{}", name.name);
4837                            let (kind, _) = self.private_use(&binding, expr.span)?;
4838                            self.private_callee(&binding, kind)?;
4839                        }
4840                    }
4841                    self.emit_jump(Opcode::Goto, call, &[]);
4842                    self.place_label(short);
4843                    self.emit(Opcode::Undefined, &[]);
4844                    self.place_label(call);
4845                    if Self::has_spread(arguments) {
4846                        self.argument_array(arguments)?;
4847                        self.emit(Opcode::Perm3, &[]);
4848                        self.emit(Opcode::Apply, &[Op::Int(0)]);
4849                        return Ok(());
4850                    }
4851                    for argument in arguments {
4852                        self.expr(argument)?;
4853                    }
4854                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4855                    return Ok(());
4856                }
4857                self.chain_link(callee, end)?;
4858                if *optional {
4859                    self.optional_guard(end);
4860                }
4861                if Self::has_spread(arguments) {
4862                    // `func array -> func undefined array`, which is the plain-call
4863                    // form of `apply`: the receiver is `undefined`.
4864                    self.argument_array(arguments)?;
4865                    self.emit(Opcode::Undefined, &[]);
4866                    self.emit(Opcode::Swap, &[]);
4867                    self.emit(Opcode::Apply, &[Op::Int(0)]);
4868                    return Ok(());
4869                }
4870                for argument in arguments {
4871                    self.expr(argument)?;
4872                }
4873                self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
4874                Ok(())
4875            }
4876            _ => self.expr(expr),
4877        }
4878    }
4879
4880    /// Compile `expr` as a tail call when it is one, reporting whether it was.
4881    ///
4882    /// `tail_call` reuses the current frame instead of pushing a new one, so a
4883    /// tail-recursive function runs in constant stack space. It also has to be the
4884    /// *last* thing the function does, which is why only a `return` reaches here.
4885    fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
4886        let ExprKind::Call {
4887            callee,
4888            arguments,
4889            optional: false,
4890        } = &expr.unparen().kind
4891        else {
4892            return Ok(false);
4893        };
4894        // A spread call has no tail form: `tail_call` takes its arguments one at a time off
4895        // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
4896        // as an ordinary call costs the one frame the optimisation was saving and keeps the
4897        // semantics — the alternative was reaching the spread expression below and failing
4898        // with "this expression form is not supported", which is how `return super.m(...a)`
4899        // stopped compiling. Checked before anything is emitted, because the decision cannot
4900        // be taken back once `super_base` or a `get_field2` is on the stack.
4901        if Self::has_spread(arguments) {
4902            return Ok(false);
4903        }
4904        let end = self.new_label();
4905        if let ExprKind::Member {
4906            object,
4907            property,
4908            optional: false,
4909        } = &callee.unparen().kind
4910        {
4911            // `super.m()` in tail position is still an ordinary method call with `this`
4912            // as the receiver; only the read of the method differs.
4913            if matches!(object.unparen().kind, ExprKind::SuperProp) {
4914                self.super_base();
4915                match property {
4916                    MemberProp::Ident(name) => self.emit(
4917                        Opcode::PushAtomValue,
4918                        &[Op::Atom(Atom::from_text(&name.name))],
4919                    ),
4920                    MemberProp::Computed(index) => self.expr(index)?,
4921                    MemberProp::Private(_) => return Ok(false),
4922                }
4923                self.emit(Opcode::GetArrayEl, &[]);
4924                for argument in arguments {
4925                    self.expr(argument)?;
4926                }
4927                self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
4928                self.place_label(end);
4929                return Ok(true);
4930            }
4931            self.chain_link(object, end)?;
4932            match property {
4933                MemberProp::Ident(name) => {
4934                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4935                }
4936                MemberProp::Computed(index) => {
4937                    self.expr(index)?;
4938                    self.emit(Opcode::GetArrayEl2, &[]);
4939                }
4940                MemberProp::Private(_) => return Ok(false),
4941            }
4942            for argument in arguments {
4943                self.expr(argument)?;
4944            }
4945            self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
4946            self.place_label(end);
4947            return Ok(true);
4948        }
4949        self.chain_link(callee, end)?;
4950        for argument in arguments {
4951            self.expr(argument)?;
4952        }
4953        self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
4954        self.place_label(end);
4955        Ok(true)
4956    }
4957
4958    /// The `?.` guard: keep the value if it is neither null nor undefined,
4959    /// otherwise replace it with `undefined` and leave the whole chain.
4960    fn optional_guard(&mut self, end: Label) {
4961        let cont = self.new_label();
4962        self.emit(Opcode::Dup, &[]);
4963        self.emit(Opcode::IsUndefinedOrNull, &[]);
4964        self.emit_jump(Opcode::IfFalse, cont, &[]);
4965        self.emit(Opcode::Drop, &[]);
4966        self.emit(Opcode::Undefined, &[]);
4967        self.emit_jump(Opcode::Goto, end, &[]);
4968        self.place_label(cont);
4969    }
4970
4971    fn push_number(&mut self, value: f64) {
4972        // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
4973        // goes into the constant pool.
4974        if value == value.trunc() && value.abs() <= i32::MAX as f64 {
4975            let int = value as i32;
4976            if (-1..=7).contains(&int) {
4977                self.emit(Opcode::PushI32, &[Op::Int(int)]);
4978                return;
4979            }
4980            if (-128..=127).contains(&int) {
4981                self.emit(Opcode::PushI8, &[Op::Int(int)]);
4982                return;
4983            }
4984            if (-32768..=32767).contains(&int) {
4985                self.emit(Opcode::PushI16, &[Op::Int(int)]);
4986                return;
4987            }
4988            self.emit(Opcode::PushI32, &[Op::Int(int)]);
4989            return;
4990        }
4991        let index = self.push_constant(Constant::Number(value));
4992        self.emit(Opcode::PushConst, &[Op::Const(index)]);
4993    }
4994
4995    /// Push a `BigInt` literal.
4996    ///
4997    /// A value that fits an `i32` uses the immediate form, which is what the reference
4998    /// emits too; anything larger goes into the constant pool, because the operand of
4999    /// `push_bigint` is only four bytes wide.
5000    fn push_bigint(&mut self, digits: &str, radix: u32) {
5001        if radix == 10
5002            && let Ok(value) = digits.parse::<i64>()
5003            && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
5004        {
5005            self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
5006            return;
5007        }
5008        let index = self.push_constant(Constant::BigInt {
5009            digits: digits.to_string(),
5010            radix,
5011        });
5012        self.emit(Opcode::PushConst, &[Op::Const(index)]);
5013    }
5014
5015    fn push_string(&mut self, text: &Wtf8) {
5016        if text.is_empty() {
5017            self.emit(Opcode::PushEmptyString, &[]);
5018            return;
5019        }
5020        self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
5021    }
5022
5023    /// Name an anonymous function from the binding it is assigned to.
5024    ///
5025    /// `var f = function(){}` produces a function whose `name` is `f`, which the
5026    /// runtime cannot know without being told: the function object is created
5027    /// before the store. `set_name` carries the name across.
5028    fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
5029        if value.is_anonymous_function_definition() {
5030            self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
5031        }
5032    }
5033
5034    /// The same, for a computed key: the name comes from the value on the stack
5035    /// rather than from an atom, so a different instruction carries it.
5036    fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
5037        if value.is_anonymous_function_definition() {
5038            self.emit(Opcode::SetNameComputed, &[]);
5039        }
5040    }
5041
5042    /// Compile a function body that exists only in the compiler's head — a class's
5043    /// implicit constructor or its field initialiser.
5044    ///
5045    /// Everything structural is the same as a written function: a fresh `FnState`, its
5046    /// own body block, and resolution while the frame is still on the stack. Only the
5047    /// statements differ.
5048    fn compile_synthetic_function(
5049        &mut self,
5050        name: &str,
5051        strict: bool,
5052        span: Span,
5053        body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
5054    ) -> Result<CompiledFunction, SyntaxError> {
5055        let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
5056        state.strict = strict;
5057        state.created_in_block = self.cur().current_block;
5058        state.with_names = self.cur().with_names.clone();
5059        state.line = span.start.line;
5060        state.column = span.start.column;
5061        let depth = self.stack.len();
5062        self.stack.push(state);
5063        let body_key = span.start.offset as u64;
5064        self.push_block(body_key, NO_PARENT);
5065        self.state().body_block = body_key;
5066        let result = (|| {
5067            self.emit_scope_enter(body_key);
5068            body(self)?;
5069            if self.end_is_reachable() {
5070                self.emit(Opcode::ReturnUndef, &[]);
5071            }
5072            Ok(())
5073        })();
5074        if result.is_err() {
5075            self.stack.truncate(depth);
5076            return result.map(|()| unreachable!());
5077        }
5078        Ok(self.finish_current())
5079    }
5080
5081    /// The implicit return of a class constructor.
5082    ///
5083    /// A constructor that falls off the end initialises its instance fields first, and a
5084    /// derived one returns `this` — which is what makes `new D()` the object `super()`
5085    /// built rather than `undefined`.
5086    fn emit_class_constructor_tail(&mut self) {
5087        match self.cur().ctor_kind {
5088            CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
5089            // Nothing to install: a base constructor did it in its prologue and a derived
5090            // one at each `super()` site, which is where `this` first exists.
5091            CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
5092            CtorKind::Derived => {
5093                // `get_loc_check` rather than `get_loc`: reaching the end without ever
5094                // running `super()` is a ReferenceError, not `undefined`.
5095                self.emit_var(VarAction::Get, "this");
5096                self.emit(Opcode::Return, &[]);
5097            }
5098        }
5099    }
5100
5101    /// `yield expr` / `yield* expr`.
5102    ///
5103    /// The suspension itself is one instruction: the value is on the stack, `yield` hands
5104    /// it to the caller and parks the frame. On resume the stack holds the value the
5105    /// caller passed *and* a "magic" number saying which method resumed it — `next`
5106    /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
5107    /// `if_false <continue>` asks whether this was an ordinary `next`:
5108    ///
5109    /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
5110    /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
5111    ///   and uses the value sitting under the magic number.
5112    ///
5113    /// A `throw` never reaches here: the interpreter unwinds instead (see
5114    /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
5115    fn yield_expression(
5116        &mut self,
5117        argument: Option<&Expr>,
5118        delegate: bool,
5119    ) -> Result<(), SyntaxError> {
5120        if delegate {
5121            return self.yield_star(argument);
5122        }
5123        // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
5124        // does the same for the `return(v)` that can resume it — which is why an async
5125        // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
5126        // generator's is just `yield`.
5127        let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
5128        match argument {
5129            Some(value) => self.expr(value)?,
5130            None => self.emit(Opcode::Undefined, &[]),
5131        }
5132        if is_async {
5133            self.emit(Opcode::Await, &[]);
5134            self.state().has_await = true;
5135        }
5136        self.emit(Opcode::Yield, &[]);
5137        let resume = self.new_label();
5138        self.emit_jump(Opcode::IfFalse, resume, &[]);
5139        // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
5140        // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
5141        // finished the generator and never ran the `finally`.
5142        if is_async {
5143            self.emit(Opcode::Await, &[]);
5144        }
5145        self.emit_unwind_for_return(true);
5146        self.emit(Opcode::ReturnAsync, &[]);
5147        self.place_label(resume);
5148        // Nothing is emitted here: the value the caller passed to `next` *is* the value
5149        // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
5150        // it through the ordinary expression-statement discard.
5151        Ok(())
5152    }
5153
5154    /// `yield* iterable`.
5155    ///
5156    /// The shape is the reference's, and it is a fall-through chain rather than a
5157    /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
5158    /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
5159    /// the inner iterator and finishes, `throw` forwards the exception into it and
5160    /// continues only if it has a `throw` method.
5161    ///
5162    /// The stack is `iter next catch value` throughout, `catch` being the offset
5163    /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
5164    fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
5165        match argument {
5166            Some(value) => self.expr(value)?,
5167            // The parser rejects a bare `yield*`, so this is unreachable in practice.
5168            None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
5169        }
5170        // `for await of` is the same protocol as `for of` with two differences that matter
5171        // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
5172        // every `next()` result is a promise the delegate has to await.
5173        let is_async = self.cur().kind.is_async();
5174        self.emit(
5175            if is_async {
5176                Opcode::ForAwaitOfStart
5177            } else {
5178                Opcode::ForOfStart
5179            },
5180            &[],
5181        );
5182        self.emit(Opcode::Drop, &[]);
5183        self.emit(Opcode::Undefined, &[]);
5184        self.emit(Opcode::Undefined, &[]);
5185        let next = self.new_label();
5186        let resume = self.new_label();
5187        let finished = self.new_label();
5188        let rethrow = self.new_label();
5189        let throw_no_method = self.new_label();
5190        let done = self.new_label();
5191        self.place_label(next);
5192        self.emit(Opcode::IteratorNext, &[]);
5193        if is_async {
5194            self.emit(Opcode::Await, &[]);
5195            self.state().has_await = true;
5196        }
5197        self.emit(Opcode::IteratorCheckObject, &[]);
5198        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5199        self.emit_jump(Opcode::IfTrue, done, &[]);
5200        // The suspension. `resume` is both the label the return path jumps back to in order
5201        // to yield one more value and where the caller's answer arrives, as the value
5202        // followed by the magic number.
5203        //
5204        // The two forms differ in what they hand the suspension: `yield_star` takes the
5205        // result object itself, `async_yield_star` takes `.value`, because an async
5206        // generator awaits and re-wraps whatever it yields.
5207        self.place_label(resume);
5208        if is_async {
5209            self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5210            self.emit(Opcode::AsyncYieldStar, &[]);
5211        } else {
5212            self.emit(Opcode::YieldStar, &[]);
5213        }
5214        self.emit(Opcode::Dup, &[]);
5215        self.emit_jump(Opcode::IfTrue, rethrow, &[]);
5216        self.emit(Opcode::Drop, &[]);
5217        self.emit_jump(Opcode::Goto, next, &[]);
5218
5219        // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
5220        self.place_label(rethrow);
5221        self.emit(Opcode::PushI32, &[Op::Int(2)]);
5222        self.emit(Opcode::StrictEq, &[]);
5223        self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
5224        // A `return` closes the inner iterator; if it had none, the delegate simply
5225        // finishes with the requested value. In an async generator both the call and its
5226        // result are awaited, because the inner `return` may itself be async.
5227        if is_async {
5228            self.emit(Opcode::Await, &[]);
5229        }
5230        self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
5231        self.emit_jump(Opcode::IfTrue, finished, &[]);
5232        if is_async {
5233            self.emit(Opcode::Await, &[]);
5234        }
5235        self.emit(Opcode::IteratorCheckObject, &[]);
5236        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5237        self.emit_jump(Opcode::IfFalse, resume, &[]);
5238        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5239        self.place_label(finished);
5240        self.emit(Opcode::Nip, &[]);
5241        self.emit(Opcode::Nip, &[]);
5242        self.emit(Opcode::Nip, &[]);
5243        // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
5244        // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
5245        // awaits the value in an async generator and then runs the same `finally`/iterator
5246        // unwinding a written `return` would. Skipping the unwinding made
5247        // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
5248        if is_async {
5249            self.emit(Opcode::Await, &[]);
5250        }
5251        self.emit_unwind_for_return(true);
5252        self.emit(Opcode::ReturnAsync, &[]);
5253
5254        // `throw(e)`: forward it into the inner iterator.
5255        self.place_label(throw_no_method);
5256        self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
5257        let no_throw = self.new_label();
5258        self.emit_jump(Opcode::IfTrue, no_throw, &[]);
5259        if is_async {
5260            self.emit(Opcode::Await, &[]);
5261        }
5262        self.emit(Opcode::IteratorCheckObject, &[]);
5263        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5264        self.emit_jump(Opcode::IfFalse, resume, &[]);
5265        self.emit_jump(Opcode::Goto, done, &[]);
5266        // No `throw` method: close the iterator, then report the spec's TypeError. The
5267        // `if_true` before the `await` is the reference's shape — the flag it consumes is
5268        // what `iterator_call` leaves behind, and a close that *did* find no `return`
5269        // method has nothing to await.
5270        self.place_label(no_throw);
5271        self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
5272        let no_close = self.new_label();
5273        self.emit_jump(Opcode::IfTrue, no_close, &[]);
5274        if is_async {
5275            self.emit(Opcode::Await, &[]);
5276        }
5277        self.place_label(no_close);
5278        self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
5279
5280        // The inner iterator finished: the delegate's value is the `yield*` expression's
5281        // value, so it is left on the stack for whatever consumes it.
5282        self.place_label(done);
5283        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5284        self.emit(Opcode::Nip, &[]);
5285        self.emit(Opcode::Nip, &[]);
5286        self.emit(Opcode::Nip, &[]);
5287        Ok(())
5288    }
5289
5290    /// `await expr`: exactly one instruction.
5291    ///
5292    /// No resume-magic branch follows it. The reference's `await` leaves a single value
5293    /// on the stack and completion is signalled by the `return_async` at the end of the
5294    /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
5295    /// reference never emits, and a `for await` loop — which reaches `await` through the
5296    /// same opcode — would then spill a value the loop's unpacking does not expect.
5297    fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
5298        self.expr(argument)?;
5299        self.emit(Opcode::Await, &[]);
5300        self.state().has_await = true;
5301        Ok(())
5302    }
5303
5304    /// The `super` base: the receiver followed by the home object's prototype.
5305    ///
5306    /// Everything `super` does needs both. A *read* starts at the prototype but reports
5307    /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
5308    /// prototype but calls it with the receiver.
5309    fn super_base(&mut self) {
5310        self.this_expression();
5311        self.home_object();
5312        self.emit(Opcode::GetSuper, &[]);
5313    }
5314
5315    /// `[[HomeObject]]` as `super` sees it.
5316    ///
5317    /// A method, a constructor and a field initialiser each carry one — `set_home_object`
5318    /// put it there — so for them the special object *is* the answer. An arrow and a
5319    /// static block have none: they read the enclosing function's, which has to be
5320    /// materialised into a local, exactly as `this` is for an arrow.
5321    ///
5322    /// The name matches what the reference stores, so the disassembly agrees; it is not a
5323    /// name any program can write.
5324    fn home_object(&mut self) {
5325        if !self.cur().is_arrow {
5326            self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
5327            return;
5328        }
5329        if let Some(target) = self.enclosing_function() {
5330            self.state_at(target).needs_home_object_local = true;
5331            self.declare_at(target, HOME_OBJECT);
5332        }
5333        self.emit_var(VarAction::Get, HOME_OBJECT);
5334    }
5335
5336    /// `super(args)`: construct the parent class and adopt the result as `this`.
5337    ///
5338    /// The parent is the prototype of the constructor that is running, which is exactly
5339    /// what `extends` set up. `new.target` is passed through unchanged so that
5340    /// `new.target` inside the parent is the class actually being constructed.
5341    fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5342        self.active_func_expression();
5343        self.emit(Opcode::GetSuper, &[]);
5344        self.new_target_expression();
5345        if Self::has_spread(arguments) {
5346            self.argument_array(arguments)?;
5347            self.emit(Opcode::Apply, &[Op::Int(1)]);
5348        } else {
5349            for argument in arguments {
5350                self.expr(argument)?;
5351            }
5352            self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
5353        }
5354        // The value stays on the stack: `super()` is an expression, and a derived
5355        // constructor's `this` may only be initialised once.
5356        self.emit(Opcode::Dup, &[]);
5357        self.emit_var(VarAction::PutInitChecked, "this");
5358        // Instance fields are installed here, not at the top of the body: a derived
5359        // constructor has no `this` to install them on until `super()` returns. The
5360        // reference emits the same call at every `super()` site.
5361        self.call_field_initialiser();
5362        Ok(())
5363    }
5364
5365    /// `this` as a local, which every class constructor and field initialiser needs.
5366    ///
5367    /// The reference materialises the receiver into a local rather than reading
5368    /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
5369    /// and a field initialiser has to see the final value.
5370    fn begin_this_local(&mut self) {
5371        self.declare_hidden_local("this", VarKind::Normal);
5372        self.emit(Opcode::PushThis, &[]);
5373        self.emit_var(VarAction::Put, "this");
5374        // The store is already at the top of the body, so `provide_this_local` has
5375        // nothing left to prepend. Without this the initialiser ended up with
5376        // `push_this; put_loc0 this` twice whenever the class also held a field
5377        // initialiser whose body read `this` through an arrow.
5378        self.state().has_this_prologue = true;
5379    }
5380
5381    /// Compile a constructor the class wrote.
5382    ///
5383    /// The flags have to be in place before the body is compiled, but
5384    /// `compile_function_with_name` creates its own state — so the caller's state is
5385    /// marked instead and the new one inherits it. That is the same trick the parameter
5386    /// prologue uses, and it keeps one code path for both.
5387    fn compile_class_constructor(
5388        &mut self,
5389        func: &ast::Function,
5390        has_heritage: bool,
5391    ) -> Result<CompiledFunction, SyntaxError> {
5392        let saved = self.cur().ctor_kind;
5393        self.state().class_ctor_pending = Some(if has_heritage {
5394            CtorKind::Derived
5395        } else {
5396            CtorKind::Base
5397        });
5398        let result = self.compile_function_with_name(func, false);
5399        self.state().ctor_kind = saved;
5400        self.state().class_ctor_pending = None;
5401        result
5402    }
5403
5404    /// The constructor a class gets when it does not declare one.
5405    ///
5406    /// A base class's is empty; a derived class's forwards every argument to the parent
5407    /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
5408    /// instance field initialiser afterwards when the class has fields, which is why the
5409    /// initialiser is captured rather than inlined.
5410    fn compile_implicit_constructor(
5411        &mut self,
5412        class: &Class,
5413        has_heritage: bool,
5414    ) -> Result<CompiledFunction, SyntaxError> {
5415        self.compile_synthetic_function(
5416            "",
5417            true,
5418            Span::new(class.body_end, class.body_end),
5419            |compiler| {
5420                if has_heritage {
5421                    // A derived constructor's `this` does not exist until `super()` returns,
5422                    // so it starts in the dead zone and `init_ctor` fills it.
5423                    compiler.declare("this", VarDef::lexical("this"));
5424                    compiler.emit(
5425                        Opcode::SetLocUninitialized,
5426                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5427                    );
5428                    compiler.emit(Opcode::InitCtor, &[]);
5429                    compiler.emit(
5430                        Opcode::PutLocCheckInit,
5431                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5432                    );
5433                } else {
5434                    compiler.begin_this_local();
5435                    compiler.emit(Opcode::CheckCtor, &[]);
5436                }
5437                compiler.call_field_initialiser();
5438                // A derived constructor returns `this`, the object `super()` built. Without
5439                // this the implicit constructor fell through to `return_undef`, and `new B()`
5440                // handed back the empty object `construct` had made instead of the one the
5441                // parent constructor initialised.
5442                if has_heritage {
5443                    compiler.emit_var(VarAction::Get, "this");
5444                    compiler.emit(Opcode::Return, &[]);
5445                }
5446                Ok(())
5447            },
5448        )
5449    }
5450
5451    /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
5452    ///
5453    /// A class with no instance fields leaves the binding `undefined`, and calling it
5454    /// would throw; the reference emits the same guard rather than branching at compile
5455    /// time because a class can be extended by a subclass whose fields still have to run.
5456    fn call_field_initialiser(&mut self) {
5457        let skip = self.new_label();
5458        self.emit_var(VarAction::Get, "<class_fields_init>");
5459        self.emit(Opcode::Dup, &[]);
5460        self.emit_jump(Opcode::IfFalse, skip, &[]);
5461        self.emit_var(VarAction::Get, "this");
5462        self.emit(Opcode::Swap, &[]);
5463        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
5464        self.place_label(skip);
5465        self.emit(Opcode::Drop, &[]);
5466    }
5467
5468    /// The function that defines one class's fields on `this`, and runs its static blocks.
5469    ///
5470    /// `define_field` rather than `put_field`: a field is an own property created
5471    /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
5472    /// `x = 1` field must not call the setter.
5473    ///
5474    /// One function serves the whole class: it is called once per instance (or once, for
5475    /// the static half) and walks the members in source order. Static blocks are compiled
5476    /// into the same function because they *are* part of the same sequence — `static a =
5477    /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
5478    /// different values, so the two kinds cannot be split apart.
5479    fn compile_field_initialiser(
5480        &mut self,
5481        items: &[StaticInitItem<'_>],
5482        span: Span,
5483        instance: bool,
5484        add_brand: bool,
5485    ) -> Result<CompiledFunction, SyntaxError> {
5486        self.compile_synthetic_function("", true, span, |compiler| {
5487            if instance {
5488                // An instance initialiser always carries a `<home_object>` local, because the
5489                // brand block below reads it — even when that block turns out to be dead. The
5490                // reference has the same artefact, and the store is visible in its dump.
5491                let current = compiler.stack.len() - 1;
5492                compiler.stack[current].needs_home_object_local = true;
5493            }
5494            compiler.begin_this_local();
5495            if instance {
5496                // `this` gets the brand the prototype created, before any field is defined —
5497                // which is what makes `#m()` usable from inside a field initialiser.
5498                //
5499                // The reference always emits `push_false; if_false L; this; home; add_brand;
5500                // L:` and patches the `push_false` to `push_true` from the class parse when
5501                // the class has private methods; either way the branch folds, but the *mark*
5502                // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
5503                // `this` local from being fused into a `set_loc`.
5504                let skip = compiler.new_label();
5505                if add_brand {
5506                    compiler.emit(Opcode::PushTrue, &[]);
5507                } else {
5508                    compiler.emit(Opcode::PushFalse, &[]);
5509                }
5510                compiler.emit_jump(Opcode::IfFalse, skip, &[]);
5511                compiler.emit_var(VarAction::Get, "this");
5512                compiler.emit_var(VarAction::Get, HOME_OBJECT);
5513                compiler.emit(Opcode::AddBrand, &[]);
5514                compiler.place_label(skip);
5515            }
5516            for item in items {
5517                match item {
5518                    StaticInitItem::Field(key, value) => {
5519                        // A private field is *defined*, not assigned: `define_private_field`
5520                        // reads `obj symbol value`, and its point is that it fails on a
5521                        // receiver that is not this class's — which `put_field` would not.
5522                        //
5523                        // The three shapes are the reference's: `define_field <atom>` for a
5524                        // static name, `define_array_el` for a key that is only known at run
5525                        // time (`obj key value`), `define_private_field` for `#x`, and a
5526                        // computed key is read from its binding rather than recomputed.
5527                        compiler.emit_var(VarAction::Get, "this");
5528                        match key {
5529                            FieldKey::Private(binding) | FieldKey::Computed(binding) => {
5530                                compiler.emit_var(VarAction::Get, binding);
5531                            }
5532                            FieldKey::Literal(_) => {}
5533                        }
5534                        match value {
5535                            Some(value) => compiler.expr(value)?,
5536                            None => compiler.emit(Opcode::Undefined, &[]),
5537                        }
5538                        match key {
5539                            FieldKey::Literal(literal) => {
5540                                let text = compiler.property_key_text(literal, span)?;
5541                                compiler
5542                                    .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
5543                            }
5544                            FieldKey::Computed(_) => {
5545                                compiler.emit(Opcode::DefineArrayEl, &[]);
5546                                // `define_array_el` leaves `obj key`; the key is consumed by
5547                                // the copy the pattern machinery wants, so both go.
5548                                compiler.emit(Opcode::Drop, &[]);
5549                            }
5550                            FieldKey::Private(_) => {
5551                                compiler.emit(Opcode::DefinePrivateField, &[]);
5552                            }
5553                        }
5554                        compiler.emit(Opcode::Drop, &[]);
5555                    }
5556                    StaticInitItem::Block { body, body_start } => {
5557                        let block = compiler.compile_static_block(body, *body_start)?;
5558                        let index = compiler.push_constant(Constant::Function(Box::new(block)));
5559                        // `this fclosure`, so `call_method` finds the receiver below the
5560                        // callee: the block runs with `this` bound to the class.
5561                        compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
5562                        compiler.emit_var(VarAction::Get, "this");
5563                        compiler.emit(Opcode::Swap, &[]);
5564                        compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
5565                        // Nothing the block evaluates is wanted; its effects are the point.
5566                        compiler.emit(Opcode::Drop, &[]);
5567                    }
5568                }
5569            }
5570            Ok(())
5571        })
5572    }
5573
5574    /// Compile a `static { … }` body into the function the class calls for it.
5575    ///
5576    /// Shaped like an arrow, because that is the one function form with no `this`,
5577    /// `new.target` or `arguments` of its own: all three reach the enclosing static
5578    /// initialiser, and through it the class. `arguments` never gets that far — the parser
5579    /// rejects the reference — but `this` and `super` both depend on it.
5580    ///
5581    /// The body is hoisted like a function body's, because the reference parses it as one:
5582    /// `var` inside a block is a local of the block's function, not of whatever encloses
5583    /// the class.
5584    fn compile_static_block(
5585        &mut self,
5586        body: &[Stmt],
5587        body_start: Position,
5588    ) -> Result<CompiledFunction, SyntaxError> {
5589        let mut state = FnState::new(String::new(), FunctionKind::Normal);
5590        // Class bodies are strict, so a static block is too.
5591        state.strict = true;
5592        // The one property that makes this an arrow: nothing of its own to bind `this` to,
5593        // so `this` and `super` come from the initialiser that calls it.
5594        state.is_arrow = true;
5595        state.created_in_block = self.cur().current_block;
5596        state.with_names = self.cur().with_names.clone();
5597        state.line = body_start.line;
5598        state.column = body_start.column;
5599        let depth = self.stack.len();
5600        self.stack.push(state);
5601        let body_key = body_start.offset as u64;
5602        self.push_block(body_key, NO_PARENT);
5603        self.state().body_block = body_key;
5604        let result = (|| {
5605            self.hoist(body, body_key)?;
5606            self.emit_scope_enter(body_key);
5607            for statement in body {
5608                self.stmt(statement)?;
5609            }
5610            if self.end_is_reachable() {
5611                self.emit(Opcode::ReturnUndef, &[]);
5612            }
5613            Ok(())
5614        })();
5615        if result.is_err() {
5616            self.stack.truncate(depth);
5617            return result.map(|()| unreachable!());
5618        }
5619        Ok(self.finish_current())
5620    }
5621
5622    /// Compile a class, leaving the constructor on the stack when `keep`.
5623    ///
5624    /// The shape follows the reference: the class body is its own scope holding the
5625    /// class's *inner* name as a `const` — which is what lets a method refer to the
5626    /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
5627    /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
5628    /// on the top of the stack: the prototype for instance members, the constructor
5629    /// itself for `static` ones, which is why a static member costs an extra `swap`.
5630    fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
5631        let parent_block = self.cur().current_block;
5632        let key = class.span.start.offset as u64;
5633        self.push_block(key, parent_block);
5634        let name = class.name.as_ref().map(|ident| ident.name.clone());
5635        // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
5636        // resolves `E` without a global lookup. An *unnamed* class expression has no such
5637        // binding, and `define_class` is handed the empty name.
5638        if let Some(name) = &name {
5639            self.declare(name, VarDef::constant(name.clone()));
5640        }
5641        self.emit_scope_enter(key);
5642
5643        // The heritage clause is evaluated outside the class's own scope: it cannot see
5644        // the class binding it is about to initialise.
5645        let saved_block = self.cur().current_block;
5646        self.state().current_block = parent_block;
5647        match &class.super_class {
5648            Some(parent) => self.expr(parent)?,
5649            None => self.emit(Opcode::Undefined, &[]),
5650        }
5651        self.state().current_block = saved_block;
5652        let has_heritage = class.super_class.is_some();
5653
5654        // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
5655        // lands after the heritage's code — which is where the reference puts it, because it
5656        // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
5657        // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
5658        // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
5659        // came out in the opposite order from the reference's.
5660        //
5661        // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
5662        // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
5663        // a const accepts — so the old comment's worry ("a const would refuse the second
5664        // store") did not apply: there is no second store.
5665        // Every `#name` the class declares gets a `const` binding in the class scope, and so
5666        // does every computed field key. That is how the reference does it
5667        // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
5668        // what makes a private name resolve like any other class-scope variable — including
5669        // through a nested function's closure — while remaining invisible outside.
5670        //
5671        // All of them are declared *before* `<class_fields_init>`, in member order, because
5672        // that is when the reference's parser creates them.
5673        let plan = ClassPlan::build(class);
5674        // The body's private names are visible from here to the end of the class, and shadow
5675        // any outer class's of the same spelling. Pushed *before* the constructor is compiled
5676        // — it is compiled first because `define_class` consumes it, but its body can name
5677        // `#x` like any other member's.
5678        self.private_scopes.push(plan.uses.clone());
5679        let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
5680        for binding in &plan.bindings {
5681            class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
5682        }
5683        let fci = self.declare(
5684            "<class_fields_init>",
5685            VarDef::constant("<class_fields_init>"),
5686        );
5687        // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
5688        // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
5689        // members' bindings follow in reverse.
5690        self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
5691        for slot in class_slots.iter().rev() {
5692            self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
5693        }
5694
5695        // The constructor is compiled before `define_class` because that instruction
5696        // consumes it; a class without one gets the implicit version.
5697        let constructor = class.elements.iter().find_map(|element| match element {
5698            ClassElement::Method {
5699                kind: MethodKind::Constructor,
5700                func,
5701                ..
5702            } => Some(&**func),
5703            _ => None,
5704        });
5705        // A constructor is compiled differently from a method: it owns `this`. The flags
5706        // go on the *enclosing* state because a constructor is a nested function and
5707        // `compile_function_with_name` starts a fresh one.
5708        let ctor = match constructor {
5709            Some(func) => self.compile_class_constructor(func, has_heritage)?,
5710            None => self.compile_implicit_constructor(class, has_heritage)?,
5711        };
5712        // A closure, not the bare constant: the constructor captures
5713        // `<class_fields_init>`, which is only filled after `define_class` has run, so it
5714        // has to hold the cell rather than a copy of its value.
5715        //
5716        // The pool slot is left unassigned for now, because the reference gives the
5717        // constructor the *last* index of the members' range: `js_parse_class` emits a
5718        // `push_const` whose operand is patched at the end of the class parse, after every
5719        // method has taken a slot. Emitting the members first and the constant second is how
5720        // the numbering comes out the same; the instruction itself stays where it is.
5721        let ctor_insn = self.cur().insns.len();
5722        self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
5723        let flags = if has_heritage { 1 } else { 0 };
5724        self.emit(
5725            Opcode::DefineClass,
5726            &[
5727                Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
5728                Op::Int(flags),
5729            ],
5730        );
5731
5732        // Instance fields and static fields are two different functions: the first runs
5733        // per instance from the constructor, the second runs once, here.
5734        let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
5735        let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
5736        for (index, element) in class.elements.iter().enumerate() {
5737            match element {
5738                ClassElement::Method {
5739                    key: member_key,
5740                    is_static,
5741                    kind,
5742                    func,
5743                    span,
5744                } => {
5745                    if *kind == MethodKind::Constructor {
5746                        continue;
5747                    }
5748                    // `static(x)` is a *method* named `static`, not a static method; the
5749                    // parser already decided which by putting it in `kind`.
5750                    if *is_static {
5751                        self.emit(Opcode::Swap, &[]);
5752                    }
5753                    // A computed key is evaluated *here*, before the method's closure
5754                    // exists, and stays under it: `define_method_computed` pops
5755                    // `function, key, object`, so the stack has to read
5756                    // `[class, prototype, key, function]`. Evaluating the key after the
5757                    // `fclosure` and swapping the two put the prototype *below* the
5758                    // closure, which defined the method on the function and lost the
5759                    // prototype: `class C { [k]() {} }` left `C` undefined. The order is
5760                    // also the spec's — a class body evaluates every element's name before
5761                    // that element's function.
5762                    if let PropName::Computed(key) = member_key {
5763                        self.expr(key)?;
5764                    }
5765                    let function = self.compile_function_with_name(func, true)?;
5766                    let index = self.push_constant(Constant::Function(Box::new(function)));
5767                    self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5768                    match member_key {
5769                        // A private method is not a property of the prototype: it is a
5770                        // closure in the class scope, which is why nothing outside can reach
5771                        // it and why a use site has to brand-check. `set_name` gives the
5772                        // function its `name` (`#m`), which an accessor does not get — the
5773                        // reference leaves that commented out.
5774                        PropName::Private(ident) => {
5775                            let name = format!("#{}", ident.name);
5776                            // `set_home_object` first: the brand check reads the function's
5777                            // home object, and for a method that is the prototype.
5778                            self.emit(Opcode::SetHomeObject, &[]);
5779                            let binding = if *kind == MethodKind::Set {
5780                                format!("{name}<set>")
5781                            } else {
5782                                name.clone()
5783                            };
5784                            if *kind == MethodKind::Method {
5785                                self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
5786                            }
5787                            self.emit_var(VarAction::PutInit, &binding);
5788                        }
5789                        PropName::Computed(_) => {
5790                            self.emit(
5791                                Opcode::DefineMethodComputed,
5792                                &[Op::Int(class_method_flags(*kind))],
5793                            );
5794                        }
5795                        PropName::Literal(literal) => {
5796                            let text = self.property_key_text(literal, *span)?;
5797                            self.emit(
5798                                Opcode::DefineMethod,
5799                                &[
5800                                    Op::Atom(Atom::from_wtf8(&text)),
5801                                    Op::Int(class_method_flags(*kind)),
5802                                ],
5803                            );
5804                        }
5805                    }
5806                    if *is_static {
5807                        self.emit(Opcode::Swap, &[]);
5808                    }
5809                }
5810                ClassElement::Field {
5811                    key: field_key,
5812                    is_static,
5813                    value,
5814                    ..
5815                } => {
5816                    // A private field's *symbol* is created here, at the member, and stored
5817                    // in its binding: the field's property is keyed by it, so it has to exist
5818                    // before any initialiser runs, and a fresh one per class body is what
5819                    // makes two classes that both write `#x` independent.
5820                    //
5821                    // A computed key is evaluated once, here, and `to_propkey`'d once — a key
5822                    // whose `toString` has a side effect must not run again per instance.
5823                    let key = match field_key {
5824                        PropName::Private(ident) => {
5825                            let binding = format!("#{}", ident.name);
5826                            if *is_static {
5827                                self.emit(Opcode::Swap, &[]);
5828                            }
5829                            self.emit(
5830                                Opcode::PrivateSymbol,
5831                                &[Op::Atom(Atom::from_text(&binding))],
5832                            );
5833                            self.emit_var(VarAction::PutInit, &binding);
5834                            if *is_static {
5835                                self.emit(Opcode::Swap, &[]);
5836                            }
5837                            FieldKey::Private(binding)
5838                        }
5839                        PropName::Computed(expression) => {
5840                            let binding = plan
5841                                .computed
5842                                .get(&index)
5843                                .cloned()
5844                                .expect("every computed key got a binding");
5845                            if *is_static {
5846                                self.emit(Opcode::Swap, &[]);
5847                            }
5848                            self.expr(expression)?;
5849                            self.emit(Opcode::ToPropkey, &[]);
5850                            self.emit_var(VarAction::PutInit, &binding);
5851                            if *is_static {
5852                                self.emit(Opcode::Swap, &[]);
5853                            }
5854                            FieldKey::Computed(binding)
5855                        }
5856                        PropName::Literal(literal) => FieldKey::Literal(literal),
5857                    };
5858                    if *is_static {
5859                        static_items.push(StaticInitItem::Field(key, value.as_deref()));
5860                    } else {
5861                        instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
5862                    }
5863                }
5864                ClassElement::StaticBlock {
5865                    body, body_start, ..
5866                } => static_items.push(StaticInitItem::Block {
5867                    body,
5868                    body_start: *body_start,
5869                }),
5870            }
5871        }
5872
5873        // Now that every member has its slot, the constructor can have the next one and the
5874        // `fclosure` above can name it.
5875        let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
5876        match self.state().insns.get_mut(ctor_insn) {
5877            Some(Insn::Fixed { operands, .. }) => {
5878                operands[0] = Op::Const(ctor_index);
5879            }
5880            // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
5881            // loudly beats emitting a `fclosure` of slot 4294967295.
5882            _ => {
5883                return Err(SyntaxError::new(
5884                    "the class constructor's fclosure went missing",
5885                    class.span,
5886                ));
5887            }
5888        }
5889
5890        // The instance brand: a symbol created once on the prototype, which every instance
5891        // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
5892        // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
5893        // copy is created. The prototype is on top of the stack at this point.
5894        if plan.instance_brand {
5895            self.emit(Opcode::Dup, &[]);
5896            self.emit(Opcode::Null, &[]);
5897            self.emit(Opcode::Swap, &[]);
5898            self.emit(Opcode::AddBrand, &[]);
5899        }
5900
5901        // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
5902        // class has no instance fields. The constructor calls it only when it is defined.
5903        //
5904        // A class with private *methods* but no fields still needs one, because adding the
5905        // brand to each new instance is the initialiser's job.
5906        if instance_fields.is_empty() && !plan.instance_brand {
5907            self.emit(Opcode::Undefined, &[]);
5908        } else {
5909            let initialiser = self.compile_field_initialiser(
5910                &instance_fields,
5911                class.span,
5912                true,
5913                plan.instance_brand,
5914            )?;
5915            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
5916            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5917            // `set_home_object` reads `obj func`, so the prototype stays where it is.
5918            self.emit(Opcode::SetHomeObject, &[]);
5919        }
5920        self.emit_var(VarAction::PutInit, "<class_fields_init>");
5921        // The prototype has done its job: every instance member is defined on it. What
5922        // is left under it is the constructor.
5923        self.emit(Opcode::Drop, &[]);
5924
5925        // The static brand, for `static #m() {}`: same opcode, but the home object is the
5926        // constructor itself, so the symbol lands on the class and the class carries it.
5927        if plan.static_brand {
5928            self.emit(Opcode::Dup, &[]);
5929            self.emit(Opcode::Dup, &[]);
5930            self.emit(Opcode::AddBrand, &[]);
5931        }
5932
5933        // The class binding is initialised *before* static fields run, so a static field
5934        // can refer to the class by name (`static y = S.x`).
5935        // `set_loc` leaves the constructor on the stack, which is what the static field
5936        // call and the outer store both consume.
5937        //
5938        // Only when there *is* such a binding: an anonymous class expression declares no
5939        // class-scope name, and asking for one by the empty string resolved to nothing —
5940        // which made `var x = class {}` assign `undefined` and put a bogus global store in
5941        // the instruction stream.
5942        if let Some(name) = &name {
5943            self.emit_var(VarAction::SetInit, name);
5944        }
5945        if !static_items.is_empty() {
5946            // The static half has no brand prologue of its own: the constructor got its
5947            // brand above, before this runs.
5948            let initialiser =
5949                self.compile_field_initialiser(&static_items, class.span, false, false)?;
5950            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
5951            self.emit(Opcode::Dup, &[]);
5952            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5953            self.emit(Opcode::SetHomeObject, &[]);
5954            self.emit(Opcode::CallMethod, &[Op::Int(0)]);
5955            self.emit(Opcode::Drop, &[]);
5956        }
5957        // The body is over, and with it this class's private names.
5958        let _ = self.private_scopes.pop();
5959        self.emit_scope_leave(key);
5960        self.state().current_block = parent_block;
5961        if keep {
5962            // A class *expression* is its own value; the class-scope binding was only
5963            // ever an alias for it.
5964            return Ok(());
5965        }
5966        // A declaration stores into the binding the enclosing statement declared.
5967        self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
5968        Ok(())
5969    }
5970
5971    fn push_this(&mut self) {
5972        self.emit(Opcode::PushThis, &[]);
5973    }
5974
5975    /// `this`, which an arrow does not have of its own.
5976    ///
5977    /// The reference gives the enclosing function a local named `this`, initialised from
5978    /// `push_this` at the top of its body, and the arrow then reads it as a captured
5979    /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
5980    /// the arrow is called with none.
5981    fn this_expression(&mut self) {
5982        // In a class constructor `this` is a local: a derived constructor only gets one
5983        // when `super()` returns, and reading the raw receiver would give the *outer*
5984        // one instead.
5985        if self.cur().ctor_kind != CtorKind::None {
5986            self.emit_var(VarAction::Get, "this");
5987            return;
5988        }
5989        if !self.cur().is_arrow {
5990            self.push_this();
5991            return;
5992        }
5993        if let Some(target) = self.enclosing_function() {
5994            self.state_at(target).needs_this_local = true;
5995            self.declare_at(target, "this");
5996        }
5997        self.emit_var(VarAction::Get, "this");
5998    }
5999
6000    /// `new.target`, which an arrow likewise does not own.
6001    fn new_target_expression(&mut self) {
6002        if !self.cur().is_arrow {
6003            self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
6004            return;
6005        }
6006        if let Some(target) = self.enclosing_function() {
6007            self.state_at(target).needs_new_target_local = true;
6008            self.declare_at(target, NEW_TARGET);
6009        }
6010        self.emit_var(VarAction::Get, NEW_TARGET);
6011    }
6012
6013    /// `this.active_func`: the function `super()` resolves against.
6014    ///
6015    /// In a constructor or a method that is the function being run, so the special object
6016    /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
6017    /// a closure variable — see [`FnState::needs_active_func_local`].
6018    fn active_func_expression(&mut self) {
6019        if !self.cur().is_arrow {
6020            self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
6021            return;
6022        }
6023        if let Some(target) = self.enclosing_function() {
6024            self.state_at(target).needs_active_func_local = true;
6025            self.declare_at(target, ACTIVE_FUNC);
6026        }
6027        self.emit_var(VarAction::Get, ACTIVE_FUNC);
6028    }
6029
6030    /// Give the function a local `<active_func>`, for an arrow inside it to capture.
6031    fn provide_active_func_local(&mut self) {
6032        let current = self.stack.len() - 1;
6033        if !self.stack[current].needs_active_func_local {
6034            return;
6035        }
6036        if !self.stack[current]
6037            .vars
6038            .iter()
6039            .any(|var| var.name == ACTIVE_FUNC)
6040        {
6041            self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
6042        }
6043        self.prepend_initialiser(
6044            ACTIVE_FUNC,
6045            Insn::Fixed {
6046                op: Opcode::SpecialObject,
6047                operands: vec![Op::Int(2)],
6048            },
6049        );
6050    }
6051
6052    /// Give the function a local `new.target`, for an arrow inside it to capture.
6053    fn provide_new_target_local(&mut self) {
6054        let current = self.stack.len() - 1;
6055        if !self.stack[current].needs_new_target_local {
6056            return;
6057        }
6058        if !self.stack[current]
6059            .vars
6060            .iter()
6061            .any(|var| var.name == NEW_TARGET)
6062        {
6063            self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
6064        }
6065        self.prepend_initialiser(
6066            NEW_TARGET,
6067            Insn::Fixed {
6068                op: Opcode::SpecialObject,
6069                operands: vec![Op::Int(3)],
6070            },
6071        );
6072    }
6073
6074    /// `arguments` reached from an arrow, which likewise belongs to the enclosing
6075    /// function.
6076    fn ensure_enclosing_arguments(&mut self) {
6077        // An arrow created in a parameter list needs the *parameter* scope's
6078        // `arguments`, not the body's: the two are separate bindings and the arrow was
6079        // born before the body existed.
6080        let from_params = self.cur().created_in_params;
6081        if let Some(target) = self.enclosing_function() {
6082            self.state_at(target).needs_arguments_local = true;
6083            if from_params {
6084                self.state_at(target).needs_param_arguments = true;
6085                // Declare it now, not at the enclosing function's `finish_current`: the
6086                // arrow resolves its own `arguments` before that runs, and a binding that
6087                // does not exist yet resolves as a global.
6088                declare_param_var_at(&mut self.stack[target], "arguments");
6089            }
6090            self.declare_at(target, "arguments");
6091        }
6092    }
6093
6094    /// The innermost enclosing frame that is a real function — an arrow inherits from it
6095    /// rather than starting a scope of its own.
6096    fn enclosing_function(&self) -> Option<usize> {
6097        (0..self.stack.len())
6098            .rev()
6099            .find(|index| !self.stack[*index].is_arrow && !self.stack[*index].is_script)
6100    }
6101
6102    fn state_at(&mut self, index: usize) -> &mut FnState {
6103        &mut self.stack[index]
6104    }
6105
6106    /// Declare a `var` binding directly in a specific frame.
6107    fn declare_at(&mut self, index: usize, name: &str) {
6108        let state = &mut self.stack[index];
6109        if state.vars.iter().any(|var| var.name == name) {
6110            return;
6111        }
6112        state.var_block.push(FUNCTION_SCOPE);
6113        state.vars.push(VarDef::var(name));
6114    }
6115
6116    /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
6117    /// the reference calls a `special_object` gets initialised on entry.
6118    fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
6119        let current = self.stack.len() - 1;
6120        let init = [
6121            producer,
6122            Insn::Var {
6123                action: VarAction::Put,
6124                name: name.to_string(),
6125                block: 0,
6126                // A prologue initialiser runs before the body proper, but it is body
6127                // code: `this` and `arguments` are provided for it, not by it.
6128                in_params: false,
6129            },
6130        ];
6131        let inserted = init.len();
6132        for (index, instruction) in init.into_iter().enumerate() {
6133            self.stack[current].insns.insert(index, instruction);
6134        }
6135        for placed in self.stack[current].labels.iter_mut().flatten() {
6136            *placed += inserted;
6137        }
6138        self.stack[current].label_since_insn = true;
6139    }
6140
6141    fn push_constant(&mut self, constant: Constant) -> u32 {
6142        let state = self.state();
6143        let index = state.cpool.len() as u32;
6144        state.cpool.push(constant);
6145        index
6146    }
6147
6148    /// Compile `a && b`, `a || b`, `a ?? b`.
6149    ///
6150    /// A run of the *same* operator shares one end label, so `a || b || c` tests
6151    /// `a` once and jumps past everything when it is truthy, instead of falling
6152    /// into `b`'s test. The parser builds such a run left-associated —
6153    /// `((a || b) || c)` — so the operands are collected off the left spine.
6154    ///
6155    /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
6156    /// `||`'s label, because the inner chain really does end before `&&` begins.
6157    fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
6158        let mut operands = Vec::new();
6159        collect_same_operator(op, left, &mut operands);
6160        operands.push(right);
6161
6162        let end = self.new_label();
6163        // Every operand but the last decides whether the chain stops here.
6164        let last = operands.pop().expect("the right operand is always present");
6165        for operand in operands {
6166            self.expr(operand)?;
6167            self.emit(Opcode::Dup, &[]);
6168            match op {
6169                LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
6170                LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
6171                // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
6172                // `0 || b` is `b`. The dedicated test keeps the value unless it is
6173                // null-ish, so the jump is taken on `false`.
6174                LogicalOp::Coalesce => {
6175                    self.emit(Opcode::IsUndefinedOrNull, &[]);
6176                    self.emit_jump(Opcode::IfFalse, end, &[]);
6177                }
6178            }
6179            self.emit(Opcode::Drop, &[]);
6180        }
6181        self.expr(last)?;
6182        self.place_label(end);
6183        Ok(())
6184    }
6185
6186    fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
6187        match op {
6188            UnaryOp::Typeof => {
6189                // `typeof x` must not throw on an undeclared name.
6190                if let ExprKind::Ident(name) = &argument.kind {
6191                    self.emit_var(VarAction::GetUndef, &name.name);
6192                } else {
6193                    self.expr(argument)?;
6194                }
6195                self.emit(Opcode::Typeof, &[]);
6196            }
6197            UnaryOp::Delete => {
6198                // `delete obj.prop` really deletes, and answers whether it could.
6199                // Deleting a *binding* is always `false`: a local, an argument and a
6200                // declared global are all non-configurable, which the reference encodes
6201                // as a constant `push_false` rather than a runtime check. Only a
6202                // property access has anything to do at run time.
6203                // `delete super.x` is not a delete at all: the spec refuses it, and the
6204                // reference encodes the refusal as a `throw_error`. The receiver and the
6205                // key are still evaluated first, which is what keeps the evaluation order
6206                // of the operand intact.
6207                // `delete z?.b.c` answers `true` when the chain short-circuits: there is
6208                // nothing to delete, and a failed delete is not the same as a skipped
6209                // one. The reference emits the guards so they land on a `drop; push_true`
6210                // tail, which is what this reproduces.
6211                if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
6212                    && let ExprKind::Member {
6213                        object, property, ..
6214                    } = &inner.unparen().kind
6215                {
6216                    let end = self.new_label();
6217                    let done = self.new_label();
6218                    self.chain_link(object, end)?;
6219                    match property {
6220                        MemberProp::Ident(name) => self.emit(
6221                            Opcode::PushAtomValue,
6222                            &[Op::Atom(Atom::from_text(&name.name))],
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                    self.emit_jump(Opcode::Goto, done, &[]);
6234                    self.place_label(end);
6235                    self.emit(Opcode::Drop, &[]);
6236                    self.emit(Opcode::PushTrue, &[]);
6237                    self.place_label(done);
6238                    return Ok(());
6239                }
6240                if let ExprKind::Member { object, .. } = &argument.unparen().kind
6241                    && matches!(object.unparen().kind, ExprKind::SuperProp)
6242                {
6243                    self.super_base();
6244                    self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
6245                    return Ok(());
6246                }
6247                match &argument.kind {
6248                    ExprKind::Member {
6249                        object, property, ..
6250                    } => {
6251                        self.expr(object)?;
6252                        match property {
6253                            MemberProp::Ident(name) => {
6254                                self.emit(
6255                                    Opcode::PushAtomValue,
6256                                    &[Op::Atom(Atom::from_text(&name.name))],
6257                                );
6258                            }
6259                            MemberProp::Computed(index) => self.expr(index)?,
6260                            MemberProp::Private(_) => {
6261                                return Err(SyntaxError::new(
6262                                    "deleting a private field is not allowed",
6263                                    argument.span,
6264                                ));
6265                            }
6266                        }
6267                        self.emit(Opcode::Delete, &[]);
6268                    }
6269                    ExprKind::Ident(name) => {
6270                        // `delete name`: a declared global, a local and an argument all
6271                        // answer `false`, but an *implicit* global (`x = 1` with no
6272                        // declaration) is a configurable property of the global object
6273                        // and really goes away. Which of those a name is only the
6274                        // resolver knows, so the decision waits for it.
6275                        let pos = self.cur().cur_pos;
6276                        self.state().insns.push(Insn::DeleteVar {
6277                            name: name.name.clone(),
6278                        });
6279                        self.state().insn_pos.push(pos);
6280                    }
6281                    _ => self.emit(Opcode::PushFalse, &[]),
6282                }
6283            }
6284            UnaryOp::Void => {
6285                self.expr(argument)?;
6286                self.emit(Opcode::Drop, &[]);
6287                self.emit(Opcode::Undefined, &[]);
6288            }
6289            UnaryOp::Minus => {
6290                self.expr(argument)?;
6291                self.emit(Opcode::Neg, &[]);
6292            }
6293            UnaryOp::Plus => {
6294                self.expr(argument)?;
6295                self.emit(Opcode::Plus, &[]);
6296            }
6297            UnaryOp::Not => {
6298                self.expr(argument)?;
6299                self.emit(Opcode::Lnot, &[]);
6300            }
6301            UnaryOp::BitNot => {
6302                self.expr(argument)?;
6303                self.emit(Opcode::Not, &[]);
6304            }
6305        }
6306        Ok(())
6307    }
6308
6309    /// Compile an assignment.
6310    ///
6311    /// Three operator families, three shapes:
6312    ///
6313    /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
6314    ///   the value is kept, because `put_field`/`put_array_el` consume both the
6315    ///   object and the value: `insert2` is `obj a -> a obj a`, so the store sees
6316    ///   the pair it wants and leaves a copy on top.
6317    /// * **compound** `+=` … — read the place, apply the operator, store. A member
6318    ///   reads through `get_field2`/`get_array_el3`, which leave the object (and
6319    ///   index) underneath the value precisely so the store can follow.
6320    /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
6321    ///   right-hand side. The test *keeps* the current value and skips the store
6322    ///   entirely, which is the whole point: `a ||= b` must not evaluate `b` when
6323    ///   `a` is already truthy.
6324    fn assign(&mut self, op: AssignOp, target: &Pattern, value: &Expr) -> Result<(), SyntaxError> {
6325        // Reading the flag clears it: only the outermost assignment of an
6326        // expression statement may drop its value.
6327        let keep = !std::mem::take(&mut self.state().discard_value);
6328        match &target.kind {
6329            PatternKind::Ident(name) => {
6330                // A *simple* store is blamed on the identifier, not on the `=`: a
6331                // strict-mode `not_def = 1` raises when the name is written, which the
6332                // reference reports at the name's column. A compound store is blamed on
6333                // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
6334                // which the reference reports at the `+=`), so only the simple case
6335                // moves the position.
6336                let saved = self.cur().cur_pos;
6337                let name_pos = Some(name.span.start);
6338                if matches!(op, AssignOp::Assign) {
6339                    self.state().cur_pos = name_pos;
6340                }
6341                // A *compound* store reads the binding before it combines, and that read
6342                // is blamed on the identifier: `not_def += 2` fails while reading
6343                // `not_def`, so the position is the name's, not the `+=`'s. The
6344                // combination that follows is blamed on the operator, which is why
6345                // `cur_pos` is put back to the operator position before it is emitted.
6346                self.state().cur_pos = name_pos;
6347                match op {
6348                    AssignOp::Assign => {
6349                        self.expr(value)?;
6350                        self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
6351                        // A discarded store to a *slot* consumes its value, so no copy
6352                        // is needed. A global store goes through `put_var`, which the
6353                        // reference always pairs with a `dup` — matching it keeps the
6354                        // bytecode identical. Getting this wrong is not only an extra
6355                        // instruction: a stray copy gives the peephole a chance to fold
6356                        // the store into an unrelated later read.
6357                        let slot = self.is_slot(&name.name);
6358                        if keep || !slot {
6359                            self.emit(Opcode::Dup, &[]);
6360                        }
6361                        self.state().no_value = !keep && slot;
6362                        self.emit_var(VarAction::Put, &name.name);
6363                    }
6364                    AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6365                        let end = self.new_label();
6366                        self.emit_var(VarAction::Get, &name.name);
6367                        self.state().cur_pos = saved;
6368                        self.emit(Opcode::Dup, &[]);
6369                        self.emit_logical_test(op);
6370                        self.emit_jump(logical_jump(op), end, &[]);
6371                        self.emit(Opcode::Drop, &[]);
6372                        self.expr(value)?;
6373                        self.emit(Opcode::Dup, &[]);
6374                        self.emit_var(VarAction::Put, &name.name);
6375                        self.place_label(end);
6376                    }
6377                    _ => {
6378                        self.emit_var(VarAction::Get, &name.name);
6379                        self.expr(value)?;
6380                        self.state().cur_pos = saved;
6381                        self.emit(compound_opcode(op), &[]);
6382                        self.emit(Opcode::Dup, &[]);
6383                        self.emit_var(VarAction::Put, &name.name);
6384                    }
6385                }
6386                self.state().cur_pos = saved;
6387                Ok(())
6388            }
6389            PatternKind::Member(member) => {
6390                // `super.x = v` is not a store through a value: it starts at the home
6391                // object's prototype but writes to `this`, so it goes through
6392                // `put_super_value` rather than `put_field`. The receiver, prototype, key
6393                // and value are handed over together.
6394                if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
6395                    return self.assign_super(member, op, value);
6396                }
6397                // A store is blamed on the selector punctuator (`.` or `[`), the same
6398                // token a load is blamed on — the reference records `put_field obj.a`
6399                // at the `.`, so a setter that throws reports that column and not the
6400                // `=` of the assignment it sits in. The inner expressions restore their
6401                // own positions, so the selector's sticks for the store instructions.
6402                let saved = self.cur().cur_pos;
6403                self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6404                self.expr(&member.object)?;
6405                match &member.property {
6406                    MemberProp::Ident(property) => {
6407                        let atom = Atom::from_text(&property.name);
6408                        match op {
6409                            AssignOp::Assign => {
6410                                self.expr(value)?;
6411                                // `put_field` consumes the object and the value, so
6412                                // without `insert2` nothing is left over for the
6413                                // statement to drop.
6414                                self.state().no_value = !keep;
6415                                if keep {
6416                                    self.emit(Opcode::Insert2, &[]);
6417                                }
6418                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6419                            }
6420                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6421                                // `get_field2` leaves the object under the value, so
6422                                // the keep path has an object to dispose of. The store
6423                                // path must jump *over* that cleanup: falling into it
6424                                // would `nip` a stack that only holds the value.
6425                                let (keep_label, end) = (self.new_label(), self.new_label());
6426                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6427                                self.emit(Opcode::Dup, &[]);
6428                                self.emit_logical_test(op);
6429                                self.emit_jump(logical_jump(op), keep_label, &[]);
6430                                self.emit(Opcode::Drop, &[]);
6431                                self.expr(value)?;
6432                                self.emit(Opcode::Insert2, &[]);
6433                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6434                                self.emit_jump(Opcode::Goto, end, &[]);
6435                                self.place_label(keep_label);
6436                                self.emit(Opcode::Nip, &[]);
6437                                self.place_label(end);
6438                            }
6439                            _ => {
6440                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6441                                self.expr(value)?;
6442                                self.emit(compound_opcode(op), &[]);
6443                                self.state().no_value = !keep;
6444                                if keep {
6445                                    self.emit(Opcode::Insert2, &[]);
6446                                }
6447                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6448                            }
6449                        }
6450                    }
6451                    MemberProp::Computed(index) => {
6452                        self.expr(index)?;
6453                        match op {
6454                            AssignOp::Assign => {
6455                                self.expr(value)?;
6456                                self.state().no_value = !keep;
6457                                if keep {
6458                                    self.emit(Opcode::Insert3, &[]);
6459                                }
6460                                self.emit(Opcode::PutArrayEl, &[]);
6461                            }
6462                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6463                                let (keep_label, end) = (self.new_label(), self.new_label());
6464                                self.emit(Opcode::GetArrayEl3, &[]);
6465                                self.emit(Opcode::Dup, &[]);
6466                                self.emit_logical_test(op);
6467                                self.emit_jump(logical_jump(op), keep_label, &[]);
6468                                self.emit(Opcode::Drop, &[]);
6469                                self.expr(value)?;
6470                                self.emit(Opcode::Insert3, &[]);
6471                                self.emit(Opcode::PutArrayEl, &[]);
6472                                self.emit_jump(Opcode::Goto, end, &[]);
6473                                self.place_label(keep_label);
6474                                // Both the object and the index are left over.
6475                                self.emit(Opcode::Nip, &[]);
6476                                self.emit(Opcode::Nip, &[]);
6477                                self.place_label(end);
6478                            }
6479                            _ => {
6480                                self.emit(Opcode::GetArrayEl3, &[]);
6481                                self.expr(value)?;
6482                                self.emit(compound_opcode(op), &[]);
6483                                self.state().no_value = !keep;
6484                                if keep {
6485                                    self.emit(Opcode::Insert3, &[]);
6486                                }
6487                                self.emit(Opcode::PutArrayEl, &[]);
6488                            }
6489                        }
6490                    }
6491                    MemberProp::Private(name) => {
6492                        // `obj value` is on the stack, and every private store wants exactly
6493                        // that. A top-level private name cannot be assigned (the parser rejects
6494                        // `#x = 1`), so the only way here is `this.#x = …` inside the class.
6495                        //
6496                        // The reference emits `insert2` whether or not the value is wanted,
6497                        // so this does too: the copy left behind is the assignment expression's
6498                        // value, and a discarded one is simply never read.
6499                        let binding = format!("#{}", name.name);
6500                        let (kind, setter) = self.private_use(&binding, member.span)?;
6501                        match op {
6502                            AssignOp::Assign => {
6503                                self.expr(value)?;
6504                                if keep {
6505                                    self.emit(Opcode::Insert2, &[]);
6506                                }
6507                                self.private_store(&binding, kind, setter.as_deref())?;
6508                                self.state().no_value = !keep;
6509                            }
6510                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6511                                let (keep_label, end) = (self.new_label(), self.new_label());
6512                                self.emit(Opcode::Dup, &[]);
6513                                self.private_load(&binding, kind, member.span)?;
6514                                self.emit(Opcode::Dup, &[]);
6515                                self.emit_logical_test(op);
6516                                self.emit_jump(logical_jump(op), keep_label, &[]);
6517                                self.emit(Opcode::Drop, &[]);
6518                                self.expr(value)?;
6519                                self.emit(Opcode::Insert2, &[]);
6520                                self.private_store(&binding, kind, setter.as_deref())?;
6521                                self.emit_jump(Opcode::Goto, end, &[]);
6522                                self.place_label(keep_label);
6523                                self.emit(Opcode::Nip, &[]);
6524                                self.place_label(end);
6525                            }
6526                            _ => {
6527                                self.emit(Opcode::Dup, &[]);
6528                                self.private_load(&binding, kind, member.span)?;
6529                                self.expr(value)?;
6530                                self.emit(compound_opcode(op), &[]);
6531                                self.emit(Opcode::Insert2, &[]);
6532                                self.private_store(&binding, kind, setter.as_deref())?;
6533                            }
6534                        }
6535                    }
6536                }
6537                self.state().cur_pos = saved;
6538                Ok(())
6539            }
6540            // A destructuring assignment: the right-hand side is the expression's own
6541            // value, so it is evaluated once and kept under the pattern's stores.
6542            PatternKind::Array { .. } | PatternKind::Object { .. } => {
6543                self.expr(value)?;
6544                if keep {
6545                    self.emit(Opcode::Dup, &[]);
6546                }
6547                self.destructure(target, None)?;
6548                self.state().no_value = !keep;
6549                Ok(())
6550            }
6551            _ => Err(SyntaxError::new(
6552                "this assignment target is not supported by the compiler yet",
6553                target.span,
6554            )),
6555        }
6556    }
6557
6558    /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
6559    ///
6560    /// The stack has to carry four values — receiver, prototype, key, value — because
6561    /// `put_super_value` takes them together; the receiver is what makes a setter found on
6562    /// the prototype run with `this`, and the key has to survive until the store, which is
6563    /// why a compound form converts it to a property key once and `dup3`s rather than
6564    /// evaluating it twice.
6565    fn assign_super(
6566        &mut self,
6567        member: &MemberPattern,
6568        op: AssignOp,
6569        value: &Expr,
6570    ) -> Result<(), SyntaxError> {
6571        let saved = self.cur().cur_pos;
6572        self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6573        self.super_base();
6574        match &member.property {
6575            MemberProp::Ident(property) => self.emit(
6576                Opcode::PushAtomValue,
6577                &[Op::Atom(Atom::from_text(&property.name))],
6578            ),
6579            MemberProp::Computed(index) => self.expr(index)?,
6580            MemberProp::Private(_) => {
6581                return Err(SyntaxError::new(
6582                    "private fields are not supported by the compiler yet",
6583                    member.span,
6584                ));
6585            }
6586        }
6587        match op {
6588            AssignOp::Assign => {
6589                // The key is only converted once, by `put_super_value` itself, so a
6590                // computed key's `toString` runs exactly once.
6591                self.expr(value)?;
6592                self.emit(Opcode::Insert4, &[]);
6593                self.emit(Opcode::PutSuperValue, &[]);
6594            }
6595            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6596                let (keep_label, end) = (self.new_label(), self.new_label());
6597                self.emit(Opcode::ToPropkey, &[]);
6598                self.emit(Opcode::Dup3, &[]);
6599                self.emit(Opcode::GetSuperValue, &[]);
6600                self.emit(Opcode::Dup, &[]);
6601                self.emit_logical_test(op);
6602                self.emit_jump(logical_jump(op), keep_label, &[]);
6603                self.emit(Opcode::Drop, &[]);
6604                self.expr(value)?;
6605                self.emit(Opcode::Insert4, &[]);
6606                self.emit(Opcode::PutSuperValue, &[]);
6607                self.emit_jump(Opcode::Goto, end, &[]);
6608                self.place_label(keep_label);
6609                // The prototype and the key are still under the value that was read.
6610                self.emit(Opcode::Nip, &[]);
6611                self.emit(Opcode::Nip, &[]);
6612                self.emit(Opcode::Nip, &[]);
6613                self.place_label(end);
6614            }
6615            _ => {
6616                self.emit(Opcode::ToPropkey, &[]);
6617                self.emit(Opcode::Dup3, &[]);
6618                self.emit(Opcode::GetSuperValue, &[]);
6619                self.expr(value)?;
6620                self.emit(compound_opcode(op), &[]);
6621                self.emit(Opcode::Insert4, &[]);
6622                self.emit(Opcode::PutSuperValue, &[]);
6623            }
6624        }
6625        // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
6626        // is still on the stack when the store finishes, and the expression statement is
6627        // what disposes of it — the same arrangement as `put_field`, reached from the other
6628        // side: there the store consumes the value (`no_value`), here it leaves it
6629        // (`keep` already false, so nothing tells the statement otherwise).
6630        self.state().cur_pos = saved;
6631        Ok(())
6632    }
6633
6634    /// The test a logical assignment applies to the current value.
6635    ///
6636    /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
6637    /// assign, while `0 ||= b` must not.
6638    fn emit_logical_test(&mut self, op: AssignOp) {
6639        if op == AssignOp::Coalesce {
6640            self.emit(Opcode::IsUndefinedOrNull, &[]);
6641        }
6642    }
6643
6644    /// The private name `#name` this use site resolves against.
6645    ///
6646    /// The parser has already rejected a name no enclosing class declares, so a miss here
6647    /// means the compiler lost track of a class scope — which is worth a real error rather
6648    /// than an `unwrap`.
6649    fn private_use(
6650        &self,
6651        binding: &str,
6652        span: Span,
6653    ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
6654        ClassPlan::find(self, binding)
6655            .map(|use_| (use_.kind, use_.setter.clone()))
6656            .ok_or_else(|| {
6657                SyntaxError::new(
6658                    format!("the private name '{binding}' is out of scope here"),
6659                    span,
6660                )
6661            })
6662    }
6663
6664    /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
6665    ///
6666    /// The three readable kinds take three different instructions, because a private name
6667    /// holds three different things — a symbol, a method function, a getter function — and
6668    /// only the first one is a property read at all.
6669    fn private_load(
6670        &mut self,
6671        binding: &str,
6672        kind: PrivateKind,
6673        span: Span,
6674    ) -> Result<(), SyntaxError> {
6675        match kind {
6676            PrivateKind::Field => {
6677                self.emit_var(VarAction::Get, binding);
6678                self.emit(Opcode::GetPrivateField, &[]);
6679            }
6680            PrivateKind::Method => {
6681                self.emit_var(VarAction::Get, binding);
6682                self.emit(Opcode::CheckBrand, &[]);
6683                // `check_brand` reads `obj func` and leaves both; the method itself is what
6684                // `this.#m` evaluates to.
6685                self.emit(Opcode::Nip, &[]);
6686            }
6687            PrivateKind::Getter => {
6688                self.emit_var(VarAction::Get, binding);
6689                self.emit(Opcode::CheckBrand, &[]);
6690                self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6691            }
6692            // `#a` is declared but never filled when only a setter exists, so reading it is
6693            // the same refusal as assigning to a `const`. The reference reports it with the
6694            // generic read-only wording and leaves the better message as a `XXX`.
6695            PrivateKind::Setter => self.emit(
6696                Opcode::ThrowError,
6697                &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
6698            ),
6699        }
6700        let _ = span;
6701        Ok(())
6702    }
6703
6704    /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
6705    fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
6706        match kind {
6707            // A method *is* the callee, so only the check goes in between.
6708            PrivateKind::Method => {
6709                self.emit_var(VarAction::Get, binding);
6710                self.emit(Opcode::CheckBrand, &[]);
6711            }
6712            _ => self.private_load(binding, kind, Span::default())?,
6713        }
6714        Ok(())
6715    }
6716
6717    /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
6718    /// wanted back.
6719    ///
6720    /// A getter/setter pair is a *method call*, not a property store: the reference reads
6721    /// the setter out of its own binding and calls it with the receiver, which is why the
6722    /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
6723    /// keeps the assignment's value for an expression context.
6724    fn private_store(
6725        &mut self,
6726        binding: &str,
6727        kind: PrivateKind,
6728        setter: Option<&str>,
6729    ) -> Result<(), SyntaxError> {
6730        match kind {
6731            PrivateKind::Field => {
6732                self.emit_var(VarAction::Get, binding);
6733                self.emit(Opcode::PutPrivateField, &[]);
6734            }
6735            PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
6736                Some(setter) => {
6737                    self.emit_var(VarAction::Get, setter);
6738                    // `obj func value` -> `value obj func` for the check, and back again for
6739                    // the call, which wants `obj func arg`.
6740                    self.emit(Opcode::Swap, &[]);
6741                    self.emit(Opcode::Rot3r, &[]);
6742                    self.emit(Opcode::CheckBrand, &[]);
6743                    self.emit(Opcode::Rot3l, &[]);
6744                    self.emit(Opcode::CallMethod, &[Op::Int(1)]);
6745                    // The setter's return value is discarded; the assignment's own value is
6746                    // whatever the caller left underneath.
6747                    self.emit(Opcode::Drop, &[]);
6748                }
6749                None => self.emit(
6750                    Opcode::ThrowError,
6751                    &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
6752                ),
6753            },
6754        }
6755        Ok(())
6756    }
6757
6758    fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
6759        let instruction = match (op, prefix) {
6760            (UpdateOp::Increment, true) => Opcode::Inc,
6761            (UpdateOp::Increment, false) => Opcode::PostInc,
6762            (UpdateOp::Decrement, true) => Opcode::Dec,
6763            (UpdateOp::Decrement, false) => Opcode::PostDec,
6764        };
6765        if let ExprKind::Member {
6766            object,
6767            property,
6768            optional: _,
6769        } = &argument.kind
6770        {
6771            // `o.x++` needs the receiver twice, so the last link is read with the
6772            // `get_*2`/`get_*3` form that keeps it, and the update is written back
6773            // with `put_field`/`put_array_el`. The reordering in between is what puts
6774            // the old value below the receiver for a postfix update and the new one
6775            // above it for a prefix one:
6776            //
6777            //   `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
6778            //   `obj val` → `inc`      → `obj new new` → `insert2` → `new obj new`
6779            //
6780            // This mirrors the reference instruction for instruction.
6781            self.expr(object)?;
6782            match property {
6783                MemberProp::Ident(name) => {
6784                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
6785                    self.emit(instruction, &[]);
6786                    self.emit(
6787                        if prefix {
6788                            Opcode::Insert2
6789                        } else {
6790                            Opcode::Perm3
6791                        },
6792                        &[],
6793                    );
6794                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
6795                }
6796                MemberProp::Computed(index) => {
6797                    self.expr(index)?;
6798                    self.emit(Opcode::GetArrayEl3, &[]);
6799                    self.emit(instruction, &[]);
6800                    self.emit(
6801                        if prefix {
6802                            Opcode::Insert3
6803                        } else {
6804                            Opcode::Perm4
6805                        },
6806                        &[],
6807                    );
6808                    self.emit(Opcode::PutArrayEl, &[]);
6809                }
6810                MemberProp::Private(name) => {
6811                    // The receiver is duplicated and the read keeps it, exactly as `get_field2`
6812                    // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
6813                    // `perm3` -> `old obj new` -> store.
6814                    let binding = format!("#{}", name.name);
6815                    let (kind, setter) = self.private_use(&binding, argument.span)?;
6816                    self.emit(Opcode::Dup, &[]);
6817                    self.private_load(&binding, kind, argument.span)?;
6818                    self.emit(instruction, &[]);
6819                    self.emit(
6820                        if prefix {
6821                            Opcode::Insert2
6822                        } else {
6823                            Opcode::Perm3
6824                        },
6825                        &[],
6826                    );
6827                    self.private_store(&binding, kind, setter.as_deref())?;
6828                }
6829            }
6830            return Ok(());
6831        }
6832        let ExprKind::Ident(name) = &argument.kind else {
6833            return Err(SyntaxError::new(
6834                "increment of a non-variable is not supported by the compiler yet",
6835                argument.span,
6836            ));
6837        };
6838        // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
6839        // reference's `inc_loc` folds those three into one, but it does so only in some
6840        // positions (a `for` update and not a bare statement, and never for a lexical
6841        // binding), so emitting it unconditionally would move *away* from its output.
6842        // The instruction is equivalent either way; matching the reference matters more
6843        // than saving two instructions.
6844        let _ = !std::mem::take(&mut self.state().discard_value);
6845        self.emit_var(VarAction::Get, &name.name);
6846        self.emit(instruction, &[]);
6847        if prefix {
6848            self.emit(Opcode::Dup, &[]);
6849        }
6850        self.emit_var(VarAction::Put, &name.name);
6851        Ok(())
6852    }
6853
6854    /// Compile an array literal.
6855    ///
6856    /// The reference splits this into three phases, and the split is load-bearing
6857    /// rather than an optimisation detail:
6858    ///
6859    /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
6860    ///    the array in one instruction.
6861    /// 2. **Everything up to the first spread** is appended with explicit indices
6862    ///    (`define_field <index>`), because a hole has no element to pass to
6863    ///    `array_from`. A hole here is what makes `length` need fixing up: an
6864    ///    explicit index does not extend the array the way a pushed element does.
6865    /// 3. **From the first spread on** the index lives on the stack, so `append` and
6866    ///    `define_array_el` can consume it and `inc` advances it.
6867    ///
6868    /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
6869    /// forces phase 2, and `[...a]` forces phase 3.
6870    fn array_literal(
6871        &mut self,
6872        elements: &[Option<ArrayElement>],
6873        span: Span,
6874    ) -> Result<(), SyntaxError> {
6875        let _ = span;
6876        let mut index: u32 = 0;
6877        let mut cursor = 0usize;
6878
6879        // Phase 1: a leading run of plain elements, at most 32 of them.
6880        while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
6881            if index >= 32 {
6882                break;
6883            }
6884            self.expr(element)?;
6885            index += 1;
6886            cursor += 1;
6887        }
6888        self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
6889
6890        // Phase 2: explicit indices, up to the first spread.
6891        let mut need_length = false;
6892        while let Some(element) = elements.get(cursor) {
6893            if matches!(element, Some(ArrayElement::Spread(_))) {
6894                break;
6895            }
6896            need_length = true;
6897            if let Some(ArrayElement::Expr(expression)) = element {
6898                self.expr(expression)?;
6899                self.emit_define_index(index);
6900                need_length = false;
6901            }
6902            index += 1;
6903            cursor += 1;
6904        }
6905
6906        if cursor >= elements.len() {
6907            if need_length {
6908                // `define_field` cannot set `length`, which is not configurable.
6909                self.emit(Opcode::Dup, &[]);
6910                self.push_number(index as f64);
6911                self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
6912            }
6913            return Ok(());
6914        }
6915
6916        // Phase 3: the index moves onto the stack for the spreading tail.
6917        //
6918        // `need_length` deliberately carries over from phase 2: a hole before the
6919        // first spread still has to be reflected in `length`, and only the final
6920        // check can do it because the array is not finished until the tail is
6921        // appended.
6922        self.push_number(index as f64);
6923        while let Some(element) = elements.get(cursor) {
6924            match element {
6925                Some(ArrayElement::Spread(expression)) => {
6926                    // `append` copies an iterable and leaves the next index behind,
6927                    // so no `inc` is needed here.
6928                    self.expr(spread_argument(expression))?;
6929                    self.emit(Opcode::Append, &[]);
6930                }
6931                None | Some(ArrayElement::Expr(_)) => {
6932                    need_length = true;
6933                    if let Some(ArrayElement::Expr(expression)) = element {
6934                        self.expr(expression)?;
6935                        self.emit(Opcode::DefineArrayEl, &[]);
6936                        need_length = false;
6937                    }
6938                    self.emit(Opcode::Inc, &[]);
6939                }
6940            }
6941            cursor += 1;
6942        }
6943        if need_length {
6944            self.emit(Opcode::Dup1, &[]);
6945            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
6946        } else {
6947            self.emit(Opcode::Drop, &[]);
6948        }
6949        Ok(())
6950    }
6951
6952    /// `define_field` with an array-index atom, which is how phase 2 stores elements.
6953    fn emit_define_index(&mut self, index: u32) {
6954        self.emit(
6955            Opcode::DefineField,
6956            &[Op::Atom(Atom::from_text(&index.to_string()))],
6957        );
6958    }
6959
6960    // -- functions ---------------------------------------------------------
6961
6962    fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
6963        self.compile_function_with_name(func, false)
6964    }
6965
6966    /// Compile a function, recording whether it is a *named function expression*.
6967    ///
6968    /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
6969    /// must not leak outside. The reference does that by declaring `g` as a local of
6970    /// the function itself and initialising it with `special_object 2` (the current
6971    /// function), which is why this has to be known at compile time.
6972    fn compile_function_with_name(
6973        &mut self,
6974        func: &ast::Function,
6975        is_expression: bool,
6976    ) -> Result<CompiledFunction, SyntaxError> {
6977        let kind = match (func.is_generator, func.is_async) {
6978            (false, false) => FunctionKind::Normal,
6979            (true, false) => FunctionKind::Generator,
6980            (false, true) => FunctionKind::Async,
6981            (true, true) => FunctionKind::AsyncGenerator,
6982        };
6983        let mut state = FnState::new(
6984            func.name
6985                .as_ref()
6986                .map(|n| n.name.clone())
6987                .unwrap_or_default(),
6988            kind,
6989        );
6990        // The function's own mode, recorded by the parser. Inheriting the enclosing
6991        // function's instead let a nested `"use strict"` directive be ignored, so the
6992        // body ran with sloppy `this`, sloppy `arguments` and no const checks.
6993        state.strict = func.strict;
6994        // A function defined inside a `with` block keeps seeing that object: the guard
6995        // chain names the enclosing `<with>` locals, which resolve outward into closure
6996        // variables exactly like any other captured binding.
6997        state.with_names = self.cur().with_names.clone();
6998        state.is_arrow = func.is_arrow;
6999        state.created_in_block = self.cur().current_block;
7000        // A default anywhere in the parameter list is what gives the function two
7001        // variable environments. The reference decides this the same way: it scans the
7002        // parenthesis for a top-level `=`, so a destructured name without a default
7003        // stays a plain function-scope binding.
7004        state.in_params = false;
7005        // The reference scans the parenthesis for *any* `=`, including one nested inside
7006        // a pattern, so `function f({a = 1})` has parameter expressions even though the
7007        // parameter itself carries no initialiser.
7008        state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
7009        // A function born inside a parameter list inherits the prohibition: it must not
7010        // see the body bindings of the function it was created in.
7011        state.created_in_params = self.cur().in_params || self.cur().created_in_params;
7012        // A class constructor knows what it is only because the class told it.
7013        if let Some(kind) = self.cur().class_ctor_pending {
7014            state.ctor_kind = kind;
7015        }
7016        // A named *expression* binds its own name; a declaration's name is already
7017        // bound in the enclosing scope.
7018        state.self_name = if is_expression && !func.is_arrow {
7019            func.name.as_ref().map(|n| n.name.clone())
7020        } else {
7021            None
7022        };
7023        state.line = func.span.start.line;
7024        state.column = func.span.start.column;
7025        // A function body has no hidden `<ret>` local; the value comes back on
7026        // the stack. Only a script keeps one.
7027        // Parameters are positional, so even a pattern occupies one argument slot. A
7028        // simple name is that slot itself; anything else (a pattern, a default, a rest
7029        // parameter) takes an anonymous slot and is unpicked into locals at the top of
7030        // the body, which is the only way one argument can bind several names.
7031        let mut prologue: Vec<(usize, Pattern)> = Vec::new();
7032        // `.length` stops at the first parameter that can be substituted: a default
7033        // fills a missing argument in, and a rest parameter absorbs the rest.
7034        let mut defined_args = func.params.len() as u32;
7035        for (index, param) in func.params.iter().enumerate() {
7036            match simple_parameter(param) {
7037                Some(name) => state.args.push(VarDef::var(name.name.clone())),
7038                None => {
7039                    state.args.push(VarDef::var(ANONYMOUS_BINDING));
7040                    prologue.push((index, param.clone()));
7041                }
7042            }
7043        }
7044        // A default anywhere before the end also ends the count, which the loop above
7045        // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
7046        for (position, param) in func.params.iter().enumerate() {
7047            if matches!(
7048                param.kind,
7049                PatternKind::Assign { .. } | PatternKind::Rest(_)
7050            ) {
7051                defined_args = position as u32;
7052                break;
7053            }
7054        }
7055        state.defined_args = defined_args;
7056        state.param_prologue = prologue;
7057        let depth = self.stack.len();
7058        self.stack.push(state);
7059        let result = self.compile_function_body(func);
7060        if result.is_err() {
7061            // A failed compile must not leave its `FnState` behind. Every caller
7062            // reads `self.state()` as "the function being compiled", so a leftover
7063            // frame silently retargets all later bookkeeping at a dead function.
7064            self.stack.truncate(depth);
7065        }
7066        result
7067    }
7068
7069    /// The body of a function, with its frame already pushed.
7070    fn compile_function_body(
7071        &mut self,
7072        func: &ast::Function,
7073    ) -> Result<CompiledFunction, SyntaxError> {
7074        let body_key = func.params_span.end.offset as u64;
7075        // Where the body begins, in source order. The runtime needs this to tell a
7076        // closure created by a default expression from one the body creates — the two see
7077        // different variable environments — and a bytecode offset would not survive the
7078        // instruction shuffling that building the frame does. Positions are in source
7079        // order, so a comparison answers it.
7080        self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
7081        self.push_block(body_key, NO_PARENT);
7082        self.state().body_block = body_key;
7083        // An arrow with an expression body has no statements; the expression is
7084        // its `return`. Building the statement here keeps one code path below, and
7085        // matters for correctness beyond convenience: returning early with the new
7086        // `FnState` still on the stack would leave the compiler looking at the
7087        // wrong function, which surfaces as an unrelated underflow later.
7088        let concise = match &func.body {
7089            js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
7090                StmtKind::Return(Some(Box::new((**value).clone()))),
7091                value.span,
7092            )),
7093            js_parse::ast::FunctionBody::Block(_) => None,
7094        };
7095        let body: &[Stmt] = match &concise {
7096            Some(stmt) => std::slice::from_ref(stmt),
7097            None => func
7098                .body
7099                .statements()
7100                .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
7101        };
7102        let prologue = std::mem::take(&mut self.state().param_prologue);
7103        let has_param_scope = self.cur().has_parameter_expressions;
7104        // The parameter scope's own bindings, declared in source order.
7105        //
7106        // With parameter expressions the list gets a variable environment of its own, and
7107        // every name it binds is a `let` there. That is what puts the *list* in the
7108        // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
7109        // and `function f(x = y, y){}` does the same, where a single shared environment
7110        // would answer `undefined` to both.
7111        if has_param_scope {
7112            let mut declared: Vec<String> = Vec::new();
7113            for param in &func.params {
7114                let mut names = Vec::new();
7115                param.bound_names(&mut names);
7116                for name in names {
7117                    if declared.contains(&name.name) {
7118                        continue;
7119                    }
7120                    declared.push(name.name.clone());
7121                    self.declare_param_binding(&name.name);
7122                }
7123            }
7124        }
7125        // A pattern parameter binds its names as function-scope locals, so they have to
7126        // exist — and be unpicked from the argument — before the body runs. With a
7127        // parameter scope these are the *second* environment: the pattern fills the
7128        // parameter's copy, and the body's binding is filled from it afterwards.
7129        for (_, pattern) in &prologue {
7130            let mut names = Vec::new();
7131            pattern.bound_names(&mut names);
7132            for name in names {
7133                self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
7134            }
7135        }
7136        self.hoist(body, body_key)?;
7137        // A constructor's prologue is not a parameter unpacking but the `this` binding:
7138        // a base constructor takes the receiver, a derived one starts in the dead zone
7139        // because only `super()` may produce it.
7140        match self.cur().ctor_kind {
7141            CtorKind::None => {}
7142            CtorKind::Base => {
7143                self.begin_this_local();
7144                self.emit(Opcode::CheckCtor, &[]);
7145                // Instance fields are installed at the top of a base constructor's body,
7146                // before any statement — `class C { x = 1; constructor() { this.x } }` sees
7147                // `1`. This used to be emitted at the *tail*, which made every field read
7148                // `undefined` inside the constructor that declared it.
7149                self.call_field_initialiser();
7150            }
7151            CtorKind::Derived => {
7152                self.declare("this", VarDef::lexical("this"));
7153                let slot = self.cur().vars.len() as u32 - 1;
7154                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7155                self.emit(Opcode::CheckCtor, &[]);
7156            }
7157        }
7158        // Entering the parameter list: everything it binds starts in the dead zone.
7159        // The order is the reference's — it walks the scope chain, which is prepended, so
7160        // the bindings come out newest first.
7161        for name in self.param_binding_names().into_iter().rev() {
7162            if let Some(slot) = self.param_binding_slot(&name) {
7163                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7164            }
7165        }
7166        // The whole parameter list is one scope, and nothing in the body exists yet, so
7167        // every name it mentions resolves against the parameter bindings and outward.
7168        self.state().in_params = has_param_scope;
7169        for (index, param) in func.params.iter().enumerate() {
7170            if let Some(pattern) = prologue_pattern(&prologue, index) {
7171                // A destructuring parameter *initialises* its bindings: with a parameter
7172                // scope they are the list's own `let`s, which is why the stores skip the
7173                // dead-zone check, and why the reference reads their properties with
7174                // `get_field2` — a `let` needs no reference.
7175                let kind = if has_param_scope {
7176                    VarDeclKind::Let
7177                } else {
7178                    VarDeclKind::Var
7179                };
7180                match &pattern.kind {
7181                    // `...rest` collects what is left rather than reading one slot.
7182                    PatternKind::Rest(inner) => {
7183                        self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7184                        self.destructure(inner, Some(kind))?;
7185                    }
7186                    _ => {
7187                        self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7188                        self.destructure(pattern, Some(kind))?;
7189                    }
7190                }
7191                continue;
7192            }
7193            // A plain name binds straight from its argument slot. With a parameter scope
7194            // the slot is also copied into the parameter binding, which is what a later
7195            // default (or a closure made among the defaults) reads.
7196            let Some(name) = simple_parameter(param) else {
7197                continue;
7198            };
7199            let target = self.param_binding_slot(&name.name);
7200            if matches!(param.kind, PatternKind::Rest(_)) {
7201                self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7202                if let Some(slot) = target {
7203                    self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
7204                }
7205                // `put_arg` rather than `set_arg`: the array is the last thing on the
7206                // stack and nothing keeps it. Named by hand because a name in the
7207                // parameter list resolves to the parameter binding, and this store has to
7208                // reach the *argument* — that is what the body reads.
7209                self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
7210                continue;
7211            }
7212            if let PatternKind::Assign { default, .. } = &param.kind {
7213                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7214                let has_value = self.new_label();
7215                self.emit(Opcode::Dup, &[]);
7216                self.emit(Opcode::IsUndefined, &[]);
7217                self.emit_jump(Opcode::IfFalse, has_value, &[]);
7218                self.emit(Opcode::Drop, &[]);
7219                self.expr(default)?;
7220                self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
7221                // The argument slot keeps the substituted value, because the *body* reads
7222                // the slot rather than the parameter binding — so this store is named
7223                // explicitly, like the rest parameter's.
7224                self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7225                self.place_label(has_value);
7226                if let Some(slot) = target {
7227                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7228                }
7229                continue;
7230            }
7231            if let Some(slot) = target {
7232                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7233                self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7234            }
7235        }
7236        // Copy the parameter scope into the body. A plain parameter needs nothing: the
7237        // body reads its argument slot, and the list kept the two in step. A name a
7238        // pattern bound has no argument slot of its own, so the body gets a `var` filled
7239        // from the parameter's copy — and *that* is why an assignment inside a default
7240        // does not reach the body.
7241        if has_param_scope {
7242            for (_, pattern) in &prologue {
7243                let mut names = Vec::new();
7244                pattern.bound_names(&mut names);
7245                for name in names {
7246                    let Some(slot) = self.param_binding_slot(&name.name) else {
7247                        continue;
7248                    };
7249                    let Some(body) = self.body_var_slot(&name.name) else {
7250                        continue;
7251                    };
7252                    self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
7253                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
7254                }
7255            }
7256        }
7257        // The parameter list is over; from here on a direct `eval` belongs to the body.
7258        self.state().in_params = false;
7259        // Entering the body's own scope comes *after* the parameter list: the body's
7260        // `let`s are not in existence while the defaults run, and the reference emits
7261        // their `set_loc_uninitialized` only once the parameters are bound.
7262        self.emit_scope_enter(body_key);
7263        // A generator starts suspended: `initial_yield` parks the body so that creating one
7264        // runs no body code until the first `next()`.
7265        //
7266        // It comes *after* the parameter unpacking, not before, because a parameter
7267        // initialiser is not body code — `function* g(a = sideEffect())` must run
7268        // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
7269        // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
7270        // until the first `next()` and 29 test262 cases that check for a synchronous throw
7271        // saw none at all.
7272        //
7273        // An async function does **not** get one. Its body runs synchronously up to the
7274        // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
7275        // before its caller's next statement — so an `initial_yield` here would park the
7276        // body before it started, which is not fixable at run time: the suspension looks
7277        // exactly like a real `await`.
7278        if self.cur().kind.is_generator() {
7279            self.emit(Opcode::InitialYield, &[]);
7280        }
7281        // Through `stmts`: the body is a block, and a `using` declaration in it is a
7282        // disposal region.
7283        self.stmts(body)?;
7284        // The implicit return only exists if control can actually get here: an
7285        // infinite loop never falls off the end.
7286        if self.end_is_reachable() {
7287            if self.cur().is_suspending() {
7288                // Falling off the end finishes the generator with `undefined`, and the
7289                // value is what tells the resume machinery "completed" rather than
7290                // "suspended".
7291                self.emit(Opcode::Undefined, &[]);
7292                self.emit(Opcode::ReturnAsync, &[]);
7293            } else {
7294                self.emit_class_constructor_tail();
7295            }
7296        }
7297        // Resolution runs while this function is still on the stack: capturing a
7298        // variable from an enclosing function means reaching into that
7299        // function's state, which requires the whole chain to be present.
7300        Ok(self.finish_current())
7301    }
7302
7303    /// Put every binding of a function that contains a direct `eval` into a cell.
7304    ///
7305    /// A direct eval can name any binding in scope, and any closure it creates has to
7306    /// keep sharing that binding after the function returns — `for (let i …)
7307    /// eval("push(() => i)")` collects one closure per iteration and each must read its
7308    /// own `i`. A copy in a side table would freeze the value, so the binding has to be
7309    /// a cell. Doing this unconditionally for such functions is the cheap, honest
7310    /// answer: the alternative is knowing at compile time which names a string will
7311    /// mention.
7312    fn capture_everything_for_eval(&mut self) {
7313        let current = self.stack.len() - 1;
7314        if !self.stack[current].has_direct_eval {
7315            return;
7316        }
7317        for arg in &mut self.stack[current].args {
7318            arg.is_captured = true;
7319        }
7320        for var in &mut self.stack[current].vars {
7321            var.is_captured = true;
7322        }
7323    }
7324
7325    /// Whether the current position in the instruction stream can be reached.
7326    ///
7327    /// A walk over the control-flow graph, using labels as instruction indices.
7328    /// The reference does the same thing to decide whether an implicit
7329    /// `return_undef` is needed.
7330    fn end_is_reachable(&self) -> bool {
7331        let state = self.cur();
7332        reachable_instructions(state, state.insns.len())[state.insns.len()]
7333    }
7334
7335    /// Resolve and assemble the function on top of the compiler stack, then pop
7336    /// it.
7337    fn finish_current(&mut self) -> CompiledFunction {
7338        self.provide_param_arguments();
7339        self.provide_arguments();
7340        self.provide_this_local();
7341        self.provide_new_target_local();
7342        self.provide_home_object_local();
7343        self.provide_active_func_local();
7344        self.provide_self_name();
7345        self.materialize_eval_sites();
7346        self.capture_everything_for_eval();
7347        let (mut resolved, resolved_pos) = resolve(&mut self.stack);
7348        // Captured bindings need a reference cell; the count goes in the header so
7349        // the runtime knows how many cells to allocate on entry.
7350        let current = self.stack.len() - 1;
7351        let captured = self.stack[current]
7352            .args
7353            .iter()
7354            .filter(|a| a.is_captured)
7355            .count()
7356            + self.stack[current]
7357                .vars
7358                .iter()
7359                .filter(|v| v.is_captured)
7360                .count();
7361        self.stack[current].var_ref_count = captured as u32;
7362        // The scope chain is only final now that every binding is known.
7363        rebuild_scope_chain(&mut self.stack[current]);
7364        let (code, stack_size, positions) =
7365            assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
7366        let _ = &mut resolved;
7367        let mut state = self.stack.pop().expect("a function is being compiled");
7368        CompiledFunction {
7369            name: state.name,
7370            kind: state.kind,
7371            strict: state.strict,
7372            is_arrow: state.is_arrow,
7373            has_parameter_expressions: state.has_parameter_expressions,
7374            body_start: state.body_start,
7375            args: state.args,
7376            defined_args: state.defined_args,
7377            vars: state.vars,
7378            closure_vars: state.closure_vars,
7379            cpool: state.cpool,
7380            atoms: state.atoms,
7381            code,
7382            stack_size,
7383            var_ref_count: state.var_ref_count,
7384            positions,
7385            source: None,
7386            line: state.line,
7387            column: state.column,
7388            filename: None,
7389            eval_sites: state.eval_sites,
7390            module: state.module.take().map(Box::new),
7391        }
7392    }
7393}
7394
7395/// Assign each binding a scope level and rebuild the scope chains.
7396///
7397/// Levels are numbered in the order the blocks appear, with 0 reserved for the
7398/// function scope where `var` and hoisted functions live. Every binding outside
7399/// level 0 gets a `scope_next` link to the next binding visible from the same
7400/// point, so walking a block's chain enumerates exactly the bindings live there.
7401///
7402/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
7403/// point at `b`, which is declared later in the source but earlier in the chain.
7404fn rebuild_scope_chain(state: &mut FnState) {
7405    // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
7406    // real block that happens to start at offset zero keeps its own level instead of
7407    // being merged into the function scope.
7408    let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
7409    for block in &state.blocks {
7410        if !levels.contains(&block.key) {
7411            levels.push(block.key);
7412        }
7413    }
7414    let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
7415    let parent_level = |level: usize| -> usize {
7416        if level == 0 {
7417            return 0;
7418        }
7419        let key = levels[level];
7420        let parent = state
7421            .blocks
7422            .iter()
7423            .find(|b| b.key == key)
7424            .map(|b| b.parent)
7425            .unwrap_or(FUNCTION_SCOPE);
7426        level_of(parent)
7427    };
7428
7429    // Own bindings per level, in declaration order.
7430    let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
7431    let keys: Vec<u64> = (0..state.vars.len())
7432        .map(|index| {
7433            state
7434                .var_block
7435                .get(index)
7436                .copied()
7437                .unwrap_or(FUNCTION_SCOPE)
7438        })
7439        .collect();
7440    for (index, key) in keys.into_iter().enumerate() {
7441        // The parameter scope is not a block: it is a level of its own with no parent,
7442        // assigned below. Letting it land in level 0 would chain the body's bindings onto
7443        // it, which the reference does not do — the two environments are siblings.
7444        if key == PARAM_SCOPE {
7445            continue;
7446        }
7447        let level = level_of(key);
7448        state.vars[index].scope_level = level as u32;
7449        // A `catch` parameter is part of the runtime scope chain even though it is
7450        // not lexical: the handler's own bindings chain on to it, which is why the
7451        // reference prints `let y [next:1]` with `e` at 1.
7452        if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
7453        {
7454            own[level].push(index);
7455        }
7456    }
7457
7458    // A scope's chain is its own bindings in reverse declaration order followed
7459    // by the enclosing scope's chain.
7460    let mut head = vec![-1i32; levels.len()];
7461    for level in 0..levels.len() {
7462        let inherited = if level == 0 {
7463            -1
7464        } else {
7465            head[parent_level(level)]
7466        };
7467        let chain: Vec<usize> = own[level].iter().rev().copied().collect();
7468        head[level] = chain.first().map_or(inherited, |first| *first as i32);
7469        for (position, &index) in chain.iter().enumerate() {
7470            let next = chain
7471                .get(position + 1)
7472                .map_or(inherited, |next| *next as i32);
7473            state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
7474        }
7475    }
7476    state.block_heads = head;
7477
7478    // The parameter list is a scope of its own, and it has no parent: the reference pops
7479    // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
7480    // the `-1` a block uses. A level past every real block keeps it out of the walk above
7481    // — nothing but the dump reads it — and the links run newest-to-oldest through the
7482    // bindings themselves, which is the order `set_loc_uninitialized` walks.
7483    let param_level = levels.len() as u32;
7484    let mut previous: Option<usize> = None;
7485    for index in 0..state.vars.len() {
7486        if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
7487        {
7488            continue;
7489        }
7490        state.vars[index].scope_level = param_level;
7491        state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
7492        previous = Some(index);
7493    }
7494}
7495
7496/// This is where names become slots and where the temporal dead zone shows up in
7497/// the instruction stream: a read of a `let`/`const` binding compiles to
7498/// `get_loc_check`, which throws if the binding is still uninitialised.
7499///
7500/// The peephole pass from the reference implementation is applied at the end,
7501/// for the same reason it is applied to resolved bytecode there: the patterns are
7502/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
7503/// resolution. Deleted instructions stay in the list as `None` so that label
7504/// indices remain valid; [`Assembler`] maps them to byte offsets.
7505/// A resolved instruction and the source position it came from.
7506type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
7507
7508/// A resolved instruction paired with its position, which is what `assemble` consumes.
7509type PositionedInsn = (Opcode, Vec<Op>);
7510
7511fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
7512    let current = stack.len() - 1;
7513    // Dead-code elimination, on the symbolic form where labels are still
7514    // instruction indices. A `break` inside a loop leaves the trailing `goto`
7515    // unreachable, and a `return` leaves everything after it unreachable; the
7516    // reference drops both. Doing it here means the emitter never has to think
7517    // about reachability.
7518    strip_empty_gosubs(stack, current);
7519    eliminate_dead_code(stack, current);
7520    let insns = std::mem::take(&mut stack[current].insns);
7521    // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
7522    // `insns`, and every arm below pushes exactly one instruction, so the positions
7523    // stay aligned with `out`.
7524    let positions = std::mem::take(&mut stack[current].insn_pos);
7525    let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
7526    let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
7527    for (index, insn) in insns.iter().enumerate() {
7528        let pos = positions.get(index).copied().flatten();
7529        out_pos.push(pos);
7530        match insn {
7531            Insn::Fixed { op, operands } => {
7532                let operands = operands
7533                    .iter()
7534                    .map(|operand| match operand {
7535                        Op::Atom(atom) => {
7536                            Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
7537                        }
7538                        other => other.clone(),
7539                    })
7540                    .collect();
7541                out.push(Some((*op, operands)));
7542            }
7543            Insn::Var {
7544                action,
7545                name,
7546                block,
7547                in_params,
7548            } => {
7549                // Both reads and writes in the parameter list address the parameter
7550                // scope. That is what puts the list in the temporal dead zone — a read of
7551                // a later parameter is `get_loc_check` on an uninitialised slot — and it
7552                // is also what keeps an assignment made inside a default away from the
7553                // body, which sees a separate environment.
7554                let slot = resolve_slot(stack, current, name, *block, *in_params);
7555                // A store to the name of a named function expression is special: the
7556                // reference drops it in sloppy mode and throws in strict mode, because
7557                // the binding is immutable but only *checked* when the body is strict.
7558                // The same rule applies when the name is reached through a closure:
7559                // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
7560                // the store in the arrow too, not just in the function that owns the
7561                // binding. Reaching the owner means walking the chain of closure
7562                // entries, which is what `self_name_binding` does.
7563                let self_name = matches!(action, VarAction::Put | VarAction::Set)
7564                    .then(|| {
7565                        // A local of this function is the common case and needs no
7566                        // chain walk; only an access that resolves elsewhere can be
7567                        // pointing at an enclosing function's name binding.
7568                        if let Slot::Loc(index) = slot {
7569                            stack[current]
7570                                .vars
7571                                .get(index as usize)
7572                                .filter(|var| var.kind == VarKind::FunctionName)
7573                                .map(|var| var.is_const)
7574                        } else {
7575                            self_name_binding(stack, current, name, *block)
7576                        }
7577                    })
7578                    .flatten();
7579                if let Some(is_const) = self_name {
7580                    out.push(Some(if is_const {
7581                        (
7582                            Opcode::ThrowError,
7583                            vec![
7584                                Op::AtomId(intern_atom(&mut stack[current], name)),
7585                                Op::Int(0),
7586                            ],
7587                        )
7588                    } else {
7589                        (Opcode::Drop, Vec::new())
7590                    }));
7591                    continue;
7592                }
7593                out.push(Some(variable_instruction(stack, current, *action, slot)));
7594            }
7595            Insn::CloseCaptured { name, block } => {
7596                // The block matters: a loop variable is scoped to the `for` head's own
7597                // block, so resolving it against block 0 would miss it entirely and
7598                // silently emit nothing.
7599                let slot = resolve_slot(stack, current, name, *block, false);
7600                // Only a local with a reference cell has anything to close. A global
7601                // or a never-captured local resolves to no instruction at all, which
7602                // keeps the bytecode identical to the reference's.
7603                if let Slot::Loc(index) = slot
7604                    && stack[current]
7605                        .vars
7606                        .get(index as usize)
7607                        .is_some_and(|v| v.is_captured)
7608                {
7609                    out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
7610                } else {
7611                    out.push(None);
7612                }
7613            }
7614            Insn::DeleteVar { name } => {
7615                // A binding — a local, an argument, or a declared global — cannot be
7616                // deleted, and the reference encodes that as a constant `push_false`.
7617                // Only an implicit global needs the runtime lookup.
7618                if matches!(
7619                    resolve_slot(stack, current, name, 0, false),
7620                    Slot::Global(_)
7621                ) {
7622                    let atom = intern_atom(&mut stack[current], name);
7623                    out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
7624                } else {
7625                    out.push(Some((Opcode::PushFalse, Vec::new())));
7626                }
7627            }
7628            Insn::Dead => out.push(None),
7629        }
7630    }
7631    // Which label (if any) sits on each instruction, so the jump patterns can
7632    // tell whether they would cross a jump target.
7633    let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
7634    for (id, placed) in stack[current].labels.iter().enumerate() {
7635        if let Some(index) = *placed
7636            && index < label_at.len()
7637            && label_at[index].is_none()
7638        {
7639            label_at[index] = Some(id as u32);
7640        }
7641    }
7642    if std::env::var_os("QJS_DEBUG").is_some() {
7643        eprintln!("--- peephole entry ---");
7644        for (i, e) in out.iter().enumerate() {
7645            eprintln!("{i}: {e:?}");
7646        }
7647        eprintln!("label_at: {label_at:?}");
7648    }
7649    peephole(&mut out, &label_at, &stack[current].labels);
7650    (out, out_pos)
7651}
7652
7653/// Find where `name` lives, capturing it in an enclosing function when needed.
7654///
7655/// The search runs outward through the enclosing functions' states, which are
7656/// still on the compiler stack while a nested function is resolved. Finding the
7657/// name in an enclosing function is what creates a closure reference, and every
7658/// function in between has to forward it — a function can only reach its own
7659/// parent's frame.
7660///
7661/// A name declared nowhere is a global. The reference does *not* look it up by
7662/// name from the inner function: the top-level function gets one `[global]`
7663/// entry and every nested function gets a `[global_ref<n>]` pointing at its
7664/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
7665/// rather than `[global]`.
7666/// The lexical blocks enclosing `block`, innermost first.
7667fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
7668    let mut chain = Vec::new();
7669    let mut current = Some(block);
7670    while let Some(key) = current {
7671        // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
7672        // explicitly (rather than on "no block with this key") is what keeps a block
7673        // that happens to sit at offset zero from being mistaken for the terminator.
7674        if key == NO_PARENT || chain.contains(&key) {
7675            break;
7676        }
7677        chain.push(key);
7678        current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
7679    }
7680    chain
7681}
7682
7683/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
7684///
7685/// The binding may be several functions away: an arrow nested in `function myfunc`
7686/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
7687/// means following `Ref` entries down and then reading the owning function's var table.
7688fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
7689    let state = stack.get(current)?;
7690    // A parameter shadows everything and is never a function-expression name.
7691    if state.args.iter().any(|arg| arg.name == name) {
7692        return None;
7693    }
7694    // A local of this very function: the answer is in its var table.
7695    if let Some(index) = local_slot_index(state, name, block) {
7696        let var = state.vars.get(index)?;
7697        return (var.kind == VarKind::FunctionName).then_some(var.is_const);
7698    }
7699    // Otherwise the name lives further out, and the closure entry says how to get
7700    // there. `Local` names the owner's slot directly; `Ref` names the next level's
7701    // closure entry, so the walk continues downwards.
7702    let mut level = current;
7703    let mut index = state
7704        .closure_vars
7705        .iter()
7706        .position(|closure| closure.name == name)?;
7707    loop {
7708        let state = stack.get(level)?;
7709        let closure = state.closure_vars.get(index)?;
7710        match closure.closure_type {
7711            ClosureType::Local => {
7712                let owner = stack.get(level.checked_sub(1)?)?;
7713                let var = owner.vars.get(closure.var_idx as usize)?;
7714                return (var.kind == VarKind::FunctionName).then_some(var.is_const);
7715            }
7716            ClosureType::Arg => return None,
7717            ClosureType::Ref => {
7718                level -= 1;
7719                index = closure.var_idx as usize;
7720            }
7721            // A global is never a function-expression name.
7722            ClosureType::Global
7723            | ClosureType::GlobalDecl
7724            | ClosureType::GlobalRef
7725            | ClosureType::ModuleDecl
7726            | ClosureType::ModuleImport => return None,
7727        }
7728    }
7729}
7730
7731/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
7732fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
7733    block_chain(state, block).into_iter().find_map(|scope| {
7734        state.vars.iter().enumerate().find_map(|(index, var)| {
7735            (var.name == name && state.var_block.get(index).copied() == Some(scope))
7736                .then_some(index)
7737        })
7738    })
7739}
7740
7741/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
7742fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
7743    if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
7744        var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
7745    }) {
7746        return index as u32;
7747    }
7748    state.var_block.push(PARAM_SCOPE);
7749    state.vars.push(VarDef::var(name));
7750    state.vars.len() as u32 - 1
7751}
7752
7753/// The name a parameter binds straight from its argument slot, if it has one.
7754///
7755/// A plain name does — with or without a default, and with or without `...`. Everything
7756/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
7757/// reference names the argument in the first case and leaves it `<null>` in the second,
7758/// so both the dump and the closures that capture the argument depend on this.
7759fn simple_parameter(param: &Pattern) -> Option<&Ident> {
7760    match &param.kind {
7761        PatternKind::Ident(name) => Some(name),
7762        PatternKind::Assign { target, .. } => match &target.kind {
7763            PatternKind::Ident(name) => Some(name),
7764            _ => None,
7765        },
7766        PatternKind::Rest(inner) => match &inner.kind {
7767            PatternKind::Ident(name) => Some(name),
7768            _ => None,
7769        },
7770        _ => None,
7771    }
7772}
7773
7774/// The pattern a parameter list has to unpick, if `index` is one of them.
7775fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
7776    prologue
7777        .iter()
7778        .find(|(at, _)| *at == index)
7779        .map(|(_, pattern)| pattern)
7780}
7781
7782/// Whether a parameter pattern contains a default anywhere, at any depth.
7783///
7784/// The reference decides "this function has parameter expressions" by scanning the
7785/// parenthesis for a top-level `=`, which a default buried in a pattern still counts as —
7786/// `function f({a = 1})` has a parameter scope just like `function f(a = 1)`.
7787fn pattern_has_default(pattern: &Pattern) -> bool {
7788    match &pattern.kind {
7789        PatternKind::Assign { .. } => true,
7790        PatternKind::Rest(inner) => pattern_has_default(inner),
7791        PatternKind::Array { elements, rest } => {
7792            elements.iter().flatten().any(element_has_default)
7793                || rest.as_deref().is_some_and(rest_has_default)
7794        }
7795        PatternKind::Object { properties, rest } => {
7796            properties.iter().flatten().any(element_has_default)
7797                || rest.as_deref().is_some_and(rest_has_default)
7798        }
7799        _ => false,
7800    }
7801}
7802
7803fn element_has_default(element: &PatternElement) -> bool {
7804    match element {
7805        PatternElement::Pattern(pattern) => pattern_has_default(pattern),
7806        PatternElement::Property { value, .. } => pattern_has_default(value),
7807    }
7808}
7809
7810fn rest_has_default(rest: &RestElement) -> bool {
7811    match rest {
7812        RestElement::Pattern(pattern) => pattern_has_default(pattern),
7813        RestElement::Member(_) => false,
7814    }
7815}
7816
7817/// Whether a function-scope binding is visible to the parameter list.
7818///
7819/// The parameter list runs before the body, so the body's `var`s and function
7820/// declarations do not exist yet — a name that only the body declares has to resolve
7821/// outward instead. What *does* exist by then is the compiler's own prologue: the
7822/// self-name of a named function expression (bound by `special_object 2` before anything
7823/// else), `this` and `new.target`. Those stay visible, which is what makes
7824/// `function f(a = this)` and `var f = function f(a = f)` work.
7825///
7826/// `arguments` is handled separately, as a binding of the parameter scope itself: with
7827/// parameter expressions the reference creates two of them, and the one the parameter
7828/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
7829fn visible_in_params(var: &VarDef) -> bool {
7830    var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
7831}
7832
7833fn resolve_slot(
7834    stack: &mut [FnState],
7835    current: usize,
7836    name: &str,
7837    block: u64,
7838    in_params: bool,
7839) -> Slot {
7840    // The parameter list's own bindings. They are consulted first because they shadow
7841    // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
7842    // `a` in the parameter scope, so a closure made there reads the parameter even after
7843    // the body assigns to its own `a`.
7844    if in_params
7845        && let Some(index) = stack[current]
7846            .vars
7847            .iter()
7848            .enumerate()
7849            .position(|(index, var)| {
7850                var.name == name
7851                    && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
7852            })
7853    {
7854        return Slot::Loc(index as u32);
7855    }
7856    // A name can be bound more than once: two `catch` parameters in nested
7857    // handlers are two slots. The binding that wins is the one whose scope encloses
7858    // the access, and among those the innermost — so the blocks are walked outward
7859    // and the first binding found on the way is the one that counts. A binding in
7860    // no block (`var`) is reachable from anywhere, which is why the function scope
7861    // is the end of the walk.
7862    //
7863    // The block walk comes *before* the argument slots, because a block may shadow a
7864    // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
7865    // slot is only the answer once nothing nearer claims the name.
7866    let chain = block_chain(&stack[current], block);
7867    for scope in &chain {
7868        let found = stack[current]
7869            .vars
7870            .iter()
7871            .enumerate()
7872            .find(|(index, var)| {
7873                var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
7874            })
7875            .map(|(index, _)| index);
7876        if let Some(index) = found {
7877            return Slot::Loc(index as u32);
7878        }
7879    }
7880    // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
7881    // its own slot, and `var` of the same name in the body is the same binding.
7882    if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
7883        return Slot::Arg(index as u32);
7884    }
7885    // Function-scope bindings — `var` and function declarations — are recorded with
7886    // the sentinel block `0`, which no real scope uses, so the walk above cannot see
7887    // them. They are reachable from anywhere in the function, which is exactly what
7888    // the sentinel means.
7889    //
7890    // This pass is *only* for those. A lexical binding has to be found through the
7891    // chain or not at all, and looking a name up without its block is precisely how
7892    // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
7893    // block leaked out of it.
7894    let function_scoped = stack[current]
7895        .vars
7896        .iter()
7897        .enumerate()
7898        .find(|(index, var)| {
7899            var.name == name
7900                && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
7901                && (!in_params || visible_in_params(var))
7902        })
7903        .map(|(index, _)| index);
7904    if let Some(index) = function_scoped {
7905        return Slot::Loc(index as u32);
7906    }
7907    if let Some(index) = stack[current]
7908        .closure_vars
7909        .iter()
7910        .position(|c| c.name == name)
7911    {
7912        return slot_for_closure(&stack[current].closure_vars[index], index as u32);
7913    }
7914
7915    for owner in (0..current).rev() {
7916        // The nested function was created inside one of this frame's blocks, and the
7917        // outermost visible binding is the innermost block on that chain — not whatever
7918        // comes first in the variable table. `function f(){ class S{} }` has two `S`
7919        // bindings: the `let S` inside `f` and the `const S` inside the class body, and
7920        // the class body is the one a method may see.
7921        let entry = stack
7922            .get(owner + 1)
7923            .map(|s| s.created_in_block)
7924            .unwrap_or(0);
7925        let lexical = block_chain(&stack[owner], entry)
7926            .into_iter()
7927            .find_map(|scope| {
7928                stack[owner]
7929                    .vars
7930                    .iter()
7931                    .enumerate()
7932                    .find(|(index, var)| {
7933                        var.name == name
7934                            && stack[owner].var_block.get(*index).copied() == Some(scope)
7935                    })
7936                    .map(|(index, _)| index)
7937            });
7938        // A function born in a parameter list sees that list's bindings, not the body's:
7939        // the parameter scope is the environment it was created in.
7940        let in_param_scope = stack
7941            .get(owner + 1)
7942            .is_some_and(|child| child.created_in_params)
7943            .then(|| {
7944                stack[owner]
7945                    .vars
7946                    .iter()
7947                    .enumerate()
7948                    .position(|(index, var)| {
7949                        var.name == name
7950                            && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
7951                    })
7952            })
7953            .flatten();
7954        let found = if let Some(index) = in_param_scope {
7955            let var = &stack[owner].vars[index];
7956            Some(Found::Local(
7957                ClosureType::Local,
7958                index as u32,
7959                var.is_const,
7960                var.needs_check(),
7961            ))
7962        } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
7963            Some(Found::Local(ClosureType::Arg, index as u32, false, false))
7964        } else if let Some(index) = lexical {
7965            let var = &stack[owner].vars[index];
7966            Some(Found::Local(
7967                ClosureType::Local,
7968                index as u32,
7969                var.is_const,
7970                var.needs_check(),
7971            ))
7972        } else if let Some(index) = stack[owner]
7973            .vars
7974            .iter()
7975            .enumerate()
7976            .find_map(|(index, var)| {
7977                // A function created inside a parameter list must not see the body of the
7978                // function it was born in; see [`FnState::created_in_params`].
7979                let hidden = stack
7980                    .get(owner + 1)
7981                    .is_some_and(|child| child.created_in_params);
7982                (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
7983            })
7984        {
7985            let var = &stack[owner].vars[index];
7986            Some(Found::Local(
7987                ClosureType::Local,
7988                index as u32,
7989                var.is_const,
7990                var.needs_check(),
7991            ))
7992        } else if stack[owner].self_name.as_deref() == Some(name) {
7993            // A named function expression's own name. The reference declares it here,
7994            // on the first lookup that fails, rather than up front — and that is what
7995            // makes it reachable from a *nested* function: the nested lookup is what
7996            // walks out and creates the binding. A direct reference in the body is
7997            // caught the same way, which is why `provide_self_name` only has to add
7998            // the prologue.
7999            let strict = stack[owner].strict;
8000            stack[owner].var_block.push(FUNCTION_SCOPE);
8001            stack[owner].vars.push(VarDef {
8002                kind: VarKind::FunctionName,
8003                // In strict mode the name is immutable, so a store raises; sloppy
8004                // mode drops the store instead (see `variable_instruction`).
8005                is_const: strict,
8006                ..VarDef::var(name)
8007            });
8008            let index = stack[owner].vars.len() as u32 - 1;
8009            Some(Found::Local(ClosureType::Local, index, strict, false))
8010        } else if let Some(index) = stack[owner]
8011            .closure_vars
8012            .iter()
8013            .position(|c| c.name == name)
8014        {
8015            let closure = &stack[owner].closure_vars[index];
8016            Some(match closure.closure_type {
8017                // `GlobalRef` belongs here too: it is a *global* reached through this
8018                // frame's reference table, so treating it as a `Ref` to a local cell makes
8019                // the reader look for a cell no frame ever fills. That is how a second
8020                // function using `eval` in its parameter list read `undefined` after a
8021                // sibling had already made `eval` a closure entry.
8022                ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
8023                    Found::Global(index as u32)
8024                }
8025                // A module variable is a cell in the *module's* environment, which is
8026                // the module body's parent as far as a nested function is concerned — so
8027                // it is captured as a plain reference, not looked up as a global.
8028                ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
8029                    ClosureType::Ref,
8030                    index as u32,
8031                    closure.is_const,
8032                    closure.is_lexical,
8033                ),
8034                _ => Found::Local(
8035                    ClosureType::Ref,
8036                    index as u32,
8037                    closure.is_const,
8038                    closure.is_lexical,
8039                ),
8040            })
8041        } else {
8042            None
8043        };
8044        let Some(found) = found else { continue };
8045
8046        let (is_const, is_lexical) = match found {
8047            Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
8048            Found::Global(_) => (false, false),
8049        };
8050        // Mark the owner's binding as captured so it moves into a reference cell.
8051        if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
8052            let slot = match found {
8053                Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
8054                _ => &mut stack[owner].vars[index as usize],
8055            };
8056            slot.is_captured = true;
8057        }
8058        // Forward the reference through every function in between.
8059        let mut previous = match found {
8060            Found::Local(kind, index, _, _) => (kind, index),
8061            Found::Global(index) => (ClosureType::Global, index),
8062        };
8063        for level in owner + 1..=current {
8064            let kind = match (previous.0, level) {
8065                // A global stays a global at *every* level. Without `GlobalRef` in
8066                // this arm the second nested function over the same global got a
8067                // `Ref` to a cell no frame ever held, so the innermost closure read
8068                // `undefined` — which is how a two-deep getter lost its outer
8069                // variable.
8070                (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
8071                    ClosureType::GlobalRef
8072                }
8073                (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
8074                _ => ClosureType::Ref,
8075            };
8076            let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
8077            previous = (kind, index);
8078        }
8079        let index = previous.1;
8080        return slot_for_closure(&stack[current].closure_vars[index as usize], index);
8081    }
8082
8083    // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
8084    // creating a property. The top-level function holds the entry.
8085    let mut previous = (
8086        ClosureType::Global,
8087        ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
8088    );
8089    for level in 1..=current {
8090        let index = ensure_closure(
8091            stack,
8092            level,
8093            name,
8094            false,
8095            false,
8096            ClosureType::GlobalRef,
8097            previous.1,
8098        );
8099        previous = (ClosureType::GlobalRef, index);
8100    }
8101    Slot::Global(previous.1)
8102}
8103
8104/// What an outward search turned up.
8105#[derive(Debug, Clone, Copy)]
8106enum Found {
8107    /// A binding in an enclosing function, reachable through a closure of this
8108    /// type, with its const/lexical flags.
8109    Local(ClosureType, u32, bool, bool),
8110    /// A global, reached through the enclosing function's closure entry.
8111    Global(u32),
8112}
8113
8114/// Add a closure entry to `level` if it is not there yet.
8115fn ensure_closure(
8116    stack: &mut [FnState],
8117    level: usize,
8118    name: &str,
8119    is_const: bool,
8120    is_lexical: bool,
8121    closure_type: ClosureType,
8122    var_idx: u32,
8123) -> u32 {
8124    if let Some(index) = stack[level]
8125        .closure_vars
8126        .iter()
8127        .position(|c| c.name == name)
8128    {
8129        return index as u32;
8130    }
8131    stack[level].closure_vars.push(ClosureVar {
8132        name: name.to_string(),
8133        is_const,
8134        is_lexical,
8135        closure_type,
8136        var_idx: var_idx as u16,
8137    });
8138    stack[level].closure_vars.len() as u32 - 1
8139}
8140
8141fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
8142    match closure.closure_type {
8143        // A `global_ref` only says *how* the binding is found (through the
8144        // parent's closure table); the access itself is an ordinary global one.
8145        ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
8146        ClosureType::GlobalDecl => Slot::GlobalDecl(index),
8147        // A module variable is a real cell in the module's environment, so it is reached
8148        // exactly like a captured local — the host, not the global object, is what fills
8149        // the slot.
8150        ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
8151        _ => Slot::VarRef(index),
8152    }
8153}
8154
8155/// Pick the opcode for one variable access.
8156///
8157/// The `_check` variants are what enforce the temporal dead zone. They are used
8158/// for every access to a `let`/`const` binding except its own initialisation —
8159/// which is exactly the operation that takes the binding out of the dead zone.
8160fn variable_instruction(
8161    stack: &[FnState],
8162    current: usize,
8163    action: VarAction,
8164    slot: Slot,
8165) -> (Opcode, Vec<Op>) {
8166    let lexical = match slot {
8167        Slot::Loc(index) => stack[current]
8168            .vars
8169            .get(index as usize)
8170            .is_some_and(|v| v.needs_check()),
8171        Slot::VarRef(index) => stack[current]
8172            .closure_vars
8173            .get(index as usize)
8174            .is_some_and(|c| c.is_lexical),
8175        _ => false,
8176    };
8177    let operand = vec![Op::Slot(slot)];
8178    match (action, slot) {
8179        (VarAction::Get, Slot::Loc(index)) => (
8180            if lexical {
8181                Opcode::GetLocCheck
8182            } else {
8183                Opcode::GetLoc
8184            },
8185            vec![Op::Slot(Slot::Loc(index))],
8186        ),
8187        (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
8188        (VarAction::Get, Slot::VarRef(index)) => (
8189            if lexical {
8190                Opcode::GetVarRefCheck
8191            } else {
8192                Opcode::GetVarRef
8193            },
8194            vec![Op::Slot(Slot::VarRef(index))],
8195        ),
8196        (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
8197        (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
8198        (VarAction::GetUndef, Slot::Loc(_)) => (Opcode::GetLoc, operand),
8199        (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
8200        (VarAction::GetUndef, Slot::VarRef(_)) => (Opcode::GetVarRef, operand),
8201        (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8202            (Opcode::GetVarUndef, operand)
8203        }
8204
8205        (VarAction::Put, Slot::Loc(_)) => (
8206            if lexical {
8207                Opcode::PutLocCheck
8208            } else {
8209                Opcode::PutLoc
8210            },
8211            operand,
8212        ),
8213        (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
8214        (VarAction::Put, Slot::VarRef(_)) => (
8215            if lexical {
8216                Opcode::PutVarRefCheck
8217            } else {
8218                Opcode::PutVarRef
8219            },
8220            operand,
8221        ),
8222        (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
8223        (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8224        // Initialisation is what ends the dead zone, so it never checks.
8225        (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8226        (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
8227        // `this` in a derived constructor is always a local, so these cannot happen;
8228        // routing them to the ordinary forms keeps the match total without inventing
8229        // opcodes the reference does not have.
8230        (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
8231        (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8232        (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8233            (Opcode::PutVarInit, operand)
8234        }
8235        (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
8236        (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8237        (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8238            (Opcode::PutVarInit, operand)
8239        }
8240        (VarAction::Set, Slot::Loc(_)) => (
8241            if lexical {
8242                Opcode::SetLocCheck
8243            } else {
8244                Opcode::SetLoc
8245            },
8246            operand,
8247        ),
8248        (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
8249        (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
8250        (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8251        (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8252        (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
8253        (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8254        (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
8255        (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
8256        (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8257        (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
8258        (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8259        (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
8260    }
8261}
8262
8263/// The instruction-rewriting pass.
8264///
8265/// These are the reference implementation's patterns, restricted to the ones the
8266/// constructs this compiler supports can produce. Each entry is a comment on the
8267/// bytecode it removes, because the whole point is that the result is one
8268/// instruction shorter than the literal translation of the AST.
8269fn peephole(
8270    insns: &mut [Option<(Opcode, Vec<Op>)>],
8271    label_at: &[Option<u32>],
8272    placed: &[Option<usize>],
8273) {
8274    fold_dup_patterns(insns, label_at);
8275
8276    // `drop` before `return_undef` is dead: the return discards the whole frame
8277    // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
8278    // consumes its own `drop`; removing the drop first would leave the `dup` and
8279    // produce a `set_` where the reference has a `put_`.
8280    for index in 0..insns.len() {
8281        if opcode_at(insns, index) != Some(Opcode::Drop) {
8282            continue;
8283        }
8284        // Skip over a run of drops, but stop at a jump target: removing code on
8285        // one side of a label would silently retarget the jump.
8286        let mut next = index + 1;
8287        while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
8288            next += 1;
8289        }
8290        if is_label_at(label_at, next) {
8291            continue;
8292        }
8293        if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
8294            for entry in &mut insns[index..next] {
8295                *entry = None;
8296            }
8297        }
8298    }
8299
8300    // The rewrites below all decide against one fixed snapshot, which is what the
8301    // reference sees: `code_match` reads the bytecode buffer as it was on entry to
8302    // the pass, so a rule never observes what an earlier rule removed. Gathering
8303    // every deletion first and applying them together reproduces that.
8304    let snapshot: Vec<Option<Opcode>> = insns
8305        .iter()
8306        .map(|entry| entry.as_ref().map(|(op, _)| *op))
8307        .collect();
8308    // The next instruction that is still there. Holes left by dead-code
8309    // elimination are not instructions, so a rule looks past them.
8310    let next_op = |index: usize| -> Option<usize> {
8311        (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
8312    };
8313
8314    let mut doomed = vec![false; insns.len()];
8315    for index in 0..insns.len() {
8316        // A constant pushed only to be dropped does nothing at all. This is what a
8317        // comma expression with a literal left operand compiles to — `(0, f)()` — and
8318        // the reference removes the pair rather than making the reader step over it.
8319        let constant = matches!(
8320            snapshot[index],
8321            Some(
8322                Opcode::Undefined
8323                    | Opcode::Null
8324                    | Opcode::PushMinus1
8325                    | Opcode::Push0
8326                    | Opcode::Push1
8327                    | Opcode::Push2
8328                    | Opcode::Push3
8329                    | Opcode::Push4
8330                    | Opcode::Push5
8331                    | Opcode::Push6
8332                    | Opcode::Push7
8333                    | Opcode::PushTrue
8334                    | Opcode::PushFalse
8335                    | Opcode::PushI32
8336            )
8337        );
8338        if constant
8339            && let Some(next) = next_op(index)
8340            && snapshot[next] == Some(Opcode::Drop)
8341        {
8342            doomed[index] = true;
8343            doomed[next] = true;
8344        }
8345    }
8346    for (index, entry) in insns.iter_mut().enumerate() {
8347        if doomed[index] {
8348            *entry = None;
8349        }
8350    }
8351
8352    // A conditional whose destination is the very next instruction just pops its
8353    // condition, so it becomes a plain `drop`. This is what an empty `case` clause
8354    // compiles to.
8355    //
8356    // Order matters, and it is the reference's order: this runs *before* the
8357    // folding below, on the instruction the conditional originally had. Folding
8358    // moves a conditional's destination, and the reference never re-examines it
8359    // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
8360    // a conditional even though folding leaves it pointing at the next
8361    // instruction.
8362    for (index, entry) in insns.iter_mut().enumerate() {
8363        let Some((op, operands)) = entry.clone() else {
8364            continue;
8365        };
8366        if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
8367            continue;
8368        }
8369        let Some(id) = label_id(&operands) else {
8370            continue;
8371        };
8372        if placed.get(id as usize).copied().flatten() == Some(index + 1) {
8373            *entry = Some((Opcode::Drop, Vec::new()));
8374        }
8375    }
8376
8377    // A constant condition is decided here rather than at run time.
8378    fold_constant_conditions(insns);
8379    // The conditional folding below is about pairs of *real* branches, so it runs
8380    // before a jump to the next instruction is dropped: `do { … if (c) continue }
8381    // while (t)` puts `continue` exactly on the condition, and the reference inverts
8382    // the branch first and only then notices the jump goes nowhere.
8383    fold_conditional_jumps(insns, label_at, placed);
8384
8385    // A jump whose destination is the very next instruction does nothing, which is
8386    // what constant folding leaves behind for `while (1) { … }`.
8387    remove_jump_to_next(insns, placed);
8388
8389    // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
8390    // a use of the same variable boils down to.
8391    for index in 0..insns.len() {
8392        let Some((put_op, _)) = insns[index].clone() else {
8393            continue;
8394        };
8395        if !is_foldable_put(put_op) {
8396            continue;
8397        }
8398        if is_label_at(label_at, index + 1) {
8399            continue;
8400        }
8401        let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
8402            continue;
8403        };
8404        if get_op != get_form_of(put_op) {
8405            continue;
8406        }
8407        let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
8408        if put_slot.is_none() || put_slot != get_operands.first().cloned() {
8409            continue;
8410        }
8411        insns[index] = Some((set_form_of(put_op), get_operands));
8412        insns[index + 1] = None;
8413    }
8414}
8415
8416/// Drop `gosub`s that call an empty subroutine.
8417///
8418/// A `gosub` whose target starts with `ret` returns immediately, so the reference
8419/// drops the call. This is how `try`/`catch` without a `finally` loses its
8420/// finalizer plumbing: the finalizer block is empty, its first instruction is
8421/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
8422/// [`eliminate_dead_code`] then removes.
8423fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
8424    let state = &stack[current];
8425    let mut targets = Vec::new();
8426    for insn in &state.insns {
8427        if let Insn::Fixed { op, operands } = insn
8428            && *op == Opcode::Gosub
8429            && let Some(id) = label_id(operands)
8430            && let Some(target) = state.labels.get(id as usize).copied().flatten()
8431        {
8432            targets.push(target);
8433        }
8434    }
8435    let empty: Vec<usize> = targets
8436        .into_iter()
8437        .filter(|target| {
8438            stack[current]
8439                .insns
8440                .get(*target)
8441                .map(|insn| {
8442                    matches!(
8443                        insn,
8444                        Insn::Fixed {
8445                            op: Opcode::Ret,
8446                            ..
8447                        }
8448                    )
8449                })
8450                .unwrap_or(false)
8451        })
8452        .collect();
8453    if empty.is_empty() {
8454        return;
8455    }
8456    for insn in stack[current].insns.iter_mut() {
8457        if let Insn::Fixed { op, operands } = insn
8458            && *op == Opcode::Gosub
8459            && let Some(id) = label_id(operands)
8460            && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
8461            && empty.contains(&target)
8462        {
8463            *insn = Insn::Dead;
8464        }
8465    }
8466}
8467
8468/// Replace unreachable instructions with [`Insn::Dead`].
8469fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
8470    let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
8471    for (index, insn) in stack[current].insns.iter_mut().enumerate() {
8472        if !reachable[index] {
8473            *insn = Insn::Dead;
8474        }
8475    }
8476}
8477
8478/// Mark every instruction index reachable from the entry, plus the index one past
8479/// the last instruction.
8480///
8481/// `seen[len]` answers "can control reach the end of this function", and the
8482/// entries before it identify dead code. Both DCE and the implicit-return decision
8483/// read the same result, which keeps them from disagreeing.
8484fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
8485    let mut seen = vec![false; count + 1];
8486    let mut worklist = vec![0usize];
8487    while let Some(index) = worklist.pop() {
8488        if index > count || seen[index] {
8489            continue;
8490        }
8491        seen[index] = true;
8492        if index == count {
8493            continue;
8494        }
8495        let (op, operands) = match &state.insns[index] {
8496            Insn::Fixed { op, operands } => (*op, operands.as_slice()),
8497            // A variable access never transfers control, and a removed
8498            // instruction is only reachable if it is already marked.
8499            Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
8500                worklist.push(index + 1);
8501                continue;
8502            }
8503        };
8504        match op {
8505            // A return, a throw and a `ret` all leave this instruction stream: the
8506            // first two give control to the caller or the handler, and `ret`
8507            // returns to a `gosub` elsewhere.
8508            // A tail call leaves the function too: the callee's result becomes this
8509            // function's result, so nothing after it runs.
8510            Opcode::Return
8511            | Opcode::ReturnUndef
8512            | Opcode::ReturnAsync
8513            | Opcode::TailCall
8514            | Opcode::TailCallMethod
8515            | Opcode::Throw
8516            | Opcode::ThrowError
8517            | Opcode::Ret => {}
8518            // A `catch` records where exceptions from the code that follows go.
8519            // That code is not reachable through normal control flow, but it is
8520            // reachable — through the exception edge — so the walk has to follow
8521            // it, or dead-code elimination would delete every handler.
8522            Opcode::Catch => {
8523                if let Some(target) = placed_label(state, operands) {
8524                    worklist.push(target);
8525                }
8526                worklist.push(index + 1);
8527            }
8528            // A `gosub` calls a subroutine and then continues, so both edges count.
8529            Opcode::Gosub => {
8530                if let Some(target) = placed_label(state, operands) {
8531                    worklist.push(target);
8532                }
8533                worklist.push(index + 1);
8534            }
8535            Opcode::Goto => {
8536                if let Some(target) = placed_label(state, operands) {
8537                    worklist.push(target);
8538                }
8539            }
8540            Opcode::IfTrue | Opcode::IfFalse => {
8541                if let Some(target) = placed_label(state, operands) {
8542                    worklist.push(target);
8543                }
8544                worklist.push(index + 1);
8545            }
8546            _ => worklist.push(index + 1),
8547        }
8548    }
8549    seen
8550}
8551
8552/// The instruction index a jump operand points at, resolved through the label
8553/// placement table.
8554fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
8555    let id = label_id(operands)?;
8556    state.labels.get(id as usize).copied().flatten()
8557}
8558
8559/// The label an instruction refers to.
8560fn label_id(operands: &[Op]) -> Option<u32> {
8561    operands.iter().find_map(|operand| match operand {
8562        Op::Label(label) => Some(label.0),
8563        _ => None,
8564    })
8565}
8566
8567/// Turn `if_false L; goto M; L:` into `if_true M`.
8568///
8569/// A conditional whose alternate branch is an unconditional jump needs one jump,
8570/// not two. This is the shape `if (c) break;` produces, so folding it removes an
8571/// instruction and a label from every conditional `break`.
8572/// The boolean a constant-push instruction produces, or `None` if it is not one.
8573///
8574/// Only the operators whose truthiness is decided by the opcode are covered; a
8575/// constant that needs the constant pool (a string) is left alone, because reading it
8576/// would mean threading the pool through the peephole for a case the reference also
8577/// skips.
8578fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
8579    match op {
8580        // `push_0` returns -1 for zero, `push_1` 1, and so on.
8581        Opcode::PushMinus1 => Some(true),
8582        Opcode::Push0 => Some(false),
8583        Opcode::Push1
8584        | Opcode::Push2
8585        | Opcode::Push3
8586        | Opcode::Push4
8587        | Opcode::Push5
8588        | Opcode::Push6
8589        | Opcode::Push7 => Some(true),
8590        Opcode::PushTrue => Some(true),
8591        Opcode::PushFalse => Some(false),
8592        Opcode::Undefined | Opcode::Null => Some(false),
8593        Opcode::PushI32 => match operands.first() {
8594            Some(Op::Int(value)) => Some(*value != 0),
8595            _ => None,
8596        },
8597        _ => None,
8598    }
8599}
8600
8601/// Fold a branch on a constant condition.
8602///
8603/// `if (0) a() else b()` must not test anything at run time, and the reference
8604/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
8605/// which is why the bytecode for a `while (1)` loop has no condition at all.
8606///
8607/// Two instructions become one, so the slot the test occupied is left empty rather
8608/// than shifting everything after it: labels have already been resolved to indices.
8609fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>]) {
8610    for index in 0..insns.len() {
8611        let Some((push_op, push_operands)) = insns[index].clone() else {
8612            continue;
8613        };
8614        let Some(truth) = constant_truth(push_op, &push_operands) else {
8615            continue;
8616        };
8617        let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
8618            continue;
8619        };
8620        let (destination, taken) = match branch_op {
8621            Opcode::IfTrue => (branch_operands.first().cloned(), truth),
8622            Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
8623            _ => continue,
8624        };
8625        let Some(destination) = destination else {
8626            continue;
8627        };
8628        insns[index] = if taken {
8629            // The branch is always taken, so it becomes an unconditional jump.
8630            Some((Opcode::Goto, vec![destination]))
8631        } else {
8632            // The branch never runs: both instructions disappear and control falls
8633            // through to what came after.
8634            None
8635        };
8636        insns[index + 1] = None;
8637    }
8638}
8639
8640/// Remove a jump whose destination is the instruction right after it.
8641///
8642/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
8643/// its test into nothing, and the loop-end jump then points at the following
8644/// instruction. The reference drops them, so `stack_size` and the listing agree.
8645fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
8646    for index in 0..insns.len() {
8647        let Some((op, operands)) = insns[index].clone() else {
8648            continue;
8649        };
8650        if !is_goto(op) {
8651            continue;
8652        }
8653        let Some(id) = label_id(&operands) else {
8654            continue;
8655        };
8656        // The next instruction that still exists, which is what "the instruction
8657        // after this jump" means once earlier folds have punched holes.
8658        let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
8659        if placed.get(id as usize).copied().flatten() == next {
8660            insns[index] = None;
8661        }
8662    }
8663}
8664
8665fn fold_conditional_jumps(
8666    insns: &mut [Option<(Opcode, Vec<Op>)>],
8667    label_at: &[Option<u32>],
8668    placed: &[Option<usize>],
8669) {
8670    for index in 0..insns.len() {
8671        let Some((op, operands)) = insns[index].clone() else {
8672            continue;
8673        };
8674        let inverted = match op {
8675            Opcode::IfFalse => Opcode::IfTrue,
8676            Opcode::IfTrue => Opcode::IfFalse,
8677            _ => continue,
8678        };
8679        // Next must be an unconditional jump that is not itself a target, and the
8680        // instruction after it must be exactly where the conditional goes.
8681        let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
8682            continue;
8683        };
8684        if !is_goto(next_op) || is_label_at(label_at, index + 1) {
8685            continue;
8686        }
8687        // The conditional must land on the instruction *after* the jump. Several
8688        // labels can share a position, so this asks where *this* label was put
8689        // rather than what label happens to sit there.
8690        let Some(taken) = label_id(&operands) else {
8691            continue;
8692        };
8693        if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
8694            continue;
8695        }
8696        let Some(destination) = next_operands.first().cloned() else {
8697            continue;
8698        };
8699        insns[index] = Some((inverted, vec![destination]));
8700        insns[index + 1] = None;
8701    }
8702}
8703
8704/// Whether a jump target is placed at this instruction index.
8705fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
8706    label_at.get(index).copied().flatten().is_some()
8707}
8708
8709fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
8710    // `dup put_x(n)` -> `set_x(n)`
8711    // `dup put_x(n) drop` -> `put_x(n)`
8712    // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
8713    for index in 0..insns.len() {
8714        if opcode_at(insns, index) != Some(Opcode::Dup) {
8715            continue;
8716        }
8717        if is_label_at(label_at, index + 1) {
8718            continue;
8719        }
8720        let Some((put_op, put_operands)) = insns[index + 1].clone() else {
8721            continue;
8722        };
8723        if !is_foldable_put(put_op) {
8724            continue;
8725        }
8726        let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
8727            continue;
8728        };
8729        let mut new_op = set_form_of(put_op);
8730        let mut end = index + 2;
8731        if is_label_at(label_at, end) {
8732            // The `put` has to stay as it is; only the `dup` can be folded.
8733            insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
8734            insns[index + 1] = None;
8735            continue;
8736        }
8737        // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
8738        // Deleting it moves the label's target onto whatever follows, and the code that
8739        // jumps there arrives with a different stack than the fall-through path: that is
8740        // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
8741        // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
8742        // an empty stack. The store had already consumed the value it was supposed to
8743        // leave behind.
8744        if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
8745            new_op = put_op;
8746            end += 1;
8747            if opcode_at(insns, end) == Some(get_form_of(put_op))
8748                && !is_label_at(label_at, end)
8749                && insns[end]
8750                    .as_ref()
8751                    .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
8752            {
8753                new_op = set_form_of(put_op);
8754                end += 1;
8755            }
8756        }
8757        insns[index] = Some((new_op, vec![Op::Slot(slot)]));
8758        for entry in &mut insns[index + 1..end] {
8759            *entry = None;
8760        }
8761    }
8762}
8763
8764fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
8765    insns
8766        .get(index)
8767        .and_then(|entry| entry.as_ref())
8768        .map(|(op, _)| *op)
8769}
8770
8771/// The four `put_` families that have a `set_` twin. Deliberately not including
8772/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
8773/// these, and folding the others would produce instructions that do not exist.
8774fn is_foldable_put(op: Opcode) -> bool {
8775    matches!(
8776        op,
8777        Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
8778    )
8779}
8780
8781fn set_form_of(op: Opcode) -> Opcode {
8782    match op {
8783        Opcode::PutLoc => Opcode::SetLoc,
8784        Opcode::PutLocCheck => Opcode::SetLocCheck,
8785        Opcode::PutArg => Opcode::SetArg,
8786        Opcode::PutVarRef => Opcode::SetVarRef,
8787        other => other,
8788    }
8789}
8790
8791fn get_form_of(op: Opcode) -> Opcode {
8792    match op {
8793        Opcode::PutLoc => Opcode::GetLoc,
8794        Opcode::PutLocCheck => Opcode::GetLocCheck,
8795        Opcode::PutArg => Opcode::GetArg,
8796        Opcode::PutVarRef => Opcode::GetVarRef,
8797        other => other,
8798    }
8799}
8800
8801/// Atom interning, per function.
8802///
8803/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
8804/// identifiers, so the array-index rule applies here rather than at the handful of
8805/// call sites that build property keys.
8806fn intern_atom(state: &mut FnState, name: &str) -> u32 {
8807    intern_atom_value(state, Atom::from_text(name))
8808}
8809
8810/// [`intern_atom`] for an operand that is already an [`Atom`].
8811///
8812/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
8813/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
8814/// would have looked up.
8815fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
8816    if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
8817        return index as u32;
8818    }
8819    state.atoms.push(atom);
8820    state.atoms.len() as u32 - 1
8821}
8822
8823fn binary_opcode(op: BinaryOp) -> Opcode {
8824    match op {
8825        BinaryOp::Add => Opcode::Add,
8826        BinaryOp::Sub => Opcode::Sub,
8827        BinaryOp::Mul => Opcode::Mul,
8828        BinaryOp::Div => Opcode::Div,
8829        BinaryOp::Mod => Opcode::Mod,
8830        BinaryOp::Pow => Opcode::Pow,
8831        BinaryOp::BitOr => Opcode::Or,
8832        BinaryOp::BitXor => Opcode::Xor,
8833        BinaryOp::BitAnd => Opcode::And,
8834        BinaryOp::Shl => Opcode::Shl,
8835        BinaryOp::Shr => Opcode::Sar,
8836        BinaryOp::UShr => Opcode::Shr,
8837        BinaryOp::Lt => Opcode::Lt,
8838        BinaryOp::LtEq => Opcode::Lte,
8839        BinaryOp::Gt => Opcode::Gt,
8840        BinaryOp::GtEq => Opcode::Gte,
8841        BinaryOp::Eq => Opcode::Eq,
8842        BinaryOp::NotEq => Opcode::Neq,
8843        BinaryOp::StrictEq => Opcode::StrictEq,
8844        BinaryOp::StrictNotEq => Opcode::StrictNeq,
8845        BinaryOp::In => Opcode::In,
8846        BinaryOp::Instanceof => Opcode::Instanceof,
8847    }
8848}
8849
8850fn compound_opcode(op: AssignOp) -> Opcode {
8851    match op {
8852        AssignOp::Add => Opcode::Add,
8853        AssignOp::Sub => Opcode::Sub,
8854        AssignOp::Mul => Opcode::Mul,
8855        AssignOp::Div => Opcode::Div,
8856        AssignOp::Mod => Opcode::Mod,
8857        AssignOp::Pow => Opcode::Pow,
8858        AssignOp::Shl => Opcode::Shl,
8859        AssignOp::Shr => Opcode::Sar,
8860        AssignOp::UShr => Opcode::Shr,
8861        AssignOp::BitOr => Opcode::Or,
8862        AssignOp::BitXor => Opcode::Xor,
8863        AssignOp::BitAnd => Opcode::And,
8864        AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
8865    }
8866}
8867
8868/// Encode the resolved instruction stream, choosing short forms where possible.
8869///
8870/// The peephole pass leaves holes in the instruction list so that label indices
8871/// stay valid. A label names an *instruction index*, and an index that was
8872/// deleted has to resolve to the next surviving instruction, which is what
8873/// [`resolve_label`] does before the byte offsets are known.
8874fn assemble(
8875    insns: &mut [Option<(Opcode, Vec<Op>)>],
8876    insn_pos: &[Option<Position>],
8877    state: &mut FnState,
8878) -> (Vec<u8>, u32, Vec<LineCol>) {
8879    // Compaction: surviving instructions in order, plus the index mapping.
8880    //
8881    // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
8882    // point below where instructions are removed — otherwise a stack trace would point
8883    // at the wrong source line as soon as dead-code elimination kicked in.
8884    let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
8885    let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
8886    let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
8887    for (original, entry) in insns.iter_mut().enumerate() {
8888        if let Some((op, operands)) = entry.take() {
8889            original_to_kept[original] = Some(kept.len());
8890            kept.push((op, operands));
8891            spans.push(insn_pos.get(original).copied().flatten());
8892        }
8893    }
8894
8895    if std::env::var_os("QJS_DEBUG").is_some() {
8896        eprintln!("--- assemble entry --- {kept:?}");
8897    }
8898    // How many labels are real, as opposed to the per-instruction ones allocated
8899    // just below. Only a real label marks a spot in the source program.
8900    let real_labels = state.labels.len();
8901
8902    // Give every surviving instruction a label of its own. Jump cleanup below
8903    // redirects jumps to arbitrary instructions, and a jump target has to be a
8904    // label; pre-allocating one per index means a redirect never has to invent
8905    // anything.
8906    let existing = state.labels.len();
8907    let base = kept.len();
8908    let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
8909    for offset in 0..=kept.len() {
8910        state.labels.push(Some(0));
8911        index_label.push(Label((existing + offset) as u32));
8912    }
8913    // Point each pre-allocated label at its instruction, reusing the count from
8914    // `original_to_kept` so the mapping survives compaction.
8915    let place_index_labels = |state: &mut FnState,
8916                              original_to_kept: &[Option<usize>],
8917                              kept_len: usize,
8918                              index_label: &[Label]| {
8919        for (original, mapped) in original_to_kept.iter().enumerate() {
8920            if let Some(kept_index) = mapped {
8921                let label = index_label[*kept_index].0 as usize;
8922                state.labels[label] = Some(original);
8923            }
8924        }
8925        state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
8926    };
8927    place_index_labels(state, &original_to_kept, base, &index_label);
8928
8929    // Resolve every label to a kept index once; the placement table maps labels
8930    // to original indices, so a second hop lands in kept space.
8931    let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
8932    for (id, placed) in state.labels.iter().enumerate() {
8933        let Some(original) = placed else { continue };
8934        label_kept[id] = if *original == usize::MAX {
8935            Some(base)
8936        } else {
8937            (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
8938        };
8939    }
8940
8941    // Code after an unconditional transfer is unreachable, and the reference drops it
8942    // as it walks past the transfer — the `skip_dead_code` in its first pass. It
8943    // scans forward until it finds a label something still jumps to, so a run of
8944    // dead instructions between a `throw` and the next live target disappears.
8945    //
8946    // The scan repeats because dropping a jump lowers the reference count of the
8947    // label it pointed at, which can strand what follows. Only a real label keeps an
8948    // instruction alive here; the per-instruction labels allocated above belong to
8949    // this pass, not to the program.
8950    loop {
8951        let mut references = vec![false; kept.len() + 1];
8952        for (_, operands) in &kept {
8953            if let Some(target) = target_kept_index(operands, &label_kept)
8954                && target < references.len()
8955            {
8956                references[target] = true;
8957            }
8958        }
8959        let mut doomed = vec![false; kept.len()];
8960        let mut any = false;
8961        for (index, (op, _)) in kept.iter().enumerate() {
8962            if !is_transfer(*op) {
8963                continue;
8964            }
8965            for next in index + 1..kept.len() {
8966                if references[next] {
8967                    break;
8968                }
8969                doomed[next] = true;
8970                any = true;
8971            }
8972        }
8973        if !any {
8974            break;
8975        }
8976        (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
8977    }
8978
8979    // A label that lands on an unconditional jump stands for wherever that jump
8980    // goes, so retarget it once and every jump to the label follows for free.
8981    // This is what makes `continue` in a `for` head reach the loop top instead of
8982    // stopping at the update's trailing jump.
8983    let folded: Vec<Option<usize>> = label_kept
8984        .iter()
8985        .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
8986        .collect();
8987    label_kept = folded;
8988
8989    // Jump cleanup, in compacted index space. Two rewrites the reference also
8990    // applies while it resolves labels:
8991    //   * a jump whose destination is the very next instruction does nothing;
8992    //   * a jump to a jump is redirected to its final destination.
8993    // The second can expose the first, so this repeats until it settles.
8994    loop {
8995        let mut delete = vec![false; kept.len()];
8996        let mut changed = false;
8997        for index in 0..kept.len() {
8998            let (op, operands) = &kept[index];
8999            if !is_goto(*op) {
9000                continue;
9001            }
9002            let Some(immediate) = target_kept_index(operands, &label_kept) else {
9003                continue;
9004            };
9005            let target = follow_jump_chain(&kept, &label_kept, immediate);
9006            if target == index + 1 {
9007                delete[index] = true;
9008                changed = true;
9009            } else if matches!(
9010                kept.get(target).map(|(op, _)| *op),
9011                Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
9012            ) {
9013                // Jumping straight to a return or throw is the same as doing it
9014                // here, so the jump becomes that instruction.
9015                kept[index] = (kept[target].0, Vec::new());
9016                changed = true;
9017            } else if target != immediate {
9018                // Redirect to the end of the chain.
9019                let label = index_label[target];
9020                kept[index].1 = vec![Op::Label(label)];
9021                changed = true;
9022            }
9023        }
9024        if !changed {
9025            break;
9026        }
9027        if !delete.iter().any(|deleted| *deleted) {
9028            break;
9029        }
9030        // Drop the deleted instructions and renumber everything.
9031        let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9032        let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9033        let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9034        for (old, entry) in kept.into_iter().enumerate() {
9035            if delete[old] {
9036                continue;
9037            }
9038            moved[old] = Some(next.len());
9039            next.push(entry);
9040            next_spans.push(spans[old]);
9041        }
9042        for (id, slot) in label_kept.iter_mut().enumerate() {
9043            let Some(old) = *slot else { continue };
9044            *slot = match moved.get(old).copied().flatten() {
9045                Some(new) => Some(new),
9046                // The target was deleted: the jump now lands on whatever follows.
9047                None => (old..moved.len())
9048                    .find_map(|i| moved[i])
9049                    .or(Some(next.len())),
9050            };
9051            let _ = id;
9052        }
9053        kept = next;
9054        spans = next_spans;
9055    }
9056
9057    // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
9058    // jump to the next instruction and is deleted, leaving the label at the end with
9059    // nothing pointing at it. If that also strands the last instruction, it goes
9060    // too — which is how a `try` whose body always returns ends on its `ret` rather
9061    // than an implicit `return_undef`.
9062    // Which instructions something still jumps to. Reading the surviving jumps is
9063    // what the reference's reference counts amount to: once a jump has been folded
9064    // away the label it named is unreferenced, even though the program still has a
9065    // label there.
9066    let mut references = vec![false; kept.len() + 1];
9067    let _ = real_labels;
9068    for (_, operands) in &kept {
9069        if let Some(target) = target_kept_index(operands, &label_kept)
9070            && target < references.len()
9071        {
9072            references[target] = true;
9073        }
9074    }
9075    let mut end = kept.len();
9076    while end > 0 {
9077        let last = end - 1;
9078        let reachable = references[last] || end < kept.len();
9079        if reachable {
9080            break;
9081        }
9082        let after_transfer = last
9083            .checked_sub(1)
9084            .map(|previous| {
9085                matches!(
9086                    kept[previous].0,
9087                    Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
9088                )
9089            })
9090            .unwrap_or(false);
9091        if !after_transfer {
9092            break;
9093        }
9094        end = last;
9095    }
9096    kept.truncate(end);
9097    spans.truncate(end);
9098
9099    // Choose an opcode for each instruction and its size, so label offsets can be
9100    // computed.
9101    let chosen = choose_opcodes(&kept, &label_kept);
9102    let offsets = instruction_offsets(&chosen);
9103    let offset = *offsets.last().unwrap_or(&0);
9104
9105    let mut code = Vec::with_capacity(offset);
9106    for (position, (_, operands)) in kept.iter().enumerate() {
9107        let op = chosen[position];
9108        code.push(op as u8);
9109        let operands = retarget_labels(operands, &label_kept, kept.len());
9110        encode_operands(&mut code, op, &operands, offsets[position], &offsets);
9111    }
9112    let stack_size = compute_stack_size(&code);
9113    // Keep only the offsets where the position actually changes: a run of
9114    // instructions on one line is one table entry, and the runtime binary searches
9115    // the table for the frame's pc.
9116    //
9117    // The table always starts at pc 0 with the *function's own* position, because the
9118    // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
9119    // last_line_num)` from `fd->source_pos`, the token the function definition starts at
9120    // (`function`, `async`, a method's property name). An instruction before the first
9121    // recorded operator therefore reports the function's own start, which is what makes a
9122    // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
9123    let mut positions: Vec<LineCol> = vec![LineCol {
9124        pc: 0,
9125        line: state.line,
9126        column: state.column,
9127    }];
9128    let mut last: Option<Position> = None;
9129    for (index, span) in spans.iter().enumerate() {
9130        let Some(pos) = *span else { continue };
9131        if last == Some(pos) {
9132            continue;
9133        }
9134        last = Some(pos);
9135        if pos.line == state.line && pos.column == state.column {
9136            // Already the seed entry above.
9137            continue;
9138        }
9139        positions.push(LineCol {
9140            pc: offsets[index] as u32,
9141            line: pos.line,
9142            column: pos.column,
9143        });
9144    }
9145    (code, stack_size, positions)
9146}
9147
9148/// Whether an instruction always transfers control away, so anything after it in the
9149/// same stream is unreachable.
9150fn is_transfer(op: Opcode) -> bool {
9151    matches!(
9152        op,
9153        Opcode::Goto
9154            | Opcode::Goto8
9155            | Opcode::Goto16
9156            | Opcode::Return
9157            | Opcode::ReturnUndef
9158            | Opcode::Throw
9159            | Opcode::ThrowError
9160            | Opcode::Ret
9161    )
9162}
9163
9164/// Remove the marked instructions and renumber the label table so it keeps pointing
9165/// at the same instructions. A label whose instruction went away moves to whatever
9166/// follows it, since a jump is never left with nowhere to land.
9167fn drop_instructions(
9168    kept: Vec<(Opcode, Vec<Op>)>,
9169    spans: Vec<Option<Position>>,
9170    label_kept: &mut [Option<usize>],
9171    doomed: &[bool],
9172) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
9173    let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9174    let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9175    let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9176    for (old, entry) in kept.into_iter().enumerate() {
9177        if doomed.get(old).copied().unwrap_or(false) {
9178            continue;
9179        }
9180        moved[old] = Some(result.len());
9181        result.push(entry);
9182        result_spans.push(spans[old]);
9183    }
9184    for slot in label_kept.iter_mut() {
9185        let Some(old) = *slot else { continue };
9186        *slot = match moved.get(old).copied().flatten() {
9187            Some(new) => Some(new),
9188            None => (old..moved.len())
9189                .find_map(|i| moved[i])
9190                .or(Some(result.len())),
9191        };
9192    }
9193    (result, result_spans)
9194}
9195
9196fn is_goto(op: Opcode) -> bool {
9197    matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
9198}
9199
9200/// The kept index a jump operand points at.
9201fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
9202    let id = label_id(operands)?;
9203    label_kept.get(id as usize).copied().flatten()
9204}
9205
9206/// Follow a chain of unconditional jumps to its first real destination.
9207fn follow_jump_chain(
9208    kept: &[(Opcode, Vec<Op>)],
9209    label_kept: &[Option<usize>],
9210    start: usize,
9211) -> usize {
9212    let mut current = start;
9213    // `for(;;)` jumps to itself, so the walk has to be bounded.
9214    for _ in 0..kept.len() {
9215        let Some((op, operands)) = kept.get(current) else {
9216            return current;
9217        };
9218        if !is_goto(*op) {
9219            return current;
9220        }
9221        let Some(next) = target_kept_index(operands, label_kept) else {
9222            return current;
9223        };
9224        if next == current {
9225            return current;
9226        }
9227        current = next;
9228    }
9229    current
9230}
9231
9232/// Rewrite label operands from label ids to kept instruction indices.
9233fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
9234    operands
9235        .iter()
9236        .map(|operand| match operand {
9237            Op::Label(label) => {
9238                let target = label_kept
9239                    .get(label.0 as usize)
9240                    .copied()
9241                    .flatten()
9242                    .unwrap_or(kept_len);
9243                Op::Label(Label(target as u32))
9244            }
9245            other => other.clone(),
9246        })
9247        .collect()
9248}
9249
9250/// Encode the resolved instruction stream, choosing short forms where possible.
9251///
9252/// Compute the maximum value-stack depth by exploring the control-flow graph.
9253///
9254/// This is a breadth-first walk from the first instruction, tracking the stack
9255/// depth on entry to each instruction. Every instruction has at most two
9256/// successors (fall through, and a jump target), so a worklist over byte offsets
9257/// is enough. The reference does the same thing in `compute_stack_size`, which is
9258/// why the resulting numbers match exactly.
9259///
9260/// Instructions that pop a variable number of values (`call`, `array_from`, …)
9261/// encode that count in their operand, which is added to the static `n_pop`.
9262fn compute_stack_size(code: &[u8]) -> u32 {
9263    let mut depth_at = vec![u16::MAX; code.len()];
9264    // Each entry carries the enclosing `catch` levels, innermost last, because
9265    // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
9266    // offset and forgets that level.
9267    let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
9268    let mut max_depth = 0u32;
9269
9270    while let Some((pc, depth, catch_levels)) = worklist.pop() {
9271        if pc >= code.len() {
9272            continue;
9273        }
9274        if depth_at[pc] != u16::MAX {
9275            continue;
9276        }
9277        force_depth(&mut depth_at, pc, depth);
9278
9279        let Some(op) = Opcode::from_u8(code[pc]) else {
9280            break;
9281        };
9282        let info = op.info();
9283        let next = pc + info.size as usize;
9284        if next > code.len() {
9285            break;
9286        }
9287        let mut n_pop = info.n_pop as u32;
9288        let mut n_push = info.n_push as u32;
9289        // Variable-length forms carry their count in the operand.
9290        match info.format {
9291            crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
9292                n_pop += read_u16(code, pc + 1) as u32;
9293            }
9294            crate::opcode::OpFormat::Npopx => {
9295                n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
9296            }
9297            _ => {}
9298        }
9299        // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
9300        // are the `set_` variant; the table already records that, so nothing to
9301        // adjust here.
9302        let _ = &mut n_push;
9303
9304        // The depth before this instruction's own push, which is what a `catch`
9305        // records as its level.
9306        let depth_before = depth;
9307        let mut depth = depth.saturating_sub(n_pop) + n_push;
9308        let mut catch_levels = catch_levels;
9309        if op == Opcode::NipCatch {
9310            // Discard everything above the innermost catch offset, keeping the value
9311            // on top: the frame the code after this sees is the same shape it would
9312            // have had if the `try` were not there.
9313            if let Some(base) = catch_levels.pop() {
9314                depth = base + 1;
9315            }
9316        }
9317        max_depth = max_depth.max(depth);
9318
9319        // Successors.
9320        let target = jump_target_of(code, pc, op);
9321        match op {
9322            Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9323                if let Some(target) = target {
9324                    worklist.push((target, depth, catch_levels));
9325                }
9326            }
9327            Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
9328                if let Some(target) = target {
9329                    worklist.push((target, depth, catch_levels.clone()));
9330                }
9331                worklist.push((next, depth, catch_levels));
9332            }
9333            // A `catch` records an exception edge to the handler. The handler is
9334            // entered with the thrown value on top of the stack, in the slot the
9335            // catch offset occupies on the normal path — which is why the handler's
9336            // first instruction can `put_loc` the exception away, and why the depth
9337            // is the same on both paths.
9338            Opcode::Catch => {
9339                if let Some(target) = target {
9340                    // The handler is protected by the *enclosing* catch, not by this
9341                    // one: an error raised inside it is what the handler's own
9342                    // `catch` catches.
9343                    worklist.push((target, depth, catch_levels.clone()));
9344                }
9345                catch_levels.push(depth_before);
9346                worklist.push((next, depth, catch_levels));
9347            }
9348            // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
9349            // rewind past it too. Its level sits one slot higher than a `catch`'s:
9350            // the iterator and next-method slots occupy the offset's place.
9351            Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
9352                if let Some(target) = target {
9353                    worklist.push((target, depth, catch_levels.clone()));
9354                }
9355                catch_levels.push(depth_before + 1);
9356                worklist.push((next, depth, catch_levels));
9357            }
9358            // `gosub` calls a subroutine with the return address on top. The opcode
9359            // table records no push for it — `ret` is what pops the slot — so the
9360            // extra one is added here, where the depth of the subroutine's first
9361            // instruction is being computed.
9362            Opcode::Gosub => {
9363                if let Some(target) = target {
9364                    worklist.push((target, depth + 1, catch_levels.clone()));
9365                }
9366                worklist.push((next, depth, catch_levels));
9367            }
9368            // `ret` goes back to a `gosub`; nothing here follows it.
9369            Opcode::Ret
9370            | Opcode::Return
9371            | Opcode::ReturnUndef
9372            | Opcode::Throw
9373            | Opcode::ThrowError => {}
9374            _ => worklist.push((next, depth, catch_levels)),
9375        }
9376    }
9377    max_depth
9378}
9379
9380/// Record the stack depth on entry to `pc`, keeping the deeper value if the
9381/// instruction is reachable more than once.
9382fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
9383    let clamped = depth.min(u16::MAX as u32 - 1) as u16;
9384    if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
9385        depth_at[pc] = clamped;
9386    }
9387}
9388
9389fn read_u16(code: &[u8], at: usize) -> u16 {
9390    let mut value = 0u16;
9391    for i in 0..2 {
9392        value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
9393    }
9394    value
9395}
9396
9397/// The absolute target of a jump instruction, if it has one.
9398fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
9399    let info = op.info();
9400    let position = pc + 1;
9401    match info.format {
9402        crate::opcode::OpFormat::Label8 => {
9403            let offset = *code.get(position)? as i8 as i64;
9404            Some((position as i64 + offset) as usize)
9405        }
9406        crate::opcode::OpFormat::Label16 => {
9407            let offset = read_u16(code, position) as i16 as i64;
9408            Some((position as i64 + offset) as usize)
9409        }
9410        crate::opcode::OpFormat::Label => {
9411            let mut offset = 0i32;
9412            for i in 0..4 {
9413                offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
9414            }
9415            Some((position as i64 + offset as i64) as usize)
9416        }
9417        _ => None,
9418    }
9419}
9420
9421fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
9422    use Opcode::*;
9423    match (op, operands.first()) {
9424        (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
9425            op.short_form(*value as u32).unwrap_or(op)
9426        }
9427        (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
9428        (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
9429        (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
9430        | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
9431        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
9432        // A declared global is reached through its reference cell, so it shares
9433        // the `var_ref` encodings, short forms included.
9434        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
9435            op.short_form(*index).unwrap_or(op)
9436        }
9437        (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
9438            op.short_form(*count as u32).unwrap_or(op)
9439        }
9440        _ => op,
9441    }
9442}
9443
9444/// The byte offset each instruction will start at, plus the total code size.
9445fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
9446    let mut offsets = Vec::with_capacity(chosen.len() + 1);
9447    let mut offset = 0usize;
9448    for op in chosen {
9449        offsets.push(offset);
9450        offset += op.size() as usize;
9451    }
9452    offsets.push(offset);
9453    offsets
9454}
9455
9456/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
9457/// the offset actually fits.
9458///
9459/// The choice is circular: an instruction's size decides the offsets of everything after
9460/// it, and the offsets decide whether a jump may be short. So this starts with every jump
9461/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
9462/// Shrinking only ever *shortens* distances, so the loop converges.
9463///
9464/// Doing it in one pass instead — which is what this used to do — silently truncated any
9465/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
9466/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
9467/// with four closures in its body simply stopped, with no error and no output past the
9468/// first iteration.
9469fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
9470    let mut chosen: Vec<Opcode> = kept
9471        .iter()
9472        .map(|(op, operands)| choose_short_form(*op, operands))
9473        .collect();
9474    // A jump the compiler emitted in its widest form, and the forms it may shrink to.
9475    let candidates = |op: Opcode| match op {
9476        Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
9477        Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
9478        Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
9479        _ => None,
9480    };
9481    loop {
9482        let offsets = instruction_offsets(&chosen);
9483        let mut changed = false;
9484        for index in 0..kept.len() {
9485            let (op, operands) = &kept[index];
9486            let Some((short, medium, has_medium)) = candidates(*op) else {
9487                continue;
9488            };
9489            if chosen[index] == short {
9490                continue;
9491            }
9492            let Some(target) = target_kept_index(operands, label_kept) else {
9493                continue;
9494            };
9495            let Some(&target_offset) = offsets.get(target) else {
9496                continue;
9497            };
9498            // A jump is relative to the byte after its opcode, which is the convention
9499            // `jump_target_of` decodes with.
9500            let relative = target_offset as i64 - (offsets[index] as i64 + 1);
9501            if (-128..=127).contains(&relative) {
9502                chosen[index] = short;
9503                changed = true;
9504            } else if has_medium
9505                && chosen[index] == Opcode::Goto
9506                && (-32_768..=32_767).contains(&relative)
9507            {
9508                // Too far for 8 bits and close enough for 16. Only `goto` has a medium
9509                // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
9510                // the reference encodes them.
9511                chosen[index] = medium;
9512                changed = true;
9513            }
9514        }
9515        if !changed {
9516            return chosen;
9517        }
9518    }
9519}
9520
9521fn encode_operands(
9522    code: &mut Vec<u8>,
9523    op: Opcode,
9524    operands: &[Op],
9525    position: usize,
9526    offsets: &[usize],
9527) {
9528    use crate::opcode::OpFormat::*;
9529    let info = op.info();
9530    let write_slot = |code: &mut Vec<u8>, slot: Slot| {
9531        let index = match slot {
9532            Slot::Arg(i)
9533            | Slot::Loc(i)
9534            | Slot::VarRef(i)
9535            | Slot::Global(i)
9536            | Slot::GlobalDecl(i) => i,
9537        };
9538        code.extend_from_slice(&(index as u16).to_be_bytes());
9539    };
9540    match info.format {
9541        None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
9542        U8 | Const8 => {
9543            if let Some(value) = operands.first().and_then(operand_uint) {
9544                code.push(value as u8);
9545            }
9546        }
9547        // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
9548        // like their wide counterparts, only one byte wide.
9549        Loc8 => {
9550            if let Some(Op::Slot(slot)) = operands.first() {
9551                let index = match slot {
9552                    Slot::Arg(i)
9553                    | Slot::Loc(i)
9554                    | Slot::VarRef(i)
9555                    | Slot::Global(i)
9556                    | Slot::GlobalDecl(i) => *i,
9557                };
9558                code.push(index as u8);
9559            }
9560        }
9561        I8 => {
9562            if let Some(value) = operands.first().and_then(operand_int) {
9563                code.push(value as i8 as u8);
9564            }
9565        }
9566        U16 | Npop => {
9567            if let Some(value) = operands.first().and_then(operand_int) {
9568                code.extend_from_slice(&(value as u16).to_be_bytes());
9569            }
9570        }
9571        I16 => {
9572            if let Some(value) = operands.first().and_then(operand_int) {
9573                code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
9574            }
9575        }
9576        I32 => {
9577            if let Some(value) = operands.first().and_then(operand_int) {
9578                code.extend_from_slice(&value.to_be_bytes());
9579            }
9580        }
9581        U32 | Const => {
9582            if let Some(value) = operands.first().and_then(operand_uint) {
9583                code.extend_from_slice(&value.to_be_bytes());
9584            }
9585        }
9586        Loc | Arg | VarRef => {
9587            if let Some(Op::Slot(slot)) = operands.first() {
9588                write_slot(code, *slot);
9589            }
9590        }
9591        Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
9592            if let Some(Op::AtomId(index)) = operands.first() {
9593                code.extend_from_slice(&index.to_be_bytes());
9594            }
9595            // The trailing immediate means different things per format, and the
9596            // atom forms that carry a *label* have to resolve it like any other
9597            // jump, so they cannot share the `U8`/`U16` arms above.
9598            match info.format {
9599                AtomU8 | AtomLabelU8 => {
9600                    if let Some(value) = operands.get(1).and_then(operand_uint) {
9601                        code.push(value as u8);
9602                    }
9603                }
9604                AtomU16 | AtomLabelU16 => {
9605                    if let Some(value) = operands.get(1).and_then(operand_uint) {
9606                        code.extend_from_slice(&(value as u16).to_be_bytes());
9607                    }
9608                }
9609                _ => {}
9610            }
9611        }
9612        NpopU16 => {
9613            for operand in operands.iter().take(2) {
9614                if let Some(value) = operand_uint(operand) {
9615                    code.extend_from_slice(&(value as u16).to_be_bytes());
9616                }
9617            }
9618        }
9619        Label | Label8 | Label16 | LabelU16 => {
9620            if let Some(Op::Label(label)) = operands.first() {
9621                // Labels were already remapped to kept-instruction indices.
9622                let Some(&target) = offsets.get(label.0 as usize) else {
9623                    debug_assert!(false, "label {} is past the end", label.0);
9624                    return;
9625                };
9626                let relative = target as i64 - (position as i64 + 1);
9627                match info.format {
9628                    Label8 => code.push(relative as i8 as u8),
9629                    Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
9630                    // `label_u16` stores the target followed by an unrelated u16.
9631                    LabelU16 => {
9632                        code.extend_from_slice(&(relative as i32).to_be_bytes());
9633                        if let Some(value) = operands.get(1).and_then(operand_uint) {
9634                            code.extend_from_slice(&(value as u16).to_be_bytes());
9635                        }
9636                    }
9637                    _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
9638                }
9639            }
9640        }
9641    }
9642}
9643
9644fn operand_int(op: &Op) -> Option<i32> {
9645    match op {
9646        Op::Int(value) => Some(*value),
9647        _ => None,
9648    }
9649}
9650
9651fn operand_uint(op: &Op) -> Option<u32> {
9652    match op {
9653        Op::Const(value) | Op::AtomId(value) => Some(*value),
9654        Op::Int(value) => Some(*value as u32),
9655        _ => None,
9656    }
9657}
9658
9659/// Disassemble a compiled function.
9660pub fn disassemble(function: &CompiledFunction) -> String {
9661    disasm::disassemble_program(function)
9662}