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    /// The function's own source range, used to record its text for
467    /// `Function.prototype.toString`.
468    span: Option<(usize, usize)>,
469    name: String,
470    kind: FunctionKind,
471    strict: bool,
472    args: Vec<VarDef>,
473    vars: Vec<VarDef>,
474    closure_vars: Vec<ClosureVar>,
475    cpool: Vec<Constant>,
476    atoms: Vec<Atom>,
477    /// Every lexical scope, in creation order.
478    blocks: Vec<Block>,
479    /// The block currently being parsed or compiled.
480    current_block: u64,
481    /// The block a *nested* function was created in, so a capture made from here can be
482    /// resolved against the enclosing function's lexical scopes rather than against a
483    /// flat name table. Without it, `function f(){ class S{} }` capturing `S` found the
484    /// function's own `let S` instead of the class body's `const S`.
485    created_in_block: u64,
486    /// The block each local was declared in, parallel to `vars`. `0` means the
487    /// function scope, where `var` bindings live.
488    var_block: Vec<u64>,
489    /// Set when the expression just compiled left no value on the stack.
490    ///
491    /// Only a store can do that: `put_field` consumes the object and the value, so
492    /// an assignment whose result is unused emits nothing extra. The expression
493    /// statement then has nothing to drop.
494    no_value: bool,
495    /// Whether a label was placed since the last instruction was emitted.
496    ///
497    /// The `put`/`get` fold is only valid when the two are adjacent in the final
498    /// stream; a label in between means a jump can land on the read, so the store has
499    /// to keep consuming its value. A flag is enough and avoids having to reason about
500    /// which index a label recorded.
501    label_since_insn: bool,
502    /// Whether the value of the expression being compiled is thrown away.
503    ///
504    /// Only an expression *statement* discards its value, and only the outermost
505    /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
506    /// still has to produce a value. Consumed by [`Compiler::assign`], which is
507    /// the one construct whose bytecode depends on it.
508    discard_value: bool,
509    /// The block that holds the function body.
510    body_block: u64,
511    /// Head of each scope's binding chain, indexed by level. Filled in by
512    /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
513    block_heads: Vec<i32>,
514    /// Enclosing `break`/`continue` targets, innermost last.
515    jump_targets: Vec<JumpTarget>,
516    insns: Vec<Insn>,
517    labels: Vec<Option<usize>>,
518    /// Captured locals, which need a reference cell.
519    var_ref_count: u32,
520    line: u32,
521    column: u32,
522    /// Whether this is a script body. A script's top-level declarations create
523    /// global properties rather than locals, which is why they show up as
524    /// closure variables with `[global_decl]`.
525    is_script: bool,
526    /// Whether this is a module body.
527    ///
528    /// A module body is a script in every respect that matters here — no `arguments`,
529    /// no `this` of its own — but its top-level declarations are *module*-scoped
530    /// instead of global, which is what this flag changes.
531    is_module: bool,
532    /// Whether the function is an arrow, which never gets its own `arguments`.
533    is_arrow: bool,
534    /// The name a *named function expression* binds inside its own body.
535    /// How many parameters count towards `.length`.
536    defined_args: u32,
537    /// Parameters that are not a plain name, with the argument slot each came from.
538    param_prologue: Vec<(usize, Pattern)>,
539    /// What kind of class constructor this function is, if any.
540    ctor_kind: CtorKind,
541    /// Whether the class has instance fields, so the constructor has to run their
542    /// initialiser before it returns.
543    /// What the nested function about to be compiled should be told about its class.
544    class_ctor_pending: Option<CtorKind>,
545    /// Whether this function needs the hidden `this` local, because an arrow inside it
546    /// refers to `this`.
547    ///
548    /// An arrow has no `this` of its own, so the reference materialises the enclosing
549    /// function's receiver into a local and lets the arrow capture it as an ordinary
550    /// closure variable. Declaring the local is not enough on its own: the store that
551    /// fills it has to be prepended to the body, which is what this flag arranges.
552    needs_this_local: bool,
553    /// The same, for `arguments`.
554    needs_arguments_local: bool,
555    /// The same, for `new.target`.
556    needs_new_target_local: bool,
557    /// Whether the body already opens by filling a `this` local, which
558    /// [`Compiler::begin_this_local`] does for a constructor and a field initialiser.
559    has_this_prologue: bool,
560    /// The same, for `<home_object>`: the object `super` resolves against.
561    ///
562    /// An arrow and a static block have no home object of their own — only the method or
563    /// initialiser they were written in does — so `super.x` inside one is a read of the
564    /// enclosing function's `[[HomeObject]]`. The value is materialised into a local there
565    /// by `special_object 4`, the same way `this` is.
566    needs_home_object_local: bool,
567    /// The same, for `this.active_func`: the function `super()` constructs from.
568    ///
569    /// An arrow has no `super` of its own, so it reads the enclosing function's — and that
570    /// is a *lexical* relationship, not a stack one. The reference keeps `this_active_func`
571    /// as a local of the enclosing function; an arrow that escaped the constructor
572    /// (`iter.return = () => super()`) then finds it in its closure even with the
573    /// constructor nowhere on the call stack.
574    needs_active_func_local: bool,
575    /// Hidden locals of the `with` blocks currently open, innermost last.
576    with_names: Vec<String>,
577    /// Set while a with-guard is being emitted, so the guard's own accesses are not
578    /// wrapped in another guard.
579    emitting_with_guard: bool,
580    self_name: Option<String>,
581    /// Where the function body starts, in source order; see [`Function::body_start`].
582    body_start: (u32, u32),
583    /// Whether the body contains a *direct* `eval(...)` call.
584    ///
585    /// A direct eval sees every binding of the function that called it, including ones
586    /// no other code mentions. It also hands those bindings to any closure it creates,
587    /// which can outlive the function. Both need the bindings to live in cells, so this
588    /// flag makes the function treat all of them as captured.
589    has_direct_eval: bool,
590    /// Whether the parameter list contains a default expression, which is what gives
591    /// the function a second variable environment (see [`PARAM_SCOPE`]).
592    has_parameter_expressions: bool,
593    /// `IsSimpleParameterList`: every parameter is a plain binding identifier.
594    simple_parameter_list: bool,
595    /// Whether the instructions being emitted belong to the parameter list.
596    ///
597    /// References made here must not see the body's `var`s: the body has not run yet,
598    /// and the reference's own model keeps the two scopes apart.
599    in_params: bool,
600    /// Whether an arrow created in this function's parameter list needs the parameter
601    /// scope's `arguments` binding.
602    needs_param_arguments: bool,
603    /// Whether this function was *created* inside a parameter list.
604    ///
605    /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
606    /// arrow too. The name reference is the arrow's, but the scope it must not see
607    /// belongs to the function the arrow was born in.
608    created_in_params: bool,
609    /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
610    ///
611    /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
612    /// final while the body is still being compiled: a named function expression declares
613    /// its own name binding *after* the body, and that binding is exactly what
614    /// `eval("myfunc = 1")` has to find.
615    eval_sites: Vec<EvalSite>,
616    /// Direct `eval` call sites seen so far: where, and the block that was current.
617    pending_eval_sites: Vec<(Span, u64, bool)>,
618    /// Whether this body contains `await`.
619    ///
620    /// For a *module* this decides whether its body is an async function: top-level
621    /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
622    /// to survive to the compiled function rather than being a local of the compiler.
623    has_await: bool,
624    /// The module tables, when this body is a module.
625    ///
626    /// Only the top-level state ever has one: `export` and `import` are top-level
627    /// statements, so nothing nested can add to these tables.
628    module: Option<ModuleMeta>,
629    /// Whether the self-name prologue (`special_object 2` then the store) has been
630    /// emitted for this function.
631    ///
632    /// A *nested* function's lookup declares the binding early (see
633    /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
634    /// prologue is still needed — the binding existing is not the same as it being
635    /// initialised.
636    self_name_initialized: bool,
637    /// Whether the code emitted so far leaves the program's result on the stack.
638    /// The reference tracks this for the hidden `<ret>` local of an eval script.
639    leaves_value: bool,
640    /// Statement nesting depth, used to tell top-level statements apart.
641    stmt_depth: u32,
642    /// Function declarations waiting to be instantiated at scope entry, as
643    /// (target slot, constant pool index). The reference emits these from
644    /// `instantiate_hoisted_definitions` rather than at the statement, because a
645    /// declaration is visible before it is reached.
646    hoisted: Vec<(u64, HoistTarget, u32)>,
647    /// Function declarations whose bodies are compiled only once the enclosing scope
648    /// has finished hoisting, as (owning block, declaration).
649    ///
650    /// Compiling a body at the declaration makes the result depend on source order: in
651    /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
652    /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
653    /// names first and the bodies second is what removes that dependence.
654    deferred_funcs: Vec<(u64, Box<ast::Function>)>,
655    /// The source position of the node being compiled. Every instruction emitted
656    /// takes it, which is how the position table that feeds stack traces is built.
657    cur_pos: Option<Position>,
658    /// One position per entry in `insns`, index-aligned.
659    insn_pos: Vec<Option<Position>>,
660}
661
662/// Where a hoisted function declaration is stored.
663#[derive(Debug, Clone)]
664enum HoistTarget {
665    Arg(u32),
666    Loc(u32),
667    /// A global, which the resolver looks up by name.
668    Global(String),
669}
670
671impl FnState {
672    /// Whether this function suspends: a generator or an async function.
673    ///
674    /// A suspending function's `return` is a `return_async` and its body starts with an
675    /// `initial_yield`, so almost every statement that touches control flow asks this.
676    fn is_suspending(&self) -> bool {
677        self.kind.is_generator() || self.kind.is_async()
678    }
679
680    fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
681        FnState {
682            span: None,
683            name: name.into(),
684            kind,
685            strict: false,
686            args: Vec::new(),
687            vars: Vec::new(),
688            closure_vars: Vec::new(),
689            cpool: Vec::new(),
690            atoms: Vec::new(),
691            blocks: Vec::new(),
692            current_block: 0,
693            created_in_block: NO_PARENT,
694            var_block: Vec::new(),
695            no_value: false,
696            label_since_insn: false,
697            discard_value: false,
698            body_block: 0,
699            block_heads: Vec::new(),
700            jump_targets: Vec::new(),
701            insns: Vec::new(),
702            labels: Vec::new(),
703            var_ref_count: 0,
704            line: 1,
705            column: 1,
706            is_script: false,
707            is_module: false,
708            is_arrow: false,
709            defined_args: 0,
710            param_prologue: Vec::new(),
711            ctor_kind: CtorKind::None,
712            class_ctor_pending: None,
713            needs_this_local: false,
714            needs_arguments_local: false,
715            needs_new_target_local: false,
716            has_this_prologue: false,
717            needs_home_object_local: false,
718            needs_active_func_local: false,
719            with_names: Vec::new(),
720            emitting_with_guard: false,
721            self_name: None,
722            has_direct_eval: false,
723            body_start: (0, 0),
724            has_parameter_expressions: false,
725            simple_parameter_list: true,
726            in_params: false,
727            needs_param_arguments: false,
728            created_in_params: false,
729            eval_sites: Vec::new(),
730            pending_eval_sites: Vec::new(),
731            has_await: false,
732            module: None,
733            self_name_initialized: false,
734            leaves_value: false,
735            stmt_depth: 0,
736            hoisted: Vec::new(),
737            deferred_funcs: Vec::new(),
738            cur_pos: None,
739            insn_pos: Vec::new(),
740        }
741    }
742
743    /// The scope a declaration lands in: a script's top-level declarations are
744    /// globals, everything else gets a slot.
745    /// Whether a binding declared *now* becomes a property of the global object.
746    ///
747    /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
748    /// The `var` case is decided by the keyword rather than by the cursor position:
749    /// `var` is function-scoped, so a `var i` in a `for` head is still the same
750    /// binding as a `var i` in the body, even though the head has its own block.
751    fn declares_globally(&self, def: &VarDef) -> bool {
752        // A module's top-level declarations are *module*-scoped: they live in the module
753        // record, never on the global object. Two modules can both declare `var x`
754        // without seeing each other, which is the whole point.
755        if self.is_module {
756            return false;
757        }
758        self.is_script && (!def.is_lexical || self.current_block == self.body_block)
759    }
760}
761
762/// The compiler's entry point.
763pub struct Compiler {
764    /// The text being compiled, kept so each function can record its own slice for
765    /// `Function.prototype.toString`.
766    source: Option<String>,
767    module: bool,
768    /// Whether the program itself is the body of an `async` function.
769    ///
770    /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
771    /// completion value is wrapped so a returned promise is not adopted.
772    async_body: bool,
773    /// Enclosing functions, outermost first. The last entry is the current one.
774    stack: Vec<FnState>,
775    /// The private names visible at this point, innermost class body last.
776    ///
777    /// A stack rather than a field of `FnState` because a private name is *lexically* scoped
778    /// to the class body: a method, an arrow inside it and a class nested inside that arrow
779    /// all resolve against the same entries, and the parser accepts exactly that set
780    /// (`self.private` in `parser.rs`). `FnState` is per-function, so it would lose the outer
781    /// class's names the moment a method started.
782    private_scopes: Vec<std::collections::HashMap<String, PrivateUse>>,
783    /// Whether the expression [`Compiler::expr`] is about to compile is the one its
784    /// statement asked to discard.
785    ///
786    /// `FnState::discard_value` says "the statement's value is thrown away", which is only
787    /// ever true of the statement's own expression — an assignment nested inside it, as in
788    /// `f(x = 1)`, has a value that is very much used. Clearing the flag on the way in and
789    /// keeping the answer here is what tells the two apart; without it the nested store
790    /// consumed its value, `call` took the callee as its argument, and `f(x = 1)` inside a
791    /// function threw `undefined is not a function`.
792    discard_root: bool,
793}
794
795/// How a use site of a private name compiles.
796///
797/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
798/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
799/// of a setter-only accessor pair.
800#[derive(Clone, Copy, PartialEq, Eq)]
801enum PrivateKind {
802    /// `#x = 1`: an own property keyed by the symbol in the binding.
803    Field,
804    /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
805    Method,
806    /// `get #a() {}`: the binding holds the getter, and a read calls it.
807    Getter,
808    /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
809    /// the same `TypeError` as reading an uninitialised `const`.
810    Setter,
811}
812
813/// What the compiler knows about one `#name` where it is used.
814#[derive(Clone)]
815struct PrivateUse {
816    kind: PrivateKind,
817    /// `#a<set>` when the class defines a setter for this name.
818    ///
819    /// A second binding, not a second field of the first: the reference stores the setter
820    /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
821    setter: Option<String>,
822}
823
824/// The class-scope bindings one class body needs, in declaration order.
825#[derive(Default)]
826struct ClassPlan {
827    /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
828    /// at class entry, in member order.
829    bindings: Vec<String>,
830    /// The private names, for the use sites inside the body.
831    uses: std::collections::HashMap<String, PrivateUse>,
832    /// Computed field keys, by element index, so the emission pass does not have to redo the
833    /// per-half counter that names them.
834    computed: std::collections::HashMap<usize, String>,
835    /// Whether the instance initialiser has to add the brand to `this`.
836    instance_brand: bool,
837    /// Whether the constructor itself has to carry the brand.
838    static_brand: bool,
839}
840
841impl ClassPlan {
842    /// Walk a class body once and decide every class-scope binding it needs.
843    ///
844    /// Order is the reference's: a member's binding is created when the member is parsed, so
845    /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
846    /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
847    /// the disassembly stops matching even when every instruction is right.
848    fn build(class: &Class) -> ClassPlan {
849        let mut plan = ClassPlan::default();
850        let mut instance_keys = 0usize;
851        let mut static_keys = 0usize;
852        for (index, element) in class.elements.iter().enumerate() {
853            match element {
854                ClassElement::Method {
855                    key: PropName::Private(ident),
856                    kind,
857                    is_static,
858                    ..
859                } => {
860                    let name = format!("#{}", ident.name);
861                    let first = !plan.uses.contains_key(&name);
862                    if first {
863                        plan.bindings.push(name.clone());
864                        plan.uses.insert(
865                            name.clone(),
866                            PrivateUse {
867                                kind: match kind {
868                                    MethodKind::Get => PrivateKind::Getter,
869                                    MethodKind::Set => PrivateKind::Setter,
870                                    _ => PrivateKind::Method,
871                                },
872                                setter: None,
873                            },
874                        );
875                    }
876                    match kind {
877                        MethodKind::Set => {
878                            let binding = format!("{name}<set>");
879                            plan.bindings.push(binding.clone());
880                            if let Some(use_) = plan.uses.get_mut(&name) {
881                                use_.setter = Some(binding);
882                            }
883                        }
884                        // A getter is what makes the name readable, so a pair that started
885                        // as a setter becomes readable once the getter arrives.
886                        MethodKind::Get => {
887                            if let Some(use_) = plan.uses.get_mut(&name) {
888                                use_.kind = PrivateKind::Getter;
889                            }
890                        }
891                        _ => {}
892                    }
893                    if *is_static {
894                        plan.static_brand = true;
895                    } else {
896                        plan.instance_brand = true;
897                    }
898                }
899                ClassElement::Method {
900                    key: PropName::Computed(_),
901                    ..
902                } => {}
903                ClassElement::Method { .. } => {}
904                ClassElement::Field {
905                    key: PropName::Private(ident),
906                    ..
907                } => {
908                    let name = format!("#{}", ident.name);
909                    if !plan.uses.contains_key(&name) {
910                        plan.bindings.push(name.clone());
911                        plan.uses.insert(
912                            name,
913                            PrivateUse {
914                                kind: PrivateKind::Field,
915                                setter: None,
916                            },
917                        );
918                    }
919                }
920                ClassElement::Field {
921                    key: PropName::Computed(_),
922                    is_static,
923                    ..
924                } => {
925                    let index_in_half = if *is_static {
926                        static_keys += 1;
927                        static_keys - 1
928                    } else {
929                        instance_keys += 1;
930                        instance_keys - 1
931                    };
932                    let binding = computed_field_binding(index_in_half, *is_static);
933                    plan.bindings.push(binding.clone());
934                    plan.computed.insert(index, binding);
935                }
936                ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
937            }
938        }
939        plan
940    }
941
942    /// How a private name used inside the body compiles, or `None` if no enclosing class
943    /// declares it.
944    fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
945        compiler
946            .private_scopes
947            .iter()
948            .rev()
949            .find_map(|scope| scope.get(name))
950    }
951}
952
953impl Compiler {
954    /// The exact source text of a function, for `Function.prototype.toString`.
955    ///
956    /// §20.2.3.5 requires the *original* text: a function must stringify back to what
957    /// was written, comments and odd spacing included. Slicing the recorded span out of
958    /// the whole source is the only way to get that — rebuilding it from the AST would
959    /// normalise the text, and answering `[native code]` for a script function (which is
960    /// what this engine used to do) makes the result useless for feature detection and
961    /// for libraries that read their own source.
962    ///
963    /// Top-level bodies have no single expression span, so their `source` stays `None`
964    /// and `toString` falls back to the calling convention the spec allows.
965    fn function_source(
966        &self,
967        span: Option<(usize, usize)>,
968        line: u32,
969        column: u32,
970    ) -> Option<String> {
971        let source = self.source.as_ref()?;
972        let span = span?;
973        let bytes = source.as_bytes();
974        let start = span.0;
975        let end = span.1;
976        if start >= bytes.len() || end > bytes.len() || start >= end {
977            let _ = (line, column);
978            return None;
979        }
980        Some(source.get(start..end)?.to_string())
981    }
982}
983
984/// Compile a script.
985pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
986    Compiler::new(false).compile(program)
987}
988
989/// Compile a script, keeping its text so `Function.prototype.toString` can answer with
990/// the original source.
991///
992/// The separate entry point rather than a parameter on [`compile_script`] because the
993/// tests and the disassembler compile from an AST they built themselves and have no
994/// source to give; they keep the `None` behaviour they already relied on.
995pub fn compile_script_with_source(
996    program: &Program,
997    source: &str,
998) -> Result<CompiledFunction, SyntaxError> {
999    let mut compiler = Compiler::new(false);
1000    compiler.source = Some(source.to_string());
1001    compiler.compile(program)
1002}
1003
1004/// [`compile_script_with_source`] for a module.
1005pub fn compile_module_with_source(
1006    program: &Program,
1007    source: &str,
1008) -> Result<CompiledFunction, SyntaxError> {
1009    let mut compiler = Compiler::new(true);
1010    compiler.source = Some(source.to_string());
1011    compiler.compile(program)
1012}
1013
1014/// Compile a script whose top level is the body of an `async` function.
1015///
1016/// The body is an ordinary script in every other way — it still reports a completion value
1017/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
1018/// it answers a promise instead of a value. The wrapper is what keeps that promise from
1019/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
1020/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
1021/// documents.
1022pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1023    Compiler::for_suspensible_script().compile(program)
1024}
1025
1026/// Compile a module.
1027pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1028    Compiler::new(true).compile(program)
1029}
1030
1031impl Compiler {
1032    /// Create a compiler.
1033    pub fn new(module: bool) -> Compiler {
1034        Compiler {
1035            source: None,
1036            module,
1037            async_body: false,
1038            stack: Vec::new(),
1039            private_scopes: Vec::new(),
1040            discard_root: false,
1041        }
1042    }
1043
1044    /// Create a compiler for a script whose top level is an `async` function body.
1045    fn for_suspensible_script() -> Compiler {
1046        Compiler {
1047            source: None,
1048            module: false,
1049            async_body: true,
1050            stack: Vec::new(),
1051            private_scopes: Vec::new(),
1052            discard_root: false,
1053        }
1054    }
1055
1056    /// Compile a whole program into its top-level function.
1057    pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
1058        let mut state = FnState::new("<eval>", FunctionKind::Normal);
1059        // A module body is *not* a script: it has no completion value, so no hidden
1060        // `<ret>` local and no `put_loc0` before each statement. What it shares with one
1061        // is having no `arguments` of its own and no receiver — see `is_module`.
1062        state.is_script = !self.module;
1063        state.is_module = self.module;
1064        if self.module {
1065            state.module = Some(ModuleMeta::default());
1066        }
1067        state.strict = program.strict || self.module;
1068        state.line = program.span.start.line;
1069        state.column = program.span.start.column;
1070        // Locals are numbered in declaration order; `<ret>` is always slot 0.
1071        //
1072        // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
1073        // slot that only appears in one of the two arrays shifts every later
1074        // binding's block and silently loses the temporal-dead-zone marking for
1075        // the script's own blocks. A function frame has no `<ret>`, which is why
1076        // the misalignment only showed up at the top level.
1077        if !self.module {
1078            state.vars.push(VarDef::var("<ret>"));
1079            state.var_block.push(FUNCTION_SCOPE);
1080        }
1081        self.stack.push(state);
1082        // The body is its own scope, keyed by the position of the program.
1083        // The script body needs a key no statement can produce. Statement keys are
1084        // source offsets, and the program's own start offset is `0` — which is also
1085        // the offset of the first statement, so a top-level `{ let x }` or
1086        // `for (let i …)` used to share the body's block and lose its scope.
1087        let body_key = SCRIPT_BODY;
1088        self.push_block(body_key, NO_PARENT);
1089        self.state().body_block = body_key;
1090        // A module body opens with a re-entry guard. The host evaluates a module exactly
1091        // once, so the guard never fires in practice — but the reference emits it, and a
1092        // module function called a second time (through `eval` of its own source, say)
1093        // must not run its body again.
1094        let module_guard = self.module.then(|| self.new_label());
1095        if let Some(body) = module_guard {
1096            // The guard wraps the *hoisting* too: a second evaluation of the same module
1097            // body must not even re-create its function declarations.
1098            self.emit(Opcode::PushThis, &[]);
1099            self.emit_jump(Opcode::IfFalse, body, &[]);
1100        }
1101        self.hoist(&program.body, body_key)?;
1102        // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
1103        // come before the guard's `return_undef`: the reference's jump target sits past
1104        // both, and a second evaluation therefore re-creates nothing.
1105        self.emit_scope_enter(body_key);
1106        if let Some(body) = module_guard {
1107            self.emit(Opcode::ReturnUndef, &[]);
1108            self.place_label(body);
1109        }
1110        // Through `stmts` rather than the loop, so a `using` region at the top level of an
1111        // eval'd body or a module gets its disposal epilogue like any other block.
1112        self.stmts(&program.body)?;
1113        if self.module {
1114            // A module has no completion value; its body simply ends.
1115            self.emit(Opcode::Undefined, &[]);
1116            self.emit(Opcode::ReturnAsync, &[]);
1117            // Top-level `await` makes the body an async function, so the host runs it as
1118            // a coroutine and waits. Without this the `await` opcode would suspend in a
1119            // body that nothing knows how to resume — which is what "a generator body ran
1120            // as an ordinary call" was reporting.
1121            if self.cur().has_await {
1122                self.state().kind = FunctionKind::Async;
1123            }
1124        } else if self.async_body {
1125            // An async body reports its completion value the same way, but through an
1126            // object: the function answers a promise, and resolving that promise *with*
1127            // the completion value would adopt a promise completion instead of reporting
1128            // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
1129            // resolve to `{value: <promise>}` rather than to `7`.
1130            //
1131            // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
1132            // value in an object so that promises can be safely returned").
1133            self.emit(Opcode::Object, &[]);
1134            self.emit(Opcode::Dup, &[]);
1135            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1136            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
1137            self.emit(Opcode::Return, &[]);
1138            self.state().kind = FunctionKind::Async;
1139        } else {
1140            // The program's value is whatever the last expression statement stored in
1141            // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
1142            // case into a single `set_loc0`.
1143            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1144            self.emit(Opcode::Return, &[]);
1145        }
1146        Ok(self.finish_current())
1147    }
1148
1149    // -- emitting ----------------------------------------------------------
1150
1151    fn state(&mut self) -> &mut FnState {
1152        self.stack.last_mut().expect("a function is being compiled")
1153    }
1154
1155    fn cur(&self) -> &FnState {
1156        self.stack.last().expect("a function is being compiled")
1157    }
1158
1159    fn emit(&mut self, op: Opcode, operands: &[Op]) {
1160        self.state().label_since_insn = false;
1161        let pos = self.cur().cur_pos;
1162        self.state().insns.push(Insn::Fixed {
1163            op,
1164            operands: operands.to_vec(),
1165        });
1166        self.state().insn_pos.push(pos);
1167    }
1168
1169    /// Reset the script's hidden return value to `undefined`.
1170    ///
1171    /// Called at the start of every statement that does not itself produce the
1172    /// program's value, which is how the reference keeps `if`/loop results from
1173    /// leaking into an eval result.
1174    fn reset_value(&mut self) {
1175        if !self.cur().is_script {
1176            return;
1177        }
1178        self.emit(Opcode::Undefined, &[]);
1179        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1180        self.state().leaves_value = false;
1181    }
1182
1183    /// Whether `name` is a local or argument slot rather than a global.
1184    fn is_slot(&self, name: &str) -> bool {
1185        self.cur().vars.iter().any(|v| v.name == name)
1186            || self.cur().args.iter().any(|a| a.name == name)
1187    }
1188
1189    /// `with (object) body`
1190    ///
1191    /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
1192    /// what makes the object reachable from a closure created inside the block, and it
1193    /// is also what lets an `eval` find it: the runtime collects the active `With`
1194    /// locals of every frame and resolves names against them before the realm.
1195    ///
1196    /// Inside the block every name reference is spelled as "look in the with objects
1197    /// first", innermost outwards, and falls through to the ordinary access. The test is
1198    /// `in`, which is `HasProperty` — the same question the spec's Object Environment
1199    /// Record asks.
1200    fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
1201        let name = self.next_with_name();
1202        // The object expression is evaluated *outside* the scope it introduces, so no
1203        // wrapper may be emitted for the names it mentions.
1204        let saved = std::mem::take(&mut self.state().with_names);
1205        self.expr(object)?;
1206        self.state().with_names = saved;
1207        self.emit(Opcode::ToObject, &[]);
1208        self.declare_hidden_local(&name, VarKind::With);
1209        // Pushed before the store so the store itself is not guarded by an *outer*
1210        // `with` — the object being stored is the new one, not something to look up.
1211        self.state().with_names.push(name.clone());
1212        self.emit_var(VarAction::Put, &name);
1213        let result = self.stmt(body);
1214        self.state().with_names.pop();
1215        result
1216    }
1217
1218    /// A hidden-local name for one `with` block, distinct from every enclosing one.
1219    fn next_with_name(&self) -> String {
1220        let depth = self.cur().with_names.len();
1221        if depth == 0 {
1222            "<with>".to_string()
1223        } else {
1224            format!("<with{depth}>")
1225        }
1226    }
1227
1228    /// Declare a hidden local that must stay a *local* even in a script.
1229    ///
1230    /// A script's `var` is a property of the global object, but the `with` object is not
1231    /// part of the source program's name space at all — it only exists for the compiler
1232    /// and the runtime — so it goes straight into the frame's slot list.
1233    fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
1234        let state = self.state();
1235        if state.vars.iter().any(|v| v.name == name) {
1236            return;
1237        }
1238        state.var_block.push(FUNCTION_SCOPE);
1239        state.vars.push(VarDef {
1240            kind,
1241            ..VarDef::var(name)
1242        });
1243    }
1244
1245    /// Emit a name access, guarded by every active `with` object.
1246    ///
1247    /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
1248    /// the read itself; the outer guards and the plain access are what the `if_false`
1249    /// jumps to, so the innermost object wins.
1250    fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
1251        let names = self.cur().with_names.clone();
1252        let done = self.new_label();
1253        let mut starts = Vec::new();
1254        // Innermost object first: the last `with` opened is the one that shadows the
1255        // others, so its guard has to be the first chance to satisfy the name.
1256        for with_name in names.iter().rev() {
1257            let next = self.new_label();
1258            // `in` takes the key then the object.
1259            self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1260            self.emit_var(VarAction::Get, with_name);
1261            self.emit(Opcode::In, &[]);
1262            self.emit_jump(Opcode::IfFalse, next, &[]);
1263            starts.push(next);
1264            match action {
1265                // A store keeps the value under the receiver, which is where
1266                // `put_field` expects it.
1267                VarAction::Put | VarAction::PutInit => {
1268                    self.emit_var(VarAction::Get, with_name);
1269                    self.emit(Opcode::Swap, &[]);
1270                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(name))]);
1271                }
1272                _ => {
1273                    self.emit_var(VarAction::Get, with_name);
1274                    self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1275                    self.emit(Opcode::GetArrayEl, &[]);
1276                }
1277            }
1278            self.emit_jump(Opcode::Goto, done, &[]);
1279            self.place_label(next);
1280        }
1281        self.emit_var(action, name);
1282        self.place_label(done);
1283    }
1284
1285    fn emit_var(&mut self, action: VarAction, name: &str) {
1286        // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
1287        // stores and keeps the value in one instruction. The reference does this
1288        // in a post-pass; folding it at emit time keeps instruction indices
1289        // stable, which matters because labels are recorded as indices.
1290        //
1291        // Only slots have a `set_` form: a global is stored with `put_var` and
1292        // read with `get_var`, and the reference does not fold those.
1293        //
1294        // A label between the two cancels the fold. `set_x v` leaves the value on
1295        // the stack, which is only equivalent when the read immediately follows the
1296        // store; when a jump target sits in between, the store must *consume* the
1297        // value and the read must fetch it afresh. A loop head is exactly that
1298        // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
1299        // condition re-reads it — and folding across the label would make the
1300        // condition compare whatever the previous iteration left on the stack.
1301        if action == VarAction::Get {
1302            let is_slot = self.is_slot(name);
1303            let at_label = std::mem::take(&mut self.state().label_since_insn);
1304            //
1305            // `arguments` is excluded because the reference treats it as a special
1306            // binding: it is initialised once and read many times, and folding its
1307            // initialisation into a `set_` would leave the object on the stack where
1308            // the reference leaves nothing.
1309            if is_slot
1310                && name != "arguments"
1311                && !at_label
1312                && let Some(Insn::Var {
1313                    action: previous,
1314                    name: previous_name,
1315                    ..
1316                }) = self.state().insns.last_mut()
1317                && *previous == VarAction::Put
1318                && previous_name == name
1319            {
1320                *previous = VarAction::Set;
1321                return;
1322            }
1323        }
1324        // Inside a `with`, every name lookup consults the with objects first. The
1325        // hidden `<with…>` locals themselves are exempt, or the guard would recurse.
1326        let guarded = !self.cur().with_names.is_empty()
1327            && !self.cur().with_names.iter().any(|hidden| hidden == name)
1328            && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1329            && !self.state().emitting_with_guard;
1330        if guarded {
1331            self.state().emitting_with_guard = true;
1332            self.emit_with_guarded(action, name);
1333            self.state().emitting_with_guard = false;
1334            return;
1335        }
1336        let block = self.cur().current_block;
1337        self.state().label_since_insn = false;
1338        let pos = self.cur().cur_pos;
1339        let in_params = self.cur().in_params;
1340        self.state().insns.push(Insn::Var {
1341            action,
1342            name: name.to_string(),
1343            block,
1344            in_params,
1345        });
1346        self.state().insn_pos.push(pos);
1347    }
1348
1349    fn new_label(&mut self) -> Label {
1350        let state = self.state();
1351        state.labels.push(None);
1352        Label(state.labels.len() as u32 - 1)
1353    }
1354
1355    fn place_label(&mut self, label: Label) {
1356        let index = self.cur().insns.len();
1357        self.state().label_since_insn = true;
1358        self.state().labels[label.0 as usize] = Some(index);
1359    }
1360
1361    fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1362        let mut operands = vec![Op::Label(label)];
1363        operands.extend_from_slice(extra);
1364        self.emit(op, &operands);
1365    }
1366
1367    // -- scopes ------------------------------------------------------------
1368
1369    /// Start a new lexical scope inside `parent`.
1370    fn push_block(&mut self, key: u64, parent: u64) {
1371        let state = self.state();
1372        if !state.blocks.iter().any(|b| b.key == key) {
1373            state.blocks.push(Block { key, parent });
1374        }
1375        state.current_block = key;
1376    }
1377
1378    /// Emit the code that runs when a lexical scope is entered.
1379    ///
1380    /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1381    /// so entering its block marks it uninitialised. Hoisted function
1382    /// declarations are created here instead, which is why a call before the
1383    /// declaration still works.
1384    ///
1385    /// The order is not obvious: bindings are emitted in *reverse* declaration
1386    /// order, because the reference walks its scope chain, which is built by
1387    /// prepending.
1388    fn emit_scope_enter(&mut self, block: u64) {
1389        // Only *this* scope's hoisted declarations are consumed here; the rest stay in the
1390        // list for the scope that owns them. `std::mem::take` used to empty the whole list,
1391        // so entering an outer scope threw away every nested block's function
1392        // declarations: `function h(){ { function k(){} } return k; }` answered
1393        // `undefined`, and `{ function g(){} }` was `undefined` even *inside* the block.
1394        // That is one Annex B rule the engine otherwise implements (a sloppy-mode function
1395        // in a block is also a `var` of the enclosing function), and it is what makes the
1396        // `for (const ctor of ctors) { function f(){} … }` shape in test262 work.
1397        let mut hoisted = std::mem::take(&mut self.state().hoisted);
1398        let mut rest = Vec::with_capacity(hoisted.len());
1399        let mut mine: Vec<(HoistTarget, u32)> = Vec::new();
1400        for (owner, target, pool_index) in hoisted.drain(..) {
1401            if owner == block {
1402                mine.push((target, pool_index));
1403            } else {
1404                rest.push((owner, target, pool_index));
1405            }
1406        }
1407        self.state().hoisted = rest;
1408        mine.sort_by_key(|(target, _)| match target {
1409            HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1410            HoistTarget::Global(_) => u32::MAX,
1411        });
1412        for (target, pool_index) in mine {
1413            self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1414            match target {
1415                HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1416                HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1417                HoistTarget::Global(name) => {
1418                    // A global binding lives in a reference cell, so the store
1419                    // goes through `put_var_ref` while reads use `get_var`.
1420                    let block = self.cur().current_block;
1421                    let pos = self.cur().cur_pos;
1422                    let in_params = self.cur().in_params;
1423                    self.state().insns.push(Insn::Var {
1424                        action: VarAction::PutRef,
1425                        name,
1426                        block,
1427                        in_params,
1428                    });
1429                    self.state().insn_pos.push(pos);
1430                }
1431            }
1432        }
1433        for index in self.block_vars_reversed(block) {
1434            self.emit(
1435                Opcode::SetLocUninitialized,
1436                &[Op::Slot(Slot::Loc(index as u32))],
1437            );
1438        }
1439    }
1440
1441    /// Emit the code that runs when a lexical scope is exited.
1442    ///
1443    /// A captured binding has to be closed: detaching its reference cell freezes
1444    /// the value the binding had when the block ended, which is what a closure
1445    /// created inside the block must keep seeing.
1446    fn emit_scope_leave(&mut self, block: u64) {
1447        for index in self.block_vars_reversed(block) {
1448            if self.cur().vars[index].is_captured {
1449                self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1450            }
1451        }
1452    }
1453
1454    /// Locals declared in `block`, in reverse declaration order.
1455    fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1456        let state = self.cur();
1457        let mut out: Vec<usize> = (0..state.vars.len())
1458            .filter(|index| {
1459                state.var_block.get(*index).copied() == Some(block)
1460                    && state.vars[*index].is_lexical
1461                    // A derived constructor's `this` is lexical but is not initialised by
1462                    // entering the scope: `check_ctor` proves it, so its dead-zone marker
1463                    // was emitted with the constructor's own prologue.
1464                    && state.vars[*index].name != "this"
1465            })
1466            .collect();
1467        out.reverse();
1468        out
1469    }
1470
1471    /// Declare a local, even at the top level of a script.
1472    ///
1473    /// A `catch` parameter is always a local: the reference puts it in the
1474    /// function's own variable list (`1: catch e`), never in the global object,
1475    /// because it only exists while the handler runs.
1476    fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1477        let state = self.state();
1478        let index = state.vars.len() as u32;
1479        // A `catch` parameter belongs to a scope even though it is not lexical: the
1480        // runtime instantiates it per handler entry, but it never sits in the
1481        // temporal dead zone.
1482        let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1483            state.current_block
1484        } else {
1485            0
1486        };
1487        state.var_block.push(block);
1488        state.vars.push(def);
1489        index
1490    }
1491
1492    fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1493        if self.cur().is_module
1494            && self.cur().current_block == self.cur().body_block
1495            && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1496        {
1497            // Only the body's own block: a `let` inside a module-level `{}` is still an
1498            // ordinary local of that block, not a module variable.
1499            //
1500            // A `using` binding is excluded on purpose, and the reference excludes it in
1501            // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1502            // "'using' variables are currently not exported in modules"): a module-level
1503            // `using` is an ordinary *local* of the module body function, not a module
1504            // cell. Two things follow, and both are what the reference does — `export {a}`
1505            // of a `using` binding is "exported variable 'a' does not exist", and
1506            // disposal works, because the disposal epilogue addresses locals by slot.
1507            //
1508            // The hidden dispose-method variable is excluded for a stronger reason: it is
1509            // *always* a local (`add_scope_var` in the reference), and it must sit
1510            // immediately after its value so `using_dispose` can find it at `slot + 1`.
1511            return self.declare_module(name, &def);
1512        }
1513        if self.cur().declares_globally(&def) {
1514            self.declare_global(name, &def);
1515            return 0;
1516        }
1517        let state = self.state();
1518        let index = state.vars.len() as u32;
1519        let block = if def.is_lexical {
1520            state.current_block
1521        } else {
1522            0
1523        };
1524        state.var_block.push(block);
1525        state.vars.push(def);
1526        index
1527    }
1528
1529    /// Declare a `using` binding and its cached dispose method, returning both slots.
1530    ///
1531    /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1532    /// `(value, value + 1)` — the reference does the same and documents the constraint.
1533    fn declare_using(&mut self, name: &str) -> (u32, u32) {
1534        let mut def = VarDef::lexical(name);
1535        def.kind = VarKind::Using;
1536        let value = self.declare(name, def);
1537        let mut method = VarDef::lexical(using_method_name(name));
1538        method.kind = VarKind::UsingMethod;
1539        let method_slot = self.declare(&using_method_name(name), method);
1540        (value, method_slot)
1541    }
1542
1543    /// The slot a `using` binding's dispose method lives in.
1544    fn using_method_slot(&self, name: &str) -> Option<u32> {
1545        let hidden = using_method_name(name);
1546        self.cur()
1547            .vars
1548            .iter()
1549            .position(|var| var.name == hidden)
1550            .map(|index| index as u32)
1551    }
1552
1553    // -- statements --------------------------------------------------------
1554
1555    fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1556        self.stmt_labelled(stmt, &[])
1557    }
1558
1559    /// Compile a statement that a chain of labels names.
1560    ///
1561    /// Only a loop consumes `labels`; every other statement ignores them (the
1562    /// parser has already rejected a label on a statement that cannot use it).
1563    fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1564        // Only a *top-level* expression statement supplies the program's value.
1565        let saved = self.cur().leaves_value;
1566        self.state().leaves_value =
1567            matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1568        self.state().stmt_depth += 1;
1569        let result = self.stmt_inner(stmt, labels);
1570        self.state().stmt_depth -= 1;
1571        // A nested statement never contributes the program's value, so the flag
1572        // the wrapper set above is what survives.
1573        let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1574        self.state().leaves_value = produced;
1575        let _ = saved;
1576        result
1577    }
1578
1579    fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1580        match &stmt.kind {
1581            StmtKind::Empty | StmtKind::Debugger => {}
1582            StmtKind::Expr(expr) => {
1583                // The statement's first token is a position the reference records: an
1584                // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1585                // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1586                // is why an error from a construct with no position of its own (`[...it]`
1587                // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1588                let saved = self.cur().cur_pos;
1589                self.state().cur_pos = Some(expr.span.start);
1590                // An expression statement's value is thrown away — except in a
1591                // script, where it becomes the program's result. `assign` reads this
1592                // and clears it, so a nested assignment still produces a value.
1593                self.state().discard_value = !self.cur().is_script;
1594                let result = self.expr(expr);
1595                self.state().discard_value = false;
1596                result?;
1597                if std::mem::take(&mut self.state().no_value) {
1598                    // A store whose value was discarded left nothing to drop.
1599                } else if self.cur().is_script {
1600                    // The program's value lands in the hidden `<ret>` local.
1601                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1602                } else {
1603                    self.emit(Opcode::Drop, &[]);
1604                }
1605                // Restored last: the trailing `drop` is part of the statement, and in the
1606                // reference it simply inherits whatever the expression last recorded.
1607                self.state().cur_pos = saved;
1608            }
1609            StmtKind::Block(body) => {
1610                // The block's declarations were hoisted with its enclosing
1611                // statement list, so there is nothing left to declare here.
1612                let key = stmt.span.start.offset as u64;
1613                let parent = self.cur().current_block;
1614                self.push_block(key, parent);
1615                self.emit_scope_enter(key);
1616                // A block is where a `using` region lives, so its statements have to go
1617                // through `stmts`: that is what emits the disposal epilogue.
1618                self.stmts(body)?;
1619                self.emit_scope_leave(key);
1620                self.state().current_block = parent;
1621            }
1622            StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1623            // A function declaration was already instantiated when its scope was
1624            // entered, so the statement itself emits nothing.
1625            StmtKind::FuncDecl(_) => {}
1626            StmtKind::If { test, cons, alt } => {
1627                self.reset_value();
1628                let else_label = self.new_label();
1629                let end_label = self.new_label();
1630                self.expr(test)?;
1631                self.emit_jump(Opcode::IfFalse, else_label, &[]);
1632                self.stmt(cons)?;
1633                if alt.is_some() {
1634                    self.emit_jump(Opcode::Goto, end_label, &[]);
1635                }
1636                self.place_label(else_label);
1637                if let Some(alt) = alt {
1638                    self.stmt(alt)?;
1639                    self.place_label(end_label);
1640                }
1641            }
1642            StmtKind::While { test, body } => {
1643                self.reset_value();
1644                let top = self.new_label();
1645                let end = self.new_label();
1646                self.place_label(top);
1647                self.expr(test)?;
1648                // The condition's false branch and `break` share one target,
1649                // which is why a `while` loop needs only one end label.
1650                self.emit_jump(Opcode::IfFalse, end, &[]);
1651                self.loop_body(body, labels, top, end)?;
1652                self.emit_jump(Opcode::Goto, top, &[]);
1653                self.place_label(end);
1654            }
1655            StmtKind::DoWhile { body, test } => {
1656                self.reset_value();
1657                let top = self.new_label();
1658                let cont = self.new_label();
1659                let end = self.new_label();
1660                self.place_label(top);
1661                // `continue` in a `do…while` runs the test, so it lands on `cont`
1662                // rather than on the loop head.
1663                self.loop_body(body, labels, cont, end)?;
1664                self.place_label(cont);
1665                self.expr(test)?;
1666                self.emit_jump(Opcode::IfTrue, top, &[]);
1667                self.place_label(end);
1668            }
1669            StmtKind::For {
1670                init,
1671                test,
1672                update,
1673                body,
1674            } => {
1675                self.reset_value();
1676                let for_key = stmt.span.start.offset as u64;
1677                let for_parent = self.cur().current_block;
1678                self.push_block(for_key, for_parent);
1679                self.emit_scope_enter(for_key);
1680                if let Some(init) = init {
1681                    match init {
1682                        ForInit::VarDecl(decl) => {
1683                            self.var_decl(decl)?;
1684                        }
1685                        ForInit::Expr(expr) => {
1686                            // The head's value is discarded. Saying so lets an
1687                            // assignment store with `put` instead of `dup`+`put`, which
1688                            // is what the reference emits — and the difference matters:
1689                            // a `dup`/`drop` pair around the store gives the peephole a
1690                            // chance to fold the store into the *condition's* read.
1691                            self.state().discard_value = true;
1692                            let result = self.expr(expr);
1693                            self.state().discard_value = false;
1694                            result?;
1695                            if !std::mem::take(&mut self.state().no_value) {
1696                                self.emit(Opcode::Drop, &[]);
1697                            }
1698                        }
1699                    }
1700                }
1701                // A `let`/`const` in the head gets a *fresh binding per iteration*,
1702                // so a closure made in the body captures that iteration's value
1703                // instead of sharing one. The reference expresses this with
1704                // `close_loc`, which swaps in a new reference cell holding the
1705                // current value; the three points below are the ones it uses — after
1706                // the initialiser, before the update, and after the loop.
1707                let loop_bindings = match init {
1708                    Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
1709                        let mut names: Vec<String> = Vec::new();
1710                        for declarator in &decl.declarators {
1711                            let mut idents = Vec::new();
1712                            declarator.target.bound_names(&mut idents);
1713                            names.extend(idents.into_iter().map(|ident| ident.name));
1714                        }
1715                        names
1716                    }
1717                    _ => Vec::new(),
1718                };
1719                // The reference also closes right after the initialiser, so the first
1720                // iteration's closures get their own cell rather than sharing the one
1721                // the initialiser wrote into.
1722                for name in &loop_bindings {
1723                    let pos = self.cur().cur_pos;
1724                    self.state().insns.push(Insn::CloseCaptured {
1725                        name: name.clone(),
1726                        block: for_key,
1727                    });
1728                    self.state().insn_pos.push(pos);
1729                }
1730                let top = self.new_label();
1731                let cont = self.new_label();
1732                let end = self.new_label();
1733                self.place_label(top);
1734                if let Some(test) = test {
1735                    self.expr(test)?;
1736                    self.emit_jump(Opcode::IfFalse, end, &[]);
1737                }
1738                // `continue` runs the update expression first, so it lands on
1739                // `cont`, which sits just before the update.
1740                self.loop_body(body, labels, cont, end)?;
1741                self.place_label(cont);
1742                // Each iteration ends with a fresh cell, so the closures the body just
1743                // created keep the cell they captured and the update writes to a new
1744                // one. Without this every closure in the loop shares one binding.
1745                let binding_block = for_key;
1746                for name in &loop_bindings {
1747                    let pos = self.cur().cur_pos;
1748                    self.state().insns.push(Insn::CloseCaptured {
1749                        name: name.clone(),
1750                        block: binding_block,
1751                    });
1752                    self.state().insn_pos.push(pos);
1753                }
1754                if let Some(update) = update {
1755                    self.state().discard_value = true;
1756                    let result = self.expr(update);
1757                    self.state().discard_value = false;
1758                    result?;
1759                    if !std::mem::take(&mut self.state().no_value) {
1760                        self.emit(Opcode::Drop, &[]);
1761                    }
1762                }
1763                self.emit_jump(Opcode::Goto, top, &[]);
1764                self.place_label(end);
1765                self.emit_scope_leave(for_key);
1766                self.state().current_block = for_parent;
1767            }
1768            StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1769            StmtKind::Throw(expr) => {
1770                self.expr(expr)?;
1771                self.emit(Opcode::Throw, &[]);
1772            }
1773            StmtKind::Break(_) | StmtKind::Continue(_) => {
1774                // Labels and loops are wired up in a later milestone; a bare
1775                // break/continue jumps to the innermost enclosing target, which
1776                // the loop helpers register.
1777                self.control_transfer(stmt)?;
1778            }
1779            StmtKind::Labeled { label, body } => {
1780                self.labeled(label, body, stmt)?;
1781            }
1782            StmtKind::Switch {
1783                discriminant,
1784                cases,
1785            } => {
1786                self.switch(discriminant, cases, stmt)?;
1787            }
1788            StmtKind::Try {
1789                block,
1790                handler,
1791                finalizer,
1792            } => {
1793                self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
1794            }
1795            StmtKind::ForIn { left, right, body } => {
1796                self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
1797            }
1798            StmtKind::ForOf {
1799                left,
1800                right,
1801                body,
1802                is_await,
1803            } => {
1804                let kind = if *is_await {
1805                    ForLoopKind::AwaitOf
1806                } else {
1807                    ForLoopKind::Of
1808                };
1809                self.for_in_of(stmt, left, right, body, kind, labels)?;
1810            }
1811            StmtKind::With { object, body } => self.with_stmt(object, body)?,
1812            StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
1813            // `import` emits nothing: hoisting already bound its names, and the host
1814            // fills their cells before the body runs.
1815            StmtKind::Import(_) => {}
1816            StmtKind::Export(decl) => self.export_stmt(decl)?,
1817        }
1818        Ok(())
1819    }
1820
1821    /// Compile `return`, running every enclosing finalizer on the way out.
1822    ///
1823    /// `nip_catch` is what makes this possible: it discards everything on the stack
1824    /// down to and including the `catch` offset while keeping the return value on
1825    /// top, so the frame the finalizer sees has the same shape as on the normal
1826    /// path.
1827    fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
1828        let mut has_value = value.is_some();
1829        if let Some(expr) = value {
1830            // `return f(x)` is a tail call *only* when nothing has to happen to the
1831            // value afterwards. A `finally` or an open iterator in scope forces the
1832            // normal path, because the cleanup has to run after the call returns —
1833            // which is exactly what a tail call refuses to do.
1834            let plain = self
1835                .cur()
1836                .jump_targets
1837                .iter()
1838                .all(|target| target.finally_label.is_none() && !target.has_iterator);
1839            if plain && self.expr_if_tail_call(expr)? {
1840                return Ok(());
1841            }
1842            self.expr(expr)?;
1843        }
1844        // `return v` in an *async generator* awaits `v` before anything else happens —
1845        // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
1846        // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
1847        // exactly that reason ("the await must be done before handling the finally in case
1848        // it raises an exception").
1849        if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
1850            self.emit(Opcode::Await, &[]);
1851            self.state().has_await = true;
1852        }
1853        has_value = self.emit_unwind_for_return(has_value);
1854        // A generator or async function does not return to its caller: it either
1855        // finishes, and the value becomes `{value, done: true}`, or it suspends.
1856        // `return_async` is the "finished" half, and it reads the value off the stack
1857        // rather than carrying it, which is what the resume machinery expects.
1858        if self.cur().is_suspending() {
1859            if !has_value {
1860                self.emit(Opcode::Undefined, &[]);
1861            }
1862            self.emit(Opcode::ReturnAsync, &[]);
1863            return Ok(());
1864        }
1865        if has_value {
1866            self.emit(Opcode::Return, &[]);
1867        } else {
1868            self.emit(Opcode::ReturnUndef, &[]);
1869        }
1870        Ok(())
1871    }
1872
1873    /// Close an iterator: the reference's `emit_iterator_close`.
1874    ///
1875    /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
1876    /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
1877    /// sequence, and three details in it are load-bearing:
1878    ///
1879    /// * the iterator object is compared against `undefined` first, because a loop that
1880    ///   ran to completion clears that slot rather than closing an exhausted iterator;
1881    /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
1882    /// * `preserve_completion` keeps whatever was underneath (the return value of the
1883    ///   function being left), which is why one branch ends on `nip` and the other on `drop`.
1884    fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
1885        if !is_async {
1886            if preserve_completion {
1887                self.emit(Opcode::Rot3r, &[]);
1888                self.emit(Opcode::Undefined, &[]);
1889            }
1890            self.emit(Opcode::IteratorClose, &[]);
1891            return;
1892        }
1893        if preserve_completion {
1894            // `iter next completion -> completion iter`
1895            self.emit(Opcode::Nip, &[]);
1896            self.emit(Opcode::Swap, &[]);
1897        } else {
1898            // `iter next catch_offset -> iter`
1899            self.emit(Opcode::Drop, &[]);
1900            self.emit(Opcode::Drop, &[]);
1901        }
1902        let done = self.new_label();
1903        let no_return = self.new_label();
1904        self.emit(Opcode::Dup, &[]);
1905        self.emit(Opcode::IsUndefined, &[]);
1906        self.emit_jump(Opcode::IfTrue, done, &[]);
1907        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
1908        self.emit(Opcode::Dup, &[]);
1909        self.emit(Opcode::IsUndefinedOrNull, &[]);
1910        self.emit_jump(Opcode::IfTrue, no_return, &[]);
1911        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
1912        self.emit(Opcode::Await, &[]);
1913        self.state().has_await = true;
1914        self.emit_jump(Opcode::Goto, done, &[]);
1915        self.place_label(no_return);
1916        self.emit(Opcode::Drop, &[]);
1917        self.place_label(done);
1918        self.emit(Opcode::Drop, &[]);
1919    }
1920
1921    /// Emit the finalizer/iterator cleanup for leaving the current position with a
1922    /// return, and report whether a value is now on the stack for it to carry.
1923    ///
1924    /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
1925    /// enclosing `finally` at once, and the two used to be separate — the `yield` path
1926    /// simply emitted `return_async`, so `it.return()` ended the generator without ever
1927    /// running `finally` blocks the body was sitting inside.
1928    fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
1929        let targets = self.cur().jump_targets.clone();
1930        for target in targets.iter().rev() {
1931            if target.finally_label.is_none() && !target.has_iterator {
1932                continue;
1933            }
1934            if !has_value {
1935                // The cleanup expects a value to pass through; with nothing to
1936                // return, `undefined` stands in.
1937                self.emit(Opcode::Undefined, &[]);
1938                has_value = true;
1939            }
1940            self.emit(Opcode::NipCatch, &[]);
1941            if target.has_iterator {
1942                // Rewind to the loop's own slots and hand the close a dummy catch offset:
1943                // the loop is being abandoned, so there is nothing left to catch.
1944                self.emit_iterator_close(target.is_async_iterator, true);
1945            } else if let Some(finally) = target.finally_label {
1946                self.emit_jump(Opcode::Gosub, finally, &[]);
1947            }
1948        }
1949        has_value
1950    }
1951
1952    /// Compile a statement list, stopping at the first statement that cannot
1953    /// fall through.
1954    fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
1955        for (index, stmt) in body.iter().enumerate() {
1956            // A `using` declaration is not just a binding: everything after it, to the end
1957            // of the list, runs inside its disposal region. Compiling the rest of the list
1958            // recursively is what gives nested regions their innermost-first order.
1959            if Self::using_declaration(stmt).is_some() {
1960                return self.using_region(stmt, &body[index + 1..]);
1961            }
1962            self.stmt(stmt)?;
1963            if Self::terminates(stmt) {
1964                break;
1965            }
1966        }
1967        Ok(())
1968    }
1969
1970    /// The declaration a `using` statement carries, if it is one.
1971    fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
1972        match &stmt.kind {
1973            StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
1974            _ => None,
1975        }
1976    }
1977
1978    /// Compile `decl` and then the rest of its block, disposing when the block ends.
1979    ///
1980    /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
1981    /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
1982    /// exception — and this engine already funnels all of those through `catch` plus
1983    /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
1984    /// `return` and `break` dispose without knowing anything about `using`.
1985    ///
1986    /// ```text
1987    ///   <declaration>              value -> x, method -> x+1
1988    ///   catch CATCH                <- an exception in the rest lands here
1989    /// REST:
1990    ///   <the rest of the block>
1991    ///   drop                       <- the catch offset, on the fall-through path
1992    ///   undefined; gosub DISPOSE; drop
1993    ///   goto END
1994    /// CATCH:
1995    ///   using_dispose x            <- merges the failure into the pending exception
1996    ///   throw
1997    /// DISPOSE:
1998    ///   using_dispose_init
1999    ///   using_dispose x
2000    ///   using_dispose_end          <- rethrows if a dispose failed
2001    ///   ret
2002    /// END:
2003    /// ```
2004    fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
2005        let Some(decl) = Self::using_declaration(stmt) else {
2006            unreachable!("using_region is only called for a using declaration");
2007        };
2008        // `using` binds exactly one name and has no pattern form, which the parser
2009        // enforces; the region still has to know *which* slot to dispose.
2010        let name = decl
2011            .declarators
2012            .first()
2013            .and_then(|declarator| match &declarator.target.kind {
2014                PatternKind::Ident(ident) => Some(ident.name.clone()),
2015                _ => None,
2016            });
2017        self.stmt(stmt)?;
2018        let Some(name) = name else {
2019            // Unreachable for a well-formed `using`, but a bare `using` with no declarator
2020            // must not make the compiler panic.
2021            return self.stmts(rest);
2022        };
2023        let Some(value_slot) = self.using_value_slot(&name) else {
2024            // Declared globally, which the parser rules out for a script; a module's
2025            // top level is a scope, and there the disposal stays a known gap.
2026            return self.stmts(rest);
2027        };
2028        // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
2029        // exit path already disposed.
2030        let live = !rest.last().is_some_and(Self::terminates);
2031        self.using_region_around(value_slot, live, |compiler| compiler.stmts(rest))
2032    }
2033
2034    /// The slot a `using` binding's value lives in.
2035    fn using_value_slot(&self, name: &str) -> Option<u32> {
2036        self.cur()
2037            .vars
2038            .iter()
2039            .position(|var| var.name == name && var.kind == VarKind::Using)
2040            .map(|index| index as u32)
2041    }
2042
2043    /// Wrap `inside` in a disposal region for the resource in `value_slot`.
2044    ///
2045    /// Shared between a `using` statement — which owns the rest of its block — and a
2046    /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
2047    /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
2048    /// the end, `return`, `break`, `continue`, and an exception — and this engine already
2049    /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
2050    /// target with a `finally_label` is what makes `return` and `break` dispose without
2051    /// knowing anything about `using`.
2052    ///
2053    /// ```text
2054    ///   catch CATCH                <- an exception inside lands here
2055    ///   <inside>
2056    ///   drop                       <- the catch offset, on the fall-through path
2057    ///   undefined; gosub DISPOSE; drop
2058    ///   goto END
2059    /// CATCH:
2060    ///   using_dispose slot         <- merges the failure into the pending exception
2061    ///   throw
2062    /// DISPOSE:
2063    ///   using_dispose_init
2064    ///   using_dispose slot
2065    ///   using_dispose_end          <- rethrows if a dispose failed
2066    ///   ret
2067    /// END:
2068    /// ```
2069    fn using_region_around(
2070        &mut self,
2071        value_slot: u32,
2072        live: bool,
2073        inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
2074    ) -> Result<(), SyntaxError> {
2075        let catch_label = self.new_label();
2076        let end_label = self.new_label();
2077        let dispose_label = self.new_label();
2078
2079        self.emit_jump(Opcode::Catch, catch_label, &[]);
2080        self.push_jump_target(JumpTarget {
2081            names: Vec::new(),
2082            break_label: None,
2083            continue_label: None,
2084            // The catch offset is the one thing on the stack that leaving has to remove.
2085            drop_count: 1,
2086            finally_label: Some(dispose_label),
2087            is_regular_stmt: false,
2088            has_iterator: false,
2089            is_async_iterator: false,
2090        });
2091        inside(self)?;
2092        self.pop_jump_target();
2093
2094        if live {
2095            self.emit(Opcode::Drop, &[]);
2096            self.emit(Opcode::Undefined, &[]);
2097            self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2098            self.emit(Opcode::Drop, &[]);
2099            self.emit_jump(Opcode::Goto, end_label, &[]);
2100        }
2101
2102        // An exception unwinds to here with the thrown value on the stack, which is exactly
2103        // the shape `using_dispose` expects as its error state.
2104        self.place_label(catch_label);
2105        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2106        self.emit(Opcode::Throw, &[]);
2107
2108        self.place_label(dispose_label);
2109        // Inside the subroutine the return value and the `gosub` return address are both
2110        // live, and neither an outer finalizer nor another region may run before this one
2111        // has finished.
2112        self.push_jump_target(JumpTarget {
2113            names: Vec::new(),
2114            break_label: None,
2115            continue_label: None,
2116            drop_count: 2,
2117            finally_label: None,
2118            is_regular_stmt: false,
2119            has_iterator: false,
2120            is_async_iterator: false,
2121        });
2122        self.emit(Opcode::UsingDisposeInit, &[]);
2123        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2124        self.emit(Opcode::UsingDisposeEnd, &[]);
2125        self.pop_jump_target();
2126        self.emit(Opcode::Ret, &[]);
2127        self.place_label(end_label);
2128        Ok(())
2129    }
2130
2131    /// Declare every name a statement list introduces, before compiling any of
2132    /// it, so a reference that appears textually before a declaration still
2133    /// resolves.
2134    ///
2135    /// Declarations are walked in source order because that is the order the
2136    /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2137    /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2138    /// declarations hoist out to the function scope; lexical names belong to the
2139    /// block they were written in, which `block` records.
2140    fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2141        let saved = self.cur().current_block;
2142        self.state().current_block = block;
2143        let result = self.hoist_list(body);
2144        // Only now is every binding of this scope known, so the deferred function
2145        // bodies can be compiled against the finished list. Compiled at its own
2146        // declaration instead, a body that names a `var` written further down would
2147        // have resolved that name as a global.
2148        if result.is_ok() {
2149            let deferred = std::mem::take(&mut self.state().deferred_funcs);
2150            let mut outcome = Ok(());
2151            for (owner, func) in deferred {
2152                let previous = self.cur().current_block;
2153                self.state().current_block = owner;
2154                outcome = self.func_decl(&func);
2155                self.state().current_block = previous;
2156                if outcome.is_err() {
2157                    break;
2158                }
2159            }
2160            self.state().current_block = saved;
2161            return outcome;
2162        }
2163        // `current_block` is restored by the caller for a block statement, since
2164        // it needs it set while compiling; only clean up on the hoist path.
2165        self.state().current_block = saved;
2166        result
2167    }
2168
2169    fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2170        for stmt in body {
2171            self.hoist_stmt(stmt)?;
2172        }
2173        Ok(())
2174    }
2175
2176    /// Whether a statement always transfers control away, making everything after
2177    /// it in the same list unreachable.
2178    ///
2179    /// The reference drops such statements in `skip_dead_code`, so `return 1;
2180    /// let x = 2;` compiles to the same bytecode as `return 1;`.
2181    fn terminates(stmt: &Stmt) -> bool {
2182        matches!(
2183            stmt.kind,
2184            StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2185        )
2186    }
2187
2188    fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2189        match &stmt.kind {
2190            StmtKind::VarDecl(decl) => {
2191                for declarator in &decl.declarators {
2192                    let mut names = Vec::new();
2193                    declarator.target.bound_names(&mut names);
2194                    for name in names {
2195                        let text = name.name.clone();
2196                        if decl.kind == VarDeclKind::Var {
2197                            let def = VarDef::var(text.clone());
2198                            self.declare_var(&text, def);
2199                        } else if decl.kind.is_using() {
2200                            // Two adjacent slots: the resource, then the dispose method
2201                            // snapshotted at declaration. `using_dispose` reads them as a
2202                            // pair `(slot, slot + 1)`, so nothing may be declared between
2203                            // them — which is why both are declared here, in one step,
2204                            // rather than the method being added at emission time.
2205                            self.declare_using(&text);
2206                        } else {
2207                            let def = if decl.kind == VarDeclKind::Const {
2208                                VarDef::constant(text.clone())
2209                            } else {
2210                                VarDef::lexical(text.clone())
2211                            };
2212                            self.declare(&text, def);
2213                        }
2214                    }
2215                }
2216            }
2217            StmtKind::FuncDecl(func) => {
2218                if let Some(name) = &func.name {
2219                    // A function declaration is a `var` binding that happens to
2220                    // hold a function, not a lexical one.
2221                    let def = VarDef::var(name.name.clone());
2222                    self.declare_var(&name.name.clone(), def);
2223                }
2224                // The function object is created when the scope is entered, so it
2225                // exists before the declaration is reached. Its body is compiled
2226                // *after* this scope's hoisting finishes, so a name it uses resolves
2227                // even when the `var` that declares it comes later in the source.
2228                let owner = self.cur().current_block;
2229                self.state().deferred_funcs.push((owner, func.clone()));
2230            }
2231            StmtKind::ClassDecl(class) => {
2232                if let Some(name) = &class.name {
2233                    self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2234                }
2235            }
2236            // A module's imports are bound before any of its code runs, and its exports
2237            // declare the very bindings they export — so both hoist the declarations
2238            // their `StmtKind` arm will later emit code for.
2239            StmtKind::Import(decl) => self.hoist_import(decl)?,
2240            StmtKind::Export(decl) => self.hoist_export(decl)?,
2241            StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2242            StmtKind::If { cons, alt, .. } => {
2243                self.hoist_stmt(cons)?;
2244                if let Some(alt) = alt {
2245                    self.hoist_stmt(alt)?;
2246                }
2247            }
2248            StmtKind::While { body, .. }
2249            | StmtKind::DoWhile { body, .. }
2250            | StmtKind::Labeled { body, .. }
2251            | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2252            StmtKind::For { init, body, .. } => {
2253                // A `for` head gets its own scope even when it declares nothing,
2254                // because `let` in the head is scoped to the loop.
2255                let key = stmt.span.start.offset as u64;
2256                let parent = self.cur().current_block;
2257                self.push_block(key, parent);
2258                if let Some(init) = init
2259                    && let ForInit::VarDecl(decl) = init
2260                {
2261                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2262                }
2263                self.hoist_stmt(body)?;
2264                self.state().current_block = parent;
2265            }
2266            StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
2267                let key = stmt.span.start.offset as u64;
2268                let parent = self.cur().current_block;
2269                self.push_block(key, parent);
2270                if let ForHead::VarDecl(decl) = left {
2271                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2272                }
2273                self.hoist_stmt(body)?;
2274                self.state().current_block = parent;
2275            }
2276            StmtKind::Try {
2277                block,
2278                handler,
2279                finalizer,
2280            } => {
2281                self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2282                let try_parent = self.cur().current_block;
2283                if let Some(handler) = handler {
2284                    // The catch parameter belongs to the function scope, not to a
2285                    // block: it is a `catch` binding rather than a `let`, so it is
2286                    // never in the temporal dead zone and `emit_scope_enter` must
2287                    // not mark it uninitialised. It still has to be declared before
2288                    // the handler body is hoisted, so it takes the slot the
2289                    // reference gives it (bindings are numbered in source order).
2290                    if let Some(pattern) = &handler.param {
2291                        // The parameter gets its own scope, so entering the handler
2292                        // does not have to re-declare it. It is not lexical, so it
2293                        // is never marked uninitialised.
2294                        let key = Self::try_block_key(stmt, TryPart::Param);
2295                        let parent = self.cur().current_block;
2296                        self.push_block(key, parent);
2297                        // A destructuring parameter binds several names, one slot each,
2298                        // in the order they are written. The reference declares those as
2299                        // `let`s rather than as one `catch` binding — its dump prints
2300                        // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2301                        // so the kind follows the shape of the parameter.
2302                        //
2303                        // Neither form is in the dead zone: the stores run as the handler
2304                        // is entered, so both use the unchecked `put_loc`.
2305                        let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2306                        let mut names = Vec::new();
2307                        pattern.bound_names(&mut names);
2308                        for name in names {
2309                            let def = VarDef {
2310                                name: name.name.clone(),
2311                                is_const: false,
2312                                is_lexical: destructures,
2313                                kind: if destructures {
2314                                    crate::bytecode::VarKind::LexicalCatch
2315                                } else {
2316                                    crate::bytecode::VarKind::Catch
2317                                },
2318                                is_captured: false,
2319                                scope_level: 0,
2320                                scope_next: None,
2321                            };
2322                            self.declare_local(&name.name.clone(), def);
2323                        }
2324                        // The handler body nests inside the parameter's scope, so the
2325                        // body's bindings chain on to the parameter (the reference
2326                        // prints `let y [next:1]`, pointing at `e`).
2327                        self.state().current_block = key;
2328                    }
2329                    self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2330                    // Back to the block the `try` itself lives in, so the finalizer
2331                    // is a sibling of the handler rather than nested in it.
2332                    self.state().current_block = try_parent;
2333                }
2334                if let Some(finalizer) = finalizer {
2335                    self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2336                }
2337            }
2338            StmtKind::Switch { cases, .. } => {
2339                let key = stmt.span.start.offset as u64;
2340                let parent = self.cur().current_block;
2341                self.push_block(key, parent);
2342                for case in cases {
2343                    self.hoist_list(&case.body)?;
2344                }
2345                self.state().current_block = parent;
2346            }
2347            _ => {}
2348        }
2349        Ok(())
2350    }
2351
2352    /// Hoist a nested statement list, which is its own lexical scope.
2353    fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2354        let parent = self.cur().current_block;
2355        self.push_block(key, parent);
2356        self.hoist_list(body)?;
2357        self.state().current_block = parent;
2358        Ok(())
2359    }
2360
2361    /// A block key for one part of a `try` statement.
2362    ///
2363    /// The three parts are three separate scopes, so they cannot share the key a
2364    /// statement's own offset would give them: the try block, the handler body and
2365    /// the finalizer would then look like one scope, and their `let` bindings would
2366    /// be marked uninitialised only on entering the first of them.
2367    fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2368        (stmt.span.start.offset as u64) * 4 + part as u64
2369    }
2370
2371    /// Declare a `var`: it lives in the function's own scope, not the block's.
2372    fn declare_var(&mut self, name: &str, def: VarDef) {
2373        if self.cur().is_module {
2374            self.declare_module(name, &def);
2375            return;
2376        }
2377        if self.cur().declares_globally(&def) {
2378            self.declare_global(name, &def);
2379            return;
2380        }
2381        let state = self.state();
2382        // A binding of the *parameter* scope does not count: the body's `var` of the
2383        // same name is a different binding and needs a slot of its own.
2384        if state.vars.iter().enumerate().any(|(index, v)| {
2385            v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
2386        }) {
2387            return;
2388        }
2389        // A `var` belongs to the function scope, never to the enclosing block.
2390        state.var_block.push(FUNCTION_SCOPE);
2391        state.vars.push(def);
2392    }
2393
2394    /// Declare `name` as a binding of the parameter scope, returning its slot.
2395    fn declare_param_var(&mut self, name: &str) -> u32 {
2396        declare_param_var_at(self.state(), name)
2397    }
2398
2399    /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2400    ///
2401    /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2402    /// so each points at the one declared before it and the oldest ends the chain with
2403    /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2404    /// runtime walks when it instantiates them.
2405    fn declare_param_binding(&mut self, name: &str) -> u32 {
2406        let state = self.state();
2407        let previous = state
2408            .vars
2409            .iter()
2410            .enumerate()
2411            .rev()
2412            .find(|(index, var)| {
2413                state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2414            })
2415            .map(|(index, _)| index as i32);
2416        let index = state.vars.len() as u32;
2417        state.var_block.push(PARAM_SCOPE);
2418        let mut def = VarDef::lexical(name);
2419        // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2420        // the function's, and its bindings are initialised one by one rather than all at
2421        // once — which is exactly what the dead zone needs.
2422        def.scope_level = 1;
2423        def.scope_next = Some(previous.unwrap_or(-2));
2424        state.vars.push(def);
2425        index
2426    }
2427
2428    /// The slot of a parameter-list binding, if the list has one by that name.
2429    fn param_binding_slot(&self, name: &str) -> Option<u32> {
2430        let state = self.cur();
2431        state
2432            .vars
2433            .iter()
2434            .enumerate()
2435            .position(|(index, var)| {
2436                var.name == name
2437                    && var.is_lexical
2438                    && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2439            })
2440            .map(|index| index as u32)
2441    }
2442
2443    /// Every parameter-list binding, in declaration order.
2444    fn param_binding_names(&self) -> Vec<String> {
2445        let state = self.cur();
2446        state
2447            .vars
2448            .iter()
2449            .enumerate()
2450            .filter(|(index, var)| {
2451                var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2452            })
2453            .map(|(_, var)| var.name.clone())
2454            .collect()
2455    }
2456
2457    /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2458    fn body_var_slot(&self, name: &str) -> Option<u32> {
2459        let state = self.cur();
2460        state
2461            .vars
2462            .iter()
2463            .enumerate()
2464            .find(|(index, var)| {
2465                var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2466            })
2467            .map(|(index, _)| index as u32)
2468    }
2469
2470    /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2471    /// one.
2472    ///
2473    /// With parameter expressions the reference creates two: an unmapped one in the
2474    /// argument scope, for the defaults and anything they close over, and the body's own.
2475    /// They are separate bindings, which is what makes
2476    /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2477    /// report 1 from `p` and 2 from the body.
2478    fn provide_param_arguments(&mut self) {
2479        if !self.cur().has_parameter_expressions {
2480            return;
2481        }
2482        let mentioned = self.cur().needs_param_arguments
2483            || self
2484                .cur()
2485                .insns
2486                .iter()
2487                .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2488        if !mentioned {
2489            return;
2490        }
2491        let slot = self.declare_param_var("arguments");
2492        let magic = if self.cur().strict || !self.cur().simple_parameter_list {
2493            0
2494        } else {
2495            1
2496        };
2497        self.prepend_initialiser_to(
2498            slot,
2499            Insn::Fixed {
2500                op: Opcode::SpecialObject,
2501                operands: vec![Op::Int(magic)],
2502            },
2503        );
2504    }
2505
2506    /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2507    fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2508        let current = self.stack.len() - 1;
2509        let init = [
2510            producer,
2511            Insn::Fixed {
2512                op: Opcode::PutLoc,
2513                operands: vec![Op::Slot(Slot::Loc(slot))],
2514            },
2515        ];
2516        let inserted = init.len();
2517        for (index, instruction) in init.into_iter().enumerate() {
2518            self.stack[current].insns.insert(index, instruction);
2519        }
2520        for placed in self.stack[current].labels.iter_mut().flatten() {
2521            *placed += inserted;
2522        }
2523        self.state().label_since_insn = false;
2524    }
2525
2526    /// Give the function an `arguments` binding if its body mentions one.
2527    ///
2528    /// The check runs on the *instruction* stream rather than the AST: by this point
2529    /// every reference has become an `Insn::Var`, so scanning is exact and needs no
2530    /// AST walker. Declaring lazily matters for more than tidiness — always declaring
2531    /// would renumber every later local slot and stop the bytecode matching the
2532    /// reference, which only adds the binding when the body uses it.
2533    ///
2534    /// `arguments` is a local, initialised at the top of the body by
2535    /// `special_object`; that is the reference's shape, so the disassembly agrees.
2536    fn provide_arguments(&mut self) {
2537        let current = self.stack.len() - 1;
2538        if self.stack[current].is_script || self.stack[current].is_module {
2539            // A module has no `arguments` binding; referring to it is a ReferenceError,
2540            // which is exactly what an unbound name produces.
2541            return;
2542        }
2543        // An arrow has no `arguments` of its own: the binding belongs to the enclosing
2544        // function, which is why `() => arguments` sees the caller's arguments.
2545        if self.stack[current].is_arrow {
2546            if self.mentions("arguments") {
2547                self.ensure_enclosing_arguments();
2548            }
2549            return;
2550        }
2551        // Only a *body* mention needs the body's binding: the parameter list has one of
2552        // its own (see [`Compiler::provide_param_arguments`]).
2553        //
2554        // `delete arguments` counts too: it compiles to `DeleteVar`, which is not a
2555        // `Var`, so without this the body got no binding at all — the name resolved to
2556        // the global object and `delete` answered `true` for a binding that cannot be
2557        // deleted. The reference answers `false`.
2558        let mentioned = self.cur().insns.iter().any(|insn| match insn {
2559            Insn::Var {
2560                name, in_params, ..
2561            } => name == "arguments" && !*in_params,
2562            Insn::DeleteVar { name } => name == "arguments",
2563            _ => false,
2564        });
2565        if !mentioned && !self.cur().needs_arguments_local {
2566            return;
2567        }
2568        // The request may have come only from a parameter-list arrow, in which case the
2569        // parameter scope's binding already answers for it and the body needs none.
2570        if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
2571            return;
2572        }
2573        // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`.
2574        //
2575        // With parameter expressions the list and the body are separate environments, so
2576        // an assignment to a parameter cannot be reflected into `arguments` at all — the
2577        // arguments object is unmapped whatever the mode, which is why the reference emits
2578        // `special_object 0` here even in sloppy code.
2579        // A non-simple parameter list (`[a]`, `...rest`, `a = 1`) makes the arguments
2580        // object unmapped whatever the mode — §10.4.4 keys the decision on
2581        // `IsSimpleParameterList`, not on strictness alone.
2582        let magic = if self.stack[current].strict || !self.stack[current].simple_parameter_list {
2583            0
2584        } else {
2585            1
2586        };
2587        // A mapped `arguments` shares storage with the parameters: `arguments[0] = 2`
2588        // has to be visible as `a`, and assigning `a` has to be visible as `arguments[0]`.
2589        // The only storage both sides can see is a reference cell, so every parameter the
2590        // object maps gets one — even a parameter no closure captured. Without this the
2591        // slot holds a plain copy and the mapping has nothing to write through.
2592        if magic == 1 {
2593            for arg in &mut self.stack[current].args {
2594                arg.is_captured = true;
2595            }
2596        }
2597        self.prepend_binding("arguments", magic);
2598    }
2599
2600    /// Whether a *body* instruction refers to `arguments`.
2601    fn body_mentions_arguments(&self) -> bool {
2602        self.cur()
2603            .insns
2604            .iter()
2605            .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
2606    }
2607
2608    /// Whether the function body's instruction stream refers to `name`.
2609    fn mentions(&self, name: &str) -> bool {
2610        let current = self.stack.len() - 1;
2611        // A binding of the parameter scope does not answer for the body: the body's own
2612        // `arguments` (or self-name) still has to be provided for it.
2613        if self.stack[current]
2614            .vars
2615            .iter()
2616            .enumerate()
2617            .any(|(index, v)| {
2618                v.name == name
2619                    && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
2620            })
2621        {
2622            return false;
2623        }
2624        self.stack[current]
2625            .insns
2626            .iter()
2627            .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
2628    }
2629
2630    /// Bind the name a named function expression uses to refer to itself.
2631    ///
2632    /// The value is `special_object 2`, the function currently running, so the binding
2633    /// is the closure itself and not a copy. It is a local of this function, which is
2634    /// what keeps `g` out of the enclosing scope.
2635    /// Give the function a local `this`, for an arrow inside it to capture.
2636    fn provide_this_local(&mut self) {
2637        let current = self.stack.len() - 1;
2638        if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
2639            return;
2640        }
2641        if !self.stack[current]
2642            .vars
2643            .iter()
2644            .any(|var| var.name == "this")
2645        {
2646            self.declare_hidden_local("this", VarKind::Normal);
2647        }
2648        self.prepend_initialiser(
2649            "this",
2650            Insn::Fixed {
2651                op: Opcode::PushThis,
2652                operands: vec![],
2653            },
2654        );
2655    }
2656
2657    /// Give the function a local `<home_object>`, for an arrow or a static block inside it
2658    /// to read through `super`.
2659    fn provide_home_object_local(&mut self) {
2660        let current = self.stack.len() - 1;
2661        if !self.stack[current].needs_home_object_local {
2662            return;
2663        }
2664        if !self.stack[current]
2665            .vars
2666            .iter()
2667            .any(|var| var.name == HOME_OBJECT)
2668        {
2669            self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
2670        }
2671        self.prepend_initialiser(
2672            HOME_OBJECT,
2673            Insn::Fixed {
2674                op: Opcode::SpecialObject,
2675                operands: vec![Op::Int(4)],
2676            },
2677        );
2678    }
2679
2680    fn provide_self_name(&mut self) {
2681        let current = self.stack.len() - 1;
2682        let Some(name) = self.stack[current].self_name.clone() else {
2683            return;
2684        };
2685        if self.stack[current].self_name_initialized {
2686            return;
2687        }
2688        // Either the body refers to the name, or a nested function already forced the
2689        // binding into existence while being resolved. A direct `eval` can name it
2690        // without mentioning it, so its presence is a third reason: in strict mode
2691        // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
2692        // that only happens if the binding exists.
2693        let declared = self.stack[current].vars.iter().any(|v| v.name == name);
2694        if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
2695            return;
2696        }
2697        self.stack[current].self_name_initialized = true;
2698        self.prepend_binding_with(&name, 2, VarKind::FunctionName);
2699    }
2700
2701    /// Insert `special_object magic` plus the store to `name` at the top of the body.
2702    ///
2703    /// Prepending shifts every label that has been placed, so they are all moved by
2704    /// the number of instructions inserted.
2705    fn prepend_binding(&mut self, name: &str, magic: i32) {
2706        self.prepend_binding_with(name, magic, VarKind::Normal);
2707    }
2708
2709    /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
2710    fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
2711        let current = self.stack.len() - 1;
2712        // A function-expression's own name is immutable in strict mode, which is what
2713        // makes `f = 1` inside a strict body throw instead of being dropped.
2714        let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
2715        self.declare_var(
2716            name,
2717            VarDef {
2718                kind,
2719                is_const,
2720                ..VarDef::var(name)
2721            },
2722        );
2723        let init = [
2724            Insn::Fixed {
2725                op: Opcode::SpecialObject,
2726                operands: vec![Op::Int(magic)],
2727            },
2728            Insn::Var {
2729                // An initialisation, not an assignment: sloppy mode drops stores to a
2730                // function-expression's own name, and the prologue is what puts the
2731                // value there in the first place.
2732                action: if kind == VarKind::FunctionName {
2733                    VarAction::PutInit
2734                } else {
2735                    VarAction::Put
2736                },
2737                name: name.to_string(),
2738                block: 0,
2739                in_params: false,
2740            },
2741        ];
2742        let inserted = init.len();
2743        for (index, instruction) in init.into_iter().enumerate() {
2744            self.stack[current].insns.insert(index, instruction);
2745        }
2746        for placed in self.stack[current].labels.iter_mut().flatten() {
2747            *placed += inserted;
2748        }
2749        // A store sits at the insertion point now, so the `put`/`get` fold must not
2750        // reach across it.
2751        self.stack[current].label_since_insn = true;
2752    }
2753
2754    /// Record a top-level script declaration as a global.
2755    ///
2756    /// A script's top-level `var`/`let`/`function` create properties of the
2757    /// global object, not slots in the script's frame, so they show up as closure
2758    /// variables instead.
2759    fn declare_global(&mut self, name: &str, def: &VarDef) {
2760        let state = self.state();
2761        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2762            // The name was already referenced, from a function compiled before this
2763            // declaration was reached — `function a(){ b() } function b(){}` resolves
2764            // `b` while `b` is still unknown, and that guess has to be corrected here.
2765            // Leaving it as a plain global meant the declaration was never registered,
2766            // so the binding did not exist at run time and `a()` threw
2767            // `b is not defined`.
2768            if matches!(existing.closure_type, ClosureType::Global) {
2769                existing.closure_type = ClosureType::GlobalDecl;
2770                existing.is_const = def.is_const;
2771                existing.is_lexical = def.is_lexical;
2772            }
2773            return;
2774        }
2775        state.closure_vars.push(ClosureVar {
2776            name: name.to_string(),
2777            is_const: def.is_const,
2778            is_lexical: def.is_lexical,
2779            closure_type: ClosureType::GlobalDecl,
2780            var_idx: 0,
2781        });
2782    }
2783
2784    /// Record a module-level declaration as a module variable.
2785    ///
2786    /// The binding is a closure variable of the module body, so reads and writes are
2787    /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
2788    /// *who fills the cell*: the module record does, before the body runs, and an import
2789    /// points its cell at the exporting module's, which is what makes bindings live and
2790    /// cycles work.
2791    fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
2792        let state = self.state();
2793        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2794            // The name may have been referenced before this declaration was hoisted,
2795            // which resolved it as a plain global. Correct that here, the way
2796            // `declare_global` does.
2797            if matches!(existing.closure_type, ClosureType::Global) {
2798                existing.closure_type = ClosureType::ModuleDecl;
2799                existing.is_const = def.is_const;
2800                existing.is_lexical = def.is_lexical;
2801            }
2802            return 0;
2803        }
2804        state.closure_vars.push(ClosureVar {
2805            name: name.to_string(),
2806            is_const: def.is_const,
2807            is_lexical: def.is_lexical,
2808            closure_type: ClosureType::ModuleDecl,
2809            var_idx: 0,
2810        });
2811        0
2812    }
2813
2814    /// Declare a module variable and answer its closure-variable index.
2815    ///
2816    /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
2817    /// module variable is not one. The import table needs the real index instead, because
2818    /// that is the position the host writes the cell into.
2819    fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
2820        self.declare_module(name, def);
2821        self.cur()
2822            .closure_vars
2823            .iter()
2824            .position(|c| c.name == name)
2825            .map(|index| index as u32)
2826            .unwrap_or(0)
2827    }
2828
2829    /// Declare one imported binding as a module variable.
2830    ///
2831    /// Returns the closure-variable index, which is what the import table records: the
2832    /// host writes the exporter's cell into that slot before the body runs.
2833    fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
2834        let state = self.state();
2835        if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
2836            // Keep the slot, fix the kind: the name may already have been referenced.
2837            state.closure_vars[index].closure_type = ClosureType::ModuleImport;
2838            state.closure_vars[index].is_const = is_const;
2839            return index as u32;
2840        }
2841        state.closure_vars.push(ClosureVar {
2842            name: name.to_string(),
2843            // An imported binding cannot be assigned: `x = 1` on an import is a
2844            // `TypeError` at run time, which the const flag is what produces.
2845            is_const: true,
2846            // Lexical, so reads go through `get_var_ref_check`: before linking has filled
2847            // the cell an import is in its dead zone, and reading it there must say so
2848            // rather than answer `undefined`.
2849            is_lexical: true,
2850            closure_type: ClosureType::ModuleImport,
2851            var_idx: 0,
2852        });
2853        state.closure_vars.len() as u32 - 1
2854    }
2855
2856    /// Emit the code an `export` needs.
2857    ///
2858    /// Only `export default <expr>` has any: everything else is a table entry whose
2859    /// binding is declared elsewhere. The expression is stored into the hidden
2860    /// `*default*` variable rather than returned, because the module body has no value
2861    /// to speak of.
2862    fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2863        match &decl.kind {
2864            ExportKind::Declaration(stmt) => self.stmt(stmt),
2865            ExportKind::Default(expr) => {
2866                // A named default function/class is already a module binding; the export
2867                // points at it and there is nothing to evaluate.
2868                if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some())
2869                    || matches!(&expr.kind, ExprKind::Class(class) if class.name.is_some())
2870                {
2871                    return Ok(());
2872                }
2873                self.expr(expr)?;
2874                let index = self.declare_export_default();
2875                self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
2876                Ok(())
2877            }
2878            ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
2879        }
2880    }
2881
2882    /// A module name as the string it denotes.
2883    fn module_name_text(name: &ModuleName) -> &str {
2884        match name {
2885            ModuleName::Ident(ident) => &ident.name,
2886            ModuleName::Str(text) => text,
2887        }
2888    }
2889
2890    /// Bind `import`'s local names and record where each one comes from.
2891    ///
2892    /// Nothing is emitted: an import is not an instruction, it is a promise that the
2893    /// binding's cell will be filled before the body runs. The cell lands in the module's
2894    /// environment at a fixed index, and the host fills it from the exporter's cell —
2895    /// which is why a cyclic import can bind before the other module has evaluated.
2896    fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
2897        let request = self.module_request(&decl.source, &decl.attributes);
2898        for specifier in &decl.specifiers {
2899            let (local, name, is_star) = match specifier {
2900                ImportSpecifier::Default(ident) => {
2901                    (ident.name.clone(), "default".to_string(), false)
2902                }
2903                ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
2904                ImportSpecifier::Named { imported, local } => (
2905                    local.name.clone(),
2906                    Self::module_name_text(imported).to_string(),
2907                    false,
2908                ),
2909            };
2910            // `import * as ns` is *not* a live binding of another module's variable —
2911            // it is a value of its own, which is why the reference declares it like a
2912            // module variable and the host stores the namespace object in that cell.
2913            let var_idx = if is_star {
2914                // `const`: a namespace object is a value, and the binding is immutable.
2915                self.declare_module_var(&local, &VarDef::constant(local.clone()))
2916            } else {
2917                self.declare_import(&local, true)
2918            };
2919            self.module_meta().imports.push(ImportEntry {
2920                module: request,
2921                name,
2922                var_idx,
2923                is_star,
2924            });
2925        }
2926        Ok(())
2927    }
2928
2929    /// Record what an `export` offers, declaring the binding it exports.
2930    ///
2931    /// `export var x = 1` is a declaration like any other; only the table entry is extra.
2932    fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2933        match &decl.kind {
2934            ExportKind::Declaration(stmt) => {
2935                // The inner declaration keeps its own hoisting, then every name it binds
2936                // becomes an export of the same name.
2937                self.hoist_stmt(stmt)?;
2938                let mut names = Vec::new();
2939                Self::declared_names(stmt, &mut names);
2940                for name in names {
2941                    let var_idx = self.module_binding_index(&name);
2942                    self.exports_local(&name, var_idx);
2943                }
2944            }
2945            ExportKind::Default(expr) => {
2946                // The reference puts a default export in a hidden `*default*` variable,
2947                // so `export default function f(){}` can export a *value* while `f` stays
2948                // a binding of the module.
2949                if let ExprKind::Function(func) = &expr.kind
2950                    && let Some(name) = &func.name
2951                {
2952                    let text = name.name.clone();
2953                    self.hoist_stmt(&Stmt {
2954                        kind: StmtKind::FuncDecl(func.clone()),
2955                        span: expr.span,
2956                    })?;
2957                    let var_idx = self.module_binding_index(&text);
2958                    self.module_meta().exports.push(ExportEntry::Local {
2959                        export_name: "default".to_string(),
2960                        var_idx,
2961                    });
2962                    return Ok(());
2963                }
2964                if let ExprKind::Class(class) = &expr.kind
2965                    && let Some(name) = &class.name
2966                {
2967                    let text = name.name.clone();
2968                    self.hoist_stmt(&Stmt {
2969                        kind: StmtKind::ClassDecl(class.clone()),
2970                        span: expr.span,
2971                    })?;
2972                    let var_idx = self.module_binding_index(&text);
2973                    let _ = var_idx;
2974                }
2975                let var_idx = self.declare_export_default();
2976                self.module_meta().exports.push(ExportEntry::Local {
2977                    export_name: "default".to_string(),
2978                    var_idx,
2979                });
2980            }
2981            ExportKind::Named {
2982                specifiers,
2983                source,
2984                attributes,
2985            } => match source {
2986                Some(source) => {
2987                    let request = self.module_request(source, attributes);
2988                    for specifier in specifiers {
2989                        self.module_meta().exports.push(ExportEntry::Indirect {
2990                            export_name: Self::module_name_text(&specifier.exported).to_string(),
2991                            module: request,
2992                            import_name: Self::module_name_text(&specifier.local).to_string(),
2993                        });
2994                    }
2995                }
2996                None => {
2997                    for specifier in specifiers {
2998                        let local = Self::module_name_text(&specifier.local).to_string();
2999                        let var_idx = self.module_binding_index(&local);
3000                        let export_name = Self::module_name_text(&specifier.exported).to_string();
3001                        self.module_meta().exports.push(ExportEntry::Local {
3002                            export_name,
3003                            var_idx,
3004                        });
3005                    }
3006                }
3007            },
3008            ExportKind::All {
3009                source,
3010                exported,
3011                attributes,
3012            } => {
3013                let request = self.module_request(source, attributes);
3014                match exported {
3015                    Some(name) => {
3016                        self.module_meta().exports.push(ExportEntry::StarAs {
3017                            export_name: Self::module_name_text(name).to_string(),
3018                            module: request,
3019                        });
3020                    }
3021                    None => {
3022                        self.module_meta()
3023                            .exports
3024                            .push(ExportEntry::Star { module: request });
3025                    }
3026                }
3027            }
3028        }
3029        Ok(())
3030    }
3031
3032    /// The names a declaration binds, which is what `export <decl>` exports.
3033    fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
3034        match &stmt.kind {
3035            StmtKind::VarDecl(decl) => {
3036                for declarator in &decl.declarators {
3037                    let mut names = Vec::new();
3038                    declarator.target.bound_names(&mut names);
3039                    out.extend(names.into_iter().map(|name| name.name));
3040                }
3041            }
3042            StmtKind::FuncDecl(func) => {
3043                if let Some(name) = &func.name {
3044                    out.push(name.name.clone());
3045                }
3046            }
3047            StmtKind::ClassDecl(class) => {
3048                if let Some(name) = &class.name {
3049                    out.push(name.name.clone());
3050                }
3051            }
3052            _ => {}
3053        }
3054    }
3055
3056    /// The closure-variable index of a module binding, declaring it if the name was
3057    /// exported without being declared here.
3058    ///
3059    /// `export { x }` where `x` is not declared in the module is a link-time
3060    /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
3061    fn module_binding_index(&mut self, name: &str) -> u32 {
3062        if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
3063            return index as u32;
3064        }
3065        self.declare_module_var(name, &VarDef::lexical(name.to_string()))
3066    }
3067
3068    fn exports_local(&mut self, export_name: &str, var_idx: u32) {
3069        self.module_meta().exports.push(ExportEntry::Local {
3070            export_name: export_name.to_string(),
3071            var_idx,
3072        });
3073    }
3074
3075    /// The hidden `*default*` binding `export default <expr>` stores into.
3076    fn declare_export_default(&mut self) -> u32 {
3077        const DEFAULT: &str = "*default*";
3078        if let Some(index) = self
3079            .cur()
3080            .closure_vars
3081            .iter()
3082            .position(|c| c.name == DEFAULT)
3083        {
3084            return index as u32;
3085        }
3086        self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
3087    }
3088
3089    /// The module tables, which only the top-level state has.
3090    fn module_meta(&mut self) -> &mut ModuleMeta {
3091        self.state()
3092            .module
3093            .as_mut()
3094            .expect("module tables are only touched while compiling a module")
3095    }
3096
3097    /// The index of `specifier`'s request, adding it if it is new.
3098    ///
3099    /// Deduplicated on the specifier *and* its attributes: the same file imported once as
3100    /// JSON and once as text is two modules with two different contents, which is exactly
3101    /// what `hello_module.js` does.
3102    fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
3103        let attributes: Vec<(String, String)> = attributes
3104            .iter()
3105            .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
3106            .collect();
3107        let meta = self.module_meta();
3108        if let Some(index) = meta
3109            .requests
3110            .iter()
3111            .position(|request| request.specifier == specifier && request.attributes == attributes)
3112        {
3113            return index as u32;
3114        }
3115        meta.requests.push(ModuleRequest {
3116            specifier: specifier.to_string(),
3117            attributes,
3118        });
3119        meta.requests.len() as u32 - 1
3120    }
3121
3122    /// Compile a loop body with a `break`/`continue` target pushed for it.
3123    fn loop_body(
3124        &mut self,
3125        body: &Stmt,
3126        labels: &[String],
3127        continue_label: Label,
3128        break_label: Label,
3129    ) -> Result<(), SyntaxError> {
3130        self.push_jump_target(JumpTarget {
3131            names: labels.to_vec(),
3132            break_label: Some(break_label),
3133            continue_label: Some(continue_label),
3134            // A loop leaves nothing of its own on the value stack.
3135            drop_count: 0,
3136            finally_label: None,
3137            is_regular_stmt: false,
3138            has_iterator: false,
3139            is_async_iterator: false,
3140        });
3141        let result = self.stmt(body);
3142        self.pop_jump_target();
3143        result
3144    }
3145
3146    fn push_jump_target(&mut self, target: JumpTarget) {
3147        self.state().jump_targets.push(target);
3148    }
3149
3150    fn pop_jump_target(&mut self) {
3151        self.state().jump_targets.pop();
3152    }
3153
3154    fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3155        let (label, is_break) = match &stmt.kind {
3156            StmtKind::Break(label) => (label.as_ref(), true),
3157            StmtKind::Continue(label) => (label.as_ref(), false),
3158            _ => unreachable!("control_transfer is only called for break and continue"),
3159        };
3160
3161        // Walk outward from the innermost construct. Everything considered before
3162        // the match is a construct control is leaving, and leaving it has a cost:
3163        // its stack slots go, and its finalizer runs.
3164        let targets = self.cur().jump_targets.clone();
3165        for target in targets.iter().rev() {
3166            let destination = match (label, is_break) {
3167                // An unlabelled `break` skips a labelled non-loop statement: `break`
3168                // may name one, but the bare form only means "leave the loop".
3169                (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3170                (None, false) => target.continue_label,
3171                (Some(name), true) => target
3172                    .break_label
3173                    .filter(|_| target.names.contains(&name.name)),
3174                (Some(name), false) => target
3175                    .continue_label
3176                    .filter(|_| target.names.contains(&name.name)),
3177            };
3178
3179            if let Some(destination) = destination {
3180                self.emit_jump(Opcode::Goto, destination, &[]);
3181                return Ok(());
3182            }
3183
3184            // Closing the iterator consumes the three slots the loop keeps on the
3185            // stack (iterator, next method, catch offset), so those are not dropped
3186            // again below.
3187            let mut remaining = target.drop_count;
3188            if target.has_iterator {
3189                self.emit_iterator_close(target.is_async_iterator, false);
3190                remaining = remaining.saturating_sub(3);
3191            }
3192            for _ in 0..remaining {
3193                self.emit(Opcode::Drop, &[]);
3194            }
3195            if let Some(finally) = target.finally_label {
3196                // The finalizer runs as a subroutine and is handed a dummy return
3197                // value, which is dropped afterwards to keep the stack the depth it
3198                // had before.
3199                self.emit(Opcode::Undefined, &[]);
3200                self.emit_jump(Opcode::Gosub, finally, &[]);
3201                self.emit(Opcode::Drop, &[]);
3202            }
3203        }
3204
3205        // The parser rejects a break/continue with no target, so reaching here
3206        // means the compiler's own bookkeeping is wrong.
3207        Err(SyntaxError::new(
3208            if is_break {
3209                "break has no enclosing loop or switch"
3210            } else {
3211                "continue has no enclosing loop"
3212            },
3213            stmt.span,
3214        ))
3215    }
3216
3217    /// Compile a labelled statement.
3218    ///
3219    /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3220    /// that loop's targets, so the chain is collected and handed to the loop. A
3221    /// label on a non-loop statement only provides a `break` target, because
3222    /// `continue` may not target it.
3223    fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3224        let mut names = vec![label.name.clone()];
3225        let mut inner = body;
3226        while let StmtKind::Labeled {
3227            label: next,
3228            body: deeper,
3229        } = &inner.kind
3230        {
3231            names.push(next.name.clone());
3232            inner = deeper;
3233        }
3234        if Self::is_loop(inner) {
3235            return self.stmt_labelled(inner, &names);
3236        }
3237        let end = self.new_label();
3238        self.push_jump_target(JumpTarget {
3239            names,
3240            break_label: Some(end),
3241            continue_label: None,
3242            drop_count: 0,
3243            finally_label: None,
3244            is_regular_stmt: true,
3245            has_iterator: false,
3246            is_async_iterator: false,
3247        });
3248        let result = self.stmt(inner);
3249        self.pop_jump_target();
3250        result?;
3251        self.place_label(end);
3252        let _ = stmt;
3253        Ok(())
3254    }
3255
3256    /// Whether a statement is a loop, i.e. a valid target for `continue`.
3257    fn is_loop(stmt: &Stmt) -> bool {
3258        matches!(
3259            stmt.kind,
3260            StmtKind::While { .. }
3261                | StmtKind::DoWhile { .. }
3262                | StmtKind::For { .. }
3263                | StmtKind::ForIn { .. }
3264                | StmtKind::ForOf { .. }
3265        )
3266    }
3267
3268    /// Compile `switch`.
3269    ///
3270    /// The discriminant is evaluated once and stays on the value stack while the
3271    /// clauses compare against copies of it, so it is dropped at the end — which is
3272    /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3273    /// clause's body jumps over the *next* clause's tests straight into its body.
3274    ///
3275    /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3276    /// the next run's tests. Only the last run's miss reaches the `default` body, or
3277    /// the end of the switch when there is no `default`. That failure path can point
3278    /// backwards (`default` written first), so the runs and their labels are worked
3279    /// out before any code is emitted.
3280    fn switch(
3281        &mut self,
3282        discriminant: &Expr,
3283        cases: &[SwitchCase],
3284        stmt: &Stmt,
3285    ) -> Result<(), SyntaxError> {
3286        self.reset_value();
3287        // The discriminant is evaluated outside the switch's block scope, before
3288        // any `case` clause exists.
3289        self.expr(discriminant)?;
3290
3291        let switch_key = stmt.span.start.offset as u64;
3292        let switch_parent = self.cur().current_block;
3293        self.push_block(switch_key, switch_parent);
3294        self.emit_scope_enter(switch_key);
3295
3296        let break_label = self.new_label();
3297        self.push_jump_target(JumpTarget {
3298            names: Vec::new(),
3299            break_label: Some(break_label),
3300            // `switch` is a valid `break` target but not a `continue` target.
3301            continue_label: None,
3302            // The discriminant stays on the value stack for the whole statement, so
3303            // a `break` aimed further out has to discard it.
3304            drop_count: 1,
3305            finally_label: None,
3306            is_regular_stmt: false,
3307            has_iterator: false,
3308            is_async_iterator: false,
3309        });
3310
3311        // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3312        // its label to the clause after it, so both tests reach the same body.
3313        let mut runs: Vec<(usize, usize)> = Vec::new();
3314        let mut scan = 0;
3315        while scan < cases.len() {
3316            if cases[scan].test.is_some() {
3317                let mut last = scan;
3318                while last + 1 < cases.len()
3319                    && cases[last].test.is_some()
3320                    && cases[last].body.is_empty()
3321                    && cases[last + 1].test.is_some()
3322                {
3323                    last += 1;
3324                }
3325                runs.push((scan, last));
3326                scan = last + 1;
3327            } else {
3328                scan += 1;
3329            }
3330        }
3331
3332        let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3333        let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3334        let default_at = cases.iter().position(|case| case.test.is_none());
3335        // Where the last run sends control when nothing matched.
3336        let miss_target = match default_at {
3337            Some(index) => body_labels[index],
3338            None => break_label,
3339        };
3340
3341        // When `default` comes first, control has to jump over it to reach the
3342        // tests. It only needs to when some clause actually has a test; otherwise
3343        // the default body is the entry point.
3344        let mut entry = None;
3345        if default_at == Some(0) && !runs.is_empty() {
3346            self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3347            entry = Some(run_labels[0]);
3348        }
3349
3350        let mut index = 0;
3351        let mut run = 0;
3352        let result = (|| -> Result<(), SyntaxError> {
3353            while index < cases.len() {
3354                if cases[index].test.is_some() {
3355                    let (first, last) = runs[run];
3356                    // Reaching these tests from the preceding body is a
3357                    // fallthrough, which continues inside the body and skips them.
3358                    if index > 0 {
3359                        self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3360                    }
3361                    if let Some(label) = entry.take() {
3362                        self.place_label(label);
3363                    }
3364                    self.place_label(run_labels[run]);
3365
3366                    for (offset, case) in cases[first..=last].iter().enumerate() {
3367                        let test = case.test.as_ref().unwrap();
3368                        self.emit(Opcode::Dup, &[]);
3369                        self.expr(test)?;
3370                        self.emit(Opcode::StrictEq, &[]);
3371                        if first + offset < last {
3372                            self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3373                        } else {
3374                            // Hand over to the next run's tests, or give up.
3375                            let next = match runs.get(run + 1) {
3376                                Some(_) => run_labels[run + 1],
3377                                None => miss_target,
3378                            };
3379                            self.emit_jump(Opcode::IfFalse, next, &[]);
3380                        }
3381                    }
3382
3383                    self.place_label(body_labels[index]);
3384                    for case in &cases[first..=last] {
3385                        self.stmts(&case.body)?;
3386                    }
3387                    index = last + 1;
3388                    run += 1;
3389                } else {
3390                    // `default`: control arrives here either by falling through or
3391                    // because every test missed.
3392                    self.place_label(body_labels[index]);
3393                    self.stmts(&cases[index].body)?;
3394                    index += 1;
3395                }
3396            }
3397            Ok(())
3398        })();
3399
3400        if result.is_ok() {
3401            self.place_label(break_label);
3402            // Discard the discriminant now that no test needs it.
3403            self.emit(Opcode::Drop, &[]);
3404        }
3405
3406        self.pop_jump_target();
3407        self.emit_scope_leave(switch_key);
3408        self.state().current_block = switch_parent;
3409        result
3410    }
3411
3412    /// Compile `try`/`catch`/`finally`.
3413    ///
3414    /// The shape is an exception table built out of `catch` instructions, each of
3415    /// which records where control goes if the instructions that follow raise:
3416    ///
3417    /// ```text
3418    /// catch HANDLER            <- if the guarded block throws, jump to HANDLER
3419    ///   <guarded block>
3420    ///   drop                   <- discard the catch offset
3421    ///   undefined; gosub FINALLY; drop
3422    ///   goto END
3423    /// HANDLER:
3424    ///   <bind the catch parameter>
3425    ///   catch CATCH2           <- if the handler itself throws, go to CATCH2
3426    ///   <handler body>
3427    ///   drop; undefined; gosub FINALLY; drop; goto END
3428    /// CATCH2:
3429    ///   gosub FINALLY; throw   <- run the finalizer, then let the error out
3430    /// FINALLY:
3431    ///   <finalizer>
3432    ///   ret                    <- return to the `gosub`
3433    /// END:
3434    /// ```
3435    ///
3436    /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
3437    /// of the finalizer serves the normal path, the handler path and the
3438    /// propagating-exception path.
3439    ///
3440    /// The `undefined` before each `gosub` is a dummy return value: the finalizer
3441    /// runs with `ret_value` on the stack, and the normal path has no value to
3442    /// keep, so it pushes one to keep the stack depth identical on every path.
3443    fn try_stmt(
3444        &mut self,
3445        stmt: &Stmt,
3446        block: &[Stmt],
3447        handler: &Option<CatchClause>,
3448        finalizer: Option<&[Stmt]>,
3449    ) -> Result<(), SyntaxError> {
3450        self.reset_value();
3451
3452        let catch_label = self.new_label();
3453        let catch2_label = self.new_label();
3454        let finally_label = self.new_label();
3455        let end_label = self.new_label();
3456
3457        self.emit_jump(Opcode::Catch, catch_label, &[]);
3458
3459        // The guarded block. `break` may not target it, so its entry exists purely
3460        // to unwind: a jump out has to discard the catch offset and run the
3461        // finalizer.
3462        self.push_jump_target(JumpTarget {
3463            names: Vec::new(),
3464            break_label: None,
3465            continue_label: None,
3466            drop_count: 1,
3467            finally_label: Some(finally_label),
3468            is_regular_stmt: false,
3469            has_iterator: false,
3470            is_async_iterator: false,
3471        });
3472
3473        let block_key = Self::try_block_key(stmt, TryPart::Block);
3474        let block_parent = self.cur().current_block;
3475        self.push_block(block_key, block_parent);
3476        self.emit_scope_enter(block_key);
3477        self.stmts(block)?;
3478        self.emit_scope_leave(block_key);
3479        self.state().current_block = block_parent;
3480        // A guarded block that ends in a `return`/`throw` never reaches the
3481        // epilogue, so the reference does not emit one.
3482        self.pop_jump_target();
3483        let block_live = !block.last().is_some_and(Self::terminates);
3484
3485        if block_live {
3486            self.emit(Opcode::Drop, &[]);
3487            self.emit(Opcode::Undefined, &[]);
3488            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3489            self.emit(Opcode::Drop, &[]);
3490            self.emit_jump(Opcode::Goto, end_label, &[]);
3491        }
3492
3493        if let Some(handler) = handler {
3494            self.place_label(catch_label);
3495            // The thrown value is on top of the stack: bind it, or discard it for
3496            // `catch { }`.
3497            match &handler.param {
3498                Some(pattern) => {
3499                    // The stores resolve the names, so they have to run inside the
3500                    // parameter's own scope; otherwise a same-named `catch` further out
3501                    // could win. A `catch` binding is never in the dead zone, so the store
3502                    // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
3503                    let param_key = Self::try_block_key(stmt, TryPart::Param);
3504                    let param_parent = self.cur().current_block;
3505                    self.push_block(param_key, param_parent);
3506                    self.destructure(pattern, Some(VarDeclKind::Var))?;
3507                    self.state().current_block = param_parent;
3508                }
3509                None => self.emit(Opcode::Drop, &[]),
3510            }
3511            self.emit_jump(Opcode::Catch, catch2_label, &[]);
3512
3513            self.push_jump_target(JumpTarget {
3514                names: Vec::new(),
3515                break_label: None,
3516                continue_label: None,
3517                drop_count: 1,
3518                finally_label: Some(finally_label),
3519                is_regular_stmt: false,
3520                has_iterator: false,
3521                is_async_iterator: false,
3522            });
3523            let catch_key = Self::try_block_key(stmt, TryPart::Catch);
3524            let catch_parent = self.cur().current_block;
3525            self.push_block(catch_key, catch_parent);
3526            self.emit_scope_enter(catch_key);
3527            self.stmts(&handler.body)?;
3528            self.emit_scope_leave(catch_key);
3529            self.state().current_block = catch_parent;
3530            self.pop_jump_target();
3531            let handler_live = !handler.body.last().is_some_and(Self::terminates);
3532
3533            if handler_live {
3534                self.emit(Opcode::Drop, &[]);
3535                self.emit(Opcode::Undefined, &[]);
3536                self.emit_jump(Opcode::Gosub, finally_label, &[]);
3537                self.emit(Opcode::Drop, &[]);
3538                self.emit_jump(Opcode::Goto, end_label, &[]);
3539            }
3540
3541            // An error raised inside the handler still has to run the finalizer.
3542            self.place_label(catch2_label);
3543            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3544            self.emit(Opcode::Throw, &[]);
3545        } else {
3546            // `try`/`finally` with no handler: the finalizer runs, then the error
3547            // keeps propagating.
3548            self.place_label(catch_label);
3549            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3550            self.emit(Opcode::Throw, &[]);
3551        }
3552
3553        self.place_label(finally_label);
3554        // Inside the finalizer, leaving has a different cost: the return value and
3555        // the `gosub` return address are both on the stack, and neither finalizer nor
3556        // any outer one may run before the block has finished.
3557        self.push_jump_target(JumpTarget {
3558            names: Vec::new(),
3559            break_label: None,
3560            continue_label: None,
3561            drop_count: 2,
3562            finally_label: None,
3563            is_regular_stmt: false,
3564            has_iterator: false,
3565            is_async_iterator: false,
3566        });
3567        if let Some(finalizer) = finalizer {
3568            let finally_key = Self::try_block_key(stmt, TryPart::Finally);
3569            let finally_parent = self.cur().current_block;
3570            self.push_block(finally_key, finally_parent);
3571            self.emit_scope_enter(finally_key);
3572            self.stmts(finalizer)?;
3573            self.emit_scope_leave(finally_key);
3574            self.state().current_block = finally_parent;
3575        }
3576        self.pop_jump_target();
3577        self.emit(Opcode::Ret, &[]);
3578        self.place_label(end_label);
3579        Ok(())
3580    }
3581
3582    /// Compile `for`/`in` and `for`/`of`.
3583    ///
3584    /// Both keep an enumeration record on the value stack for the whole loop, which
3585    /// is what makes leaving early expensive: the record has to be dropped, or the
3586    /// iterator closed. The layout is
3587    ///
3588    /// ```text
3589    ///   <iterated expression>
3590    ///   for_in_start | for_of_start      <- pushes the record
3591    ///   goto TEST
3592    /// NEXT:
3593    ///   <bind the loop variable>
3594    ///   <body>
3595    /// TEST:
3596    ///   for_in_next | for_of_next 0
3597    ///   if_false NEXT                    <- not finished: next iteration
3598    ///   drop                             <- finished: discard the leftover value
3599    /// BREAK:
3600    ///   drop | iterator_close            <- the one cleanup `break` also uses
3601    /// ```
3602    ///
3603    /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
3604    /// normal exit share one copy — which is why `break` inside the loop emits nothing
3605    /// of its own, and only a jump that passes *through* the loop pays for its record.
3606    fn for_in_of(
3607        &mut self,
3608        stmt: &Stmt,
3609        left: &ForHead,
3610        right: &Expr,
3611        body: &Stmt,
3612        kind: ForLoopKind,
3613        labels: &[String],
3614    ) -> Result<(), SyntaxError> {
3615        self.reset_value();
3616
3617        let loop_key = stmt.span.start.offset as u64;
3618        let loop_parent = self.cur().current_block;
3619        self.push_block(loop_key, loop_parent);
3620        self.emit_scope_enter(loop_key);
3621
3622        // The iterated expression is evaluated inside the loop's scope, after the
3623        // bindings exist in the temporal dead zone.
3624        self.expr(right)?;
3625
3626        let next = self.new_label();
3627        let test = self.new_label();
3628        let break_target = self.new_label();
3629
3630        let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
3631        match kind {
3632            ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
3633            ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
3634            ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
3635        }
3636        self.emit_jump(Opcode::Goto, test, &[]);
3637
3638        self.push_jump_target(JumpTarget {
3639            // `outer: for (x of xs) … break outer` needs the name here. Without it the
3640            // loop had no label to break to, and the compiler reported "break has no
3641            // enclosing loop" for a loop that was plainly enclosing it.
3642            names: labels.to_vec(),
3643            break_label: Some(break_target),
3644            continue_label: Some(test),
3645            // Passing through the loop has to dispose of its record. A `for`/`of`
3646            // record is three slots, and closing the iterator consumes all of them.
3647            drop_count: if has_iterator { 3 } else { 1 },
3648            finally_label: None,
3649            is_regular_stmt: false,
3650            has_iterator,
3651            is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
3652        });
3653
3654        self.place_label(next);
3655        self.bind_loop_variable(left)?;
3656
3657        // The reference marks the body with its own label here. Nothing jumps to it
3658        // once the loop is laid out, but it is not decoration: a label between the
3659        // store and the body is why `put_loc v; get_loc v` does *not* fold into
3660        // `set_loc v` when the body starts by reading the loop variable.
3661        let body_label = self.new_label();
3662        self.place_label(body_label);
3663        // `for (using x of …)` disposes once per iteration, so the body is a disposal
3664        // region rather than the whole loop: the resource is the element that this
3665        // iteration produced.
3666        let using_slot = match left {
3667            ForHead::VarDecl(decl) if decl.kind.is_using() => {
3668                decl.declarators
3669                    .first()
3670                    .and_then(|declarator| match &declarator.target.kind {
3671                        PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
3672                        _ => None,
3673                    })
3674            }
3675            _ => None,
3676        };
3677        match using_slot {
3678            Some(slot) => {
3679                let live = !Self::terminates(body);
3680                self.using_region_around(slot, live, |compiler| compiler.stmt(body))?;
3681            }
3682            None => self.stmt(body)?,
3683        }
3684
3685        // §14.7.5.6 `ForIn/OfBodyEvaluation` step 6: a `let`/`const` head gets a **fresh
3686        // binding each iteration**, so a closure the body creates keeps that iteration's
3687        // value. `CloseCaptured` is the same instruction the C-style `for` uses: it swaps in
3688        // a new reference cell holding the current value.
3689        //
3690        // The position is the *end* of the body, not the start: closing before the body
3691        // would leave the closures pointing at the cell the next `put_loc` overwrites, and
3692        // `for (const x of [1,2,3]) fs.push(() => x)` answered `2,3,3` instead of `1,2,3`.
3693        for name in Self::loop_binding_names(left) {
3694            let pos = self.cur().cur_pos;
3695            self.state().insns.push(Insn::CloseCaptured {
3696                name,
3697                block: loop_key,
3698            });
3699            self.state().insn_pos.push(pos);
3700        }
3701        self.place_label(test);
3702        match kind {
3703            ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
3704            ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
3705            ForLoopKind::AwaitOf => {
3706                // The reference's shape: step, `await` the result, then unpack it.
3707                self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
3708                self.emit(Opcode::Await, &[]);
3709                self.state().has_await = true;
3710                self.emit(Opcode::IteratorGetValueDone, &[]);
3711            }
3712        }
3713        self.emit_jump(Opcode::IfFalse, next, &[]);
3714        // The loop is finished; `for_xx_next` left an `undefined` behind.
3715        self.emit(Opcode::Drop, &[]);
3716
3717        self.pop_jump_target();
3718        self.place_label(break_target);
3719        if has_iterator {
3720            // A loop that ran to completion finds its iterator slot already cleared (see
3721            // `iterator_get_value_done`), so this closes only an iterator abandoned by a
3722            // `break` that jumped here.
3723            self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
3724        } else {
3725            self.emit(Opcode::Drop, &[]);
3726        }
3727
3728        self.emit_scope_leave(loop_key);
3729        self.state().current_block = loop_parent;
3730        Ok(())
3731    }
3732
3733    /// The names a `for (let … of/in …)` head declares, which need a fresh cell per
3734    /// iteration. An assignment head (`for (x of …)`) declares nothing, so it is empty.
3735    fn loop_binding_names(left: &ForHead) -> Vec<String> {
3736        let ForHead::VarDecl(decl) = left else {
3737            return Vec::new();
3738        };
3739        if decl.kind == VarDeclKind::Var {
3740            return Vec::new();
3741        }
3742        let mut names = Vec::new();
3743        for declarator in &decl.declarators {
3744            let mut idents = Vec::new();
3745            declarator.target.bound_names(&mut idents);
3746            names.extend(idents.into_iter().map(|ident| ident.name));
3747        }
3748        names
3749    }
3750
3751    /// Store the value `for_xx_next` left on the stack into the loop variable.
3752    fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
3753        // A declaration *initialises* the binding, which is what takes a `let` out of
3754        // the temporal dead zone, so the store is the unchecked form. Assigning to a
3755        // binding declared elsewhere is an ordinary write and keeps its check.
3756        let (pattern, action) = match left {
3757            ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
3758            ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
3759        };
3760        match &pattern.kind {
3761            PatternKind::Ident(name) => {
3762                // `for (using x of …)` validates and snapshots each iteration's value
3763                // before the body runs, which is what makes a non-disposable element fail
3764                // on the iteration that produced it rather than at the end of the loop.
3765                if let ForHead::VarDecl(decl) = left
3766                    && decl.kind.is_using()
3767                {
3768                    let method_slot = self
3769                        .using_method_slot(&name.name)
3770                        .expect("a using binding was declared during hoisting");
3771                    self.emit(
3772                        Opcode::UsingCheck,
3773                        &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3774                    );
3775                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3776                }
3777                self.emit_var(action, &name.name);
3778                Ok(())
3779            }
3780            // Every other target stores through the same path an assignment pattern
3781            // uses, which is what makes `for (a[0] in obj)` write each key into the
3782            // property instead of refusing the loop outright.
3783            _ => self.destructure(
3784                pattern,
3785                match left {
3786                    ForHead::VarDecl(decl) => Some(decl.kind),
3787                    ForHead::Assign(_) => None,
3788                },
3789            ),
3790        }
3791    }
3792
3793    fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
3794        for declarator in &decl.declarators {
3795            let Some(init) = &declarator.init else {
3796                // `var x;` stays `undefined`. A lexical binding is different: it
3797                // has to be *initialised* to leave the temporal dead zone, so the
3798                // compiler supplies an explicit `undefined`.
3799                if decl.kind.is_lexical() {
3800                    // A lexical binding has to be *initialised* to leave the temporal
3801                    // dead zone, and a destructuring one is no different — `let {a}`
3802                    // with no initialiser is a syntax error, but `let [a] = []` still
3803                    // needs `a` to be initialised from an empty source, which the
3804                    // pattern does on its own.
3805                    self.emit(Opcode::Undefined, &[]);
3806                    self.destructure(&declarator.target, Some(decl.kind))?;
3807                }
3808                continue;
3809            };
3810            match &declarator.target.kind {
3811                PatternKind::Ident(name) => {
3812                    self.expr(init)?;
3813                    self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
3814                    if decl.kind.is_using() {
3815                        // `using_check` validates the value and snapshots its dispose
3816                        // method: `value -> value, method`. The snapshot is what makes a
3817                        // later change to `Symbol.dispose` irrelevant, and validating here
3818                        // is what keeps the body from running at all when the value is not
3819                        // disposable.
3820                        let method_slot = self
3821                            .using_method_slot(&name.name)
3822                            .expect("a using binding was declared during hoisting");
3823                        self.emit(
3824                            Opcode::UsingCheck,
3825                            &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3826                        );
3827                        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3828                        self.emit_var(VarAction::PutInit, &name.name);
3829                        continue;
3830                    }
3831                    // A declaration statement produces no value, so nothing is
3832                    // duplicated onto the stack.
3833                    match decl.kind {
3834                        VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
3835                        _ => self.emit_var(VarAction::PutInit, &name.name),
3836                    }
3837                }
3838                _ => {
3839                    // A destructuring declaration keeps nothing on the stack: the
3840                    // pattern consumes the initialiser.
3841                    self.expr(init)?;
3842                    self.destructure(&declarator.target, Some(decl.kind))?;
3843                }
3844            }
3845        }
3846        Ok(())
3847    }
3848
3849    /// Bind a destructuring pattern from the value on top of the stack.
3850    ///
3851    /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
3852    /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
3853    /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
3854    /// *assignment*, where a member expression is a legal target and the store is an
3855    /// ordinary property write.
3856    ///
3857    /// The value is consumed. An assignment expression's own result is the right-hand
3858    /// side, which the caller keeps separately — the spec does not make the pattern's
3859    /// last store produce it.
3860    fn destructure(
3861        &mut self,
3862        pattern: &Pattern,
3863        decl: Option<VarDeclKind>,
3864    ) -> Result<(), SyntaxError> {
3865        match &pattern.kind {
3866            PatternKind::Ident(name) => {
3867                match decl {
3868                    Some(VarDeclKind::Var) | None => {
3869                        self.emit_var(VarAction::Put, &name.name);
3870                    }
3871                    Some(_) => self.emit_var(VarAction::PutInit, &name.name),
3872                }
3873                Ok(())
3874            }
3875            PatternKind::Assign { target, default } => {
3876                // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
3877                // keeps `null`.
3878                //
3879                // The shape is the reference's: test for `undefined`, and when the value is
3880                // present fall **through** to a single store both paths share. The
3881                // alternatives — branching to the store on each side — need a second store
3882                // and a jump between them, which is what the dump used to show.
3883                let has_value = self.new_label();
3884                self.emit(Opcode::Dup, &[]);
3885                self.emit(Opcode::IsUndefined, &[]);
3886                self.emit_jump(Opcode::IfFalse, has_value, &[]);
3887                self.emit(Opcode::Drop, &[]);
3888                self.expr(default)?;
3889                // `var {f = function(){}} = {}` names the function `f`, like a plain
3890                // `var f = function(){}` does. Both pattern forms do it:
3891                // `BindingInitialization` names the value for a *binding* target, and since
3892                // ES2018 `DestructuringAssignmentEvaluation` does the same, so
3893                // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
3894                // no name to give, which is why only an identifier qualifies.
3895                if let PatternKind::Ident(name) = &target.kind {
3896                    self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
3897                }
3898                self.place_label(has_value);
3899                self.destructure(target, decl)
3900            }
3901            PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
3902            PatternKind::Object { properties, rest } => {
3903                self.destructure_object(properties, rest, decl, pattern)
3904            }
3905            PatternKind::Member(member) if decl.is_none() => {
3906                // An assignment pattern may store into a property. The value is on the
3907                // stack, so the receiver and the key go above it and `rot3l`/`swap2`
3908                // put the three in the order `put_array_el`/`put_field` expect.
3909                self.expr(&member.object)?;
3910                match &member.property {
3911                    MemberProp::Ident(name) => {
3912                        // `value obj` -> `obj value`, the order `put_field` takes.
3913                        // Nothing needs to be left behind: a pattern element's value is
3914                        // consumed by its own store.
3915                        self.emit(Opcode::Swap, &[]);
3916                        self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
3917                    }
3918                    MemberProp::Computed(index) => {
3919                        self.expr(index)?;
3920                        // `value obj key` -> `obj key value`.
3921                        self.emit(Opcode::Rot3l, &[]);
3922                        self.emit(Opcode::PutArrayEl, &[]);
3923                    }
3924                    MemberProp::Private(name) => {
3925                        // `value obj` -> `obj value`, and the store half of the assignment is
3926                        // the same one `obj.#x = value` uses — only without `insert2`,
3927                        // because a pattern element's value is not wanted back.
3928                        let binding = format!("#{}", name.name);
3929                        let (kind, setter) = self.private_use(&binding, member.span)?;
3930                        self.emit(Opcode::Swap, &[]);
3931                        self.private_store(&binding, kind, setter.as_deref())?;
3932                    }
3933                }
3934                Ok(())
3935            }
3936            PatternKind::Rest(inner) => self.destructure(inner, decl),
3937            PatternKind::Invalid(expr) => {
3938                Err(SyntaxError::new("invalid assignment target", expr.span))
3939            }
3940            _ => Err(SyntaxError::new(
3941                "this destructuring target is not supported by the compiler yet",
3942                pattern.span,
3943            )),
3944        }
3945    }
3946
3947    /// `[…]` on the left: drain an iterator, binding one target per element.
3948    fn destructure_array(
3949        &mut self,
3950        elements: &[Option<PatternElement>],
3951        rest: &Option<Box<RestElement>>,
3952        decl: Option<VarDeclKind>,
3953    ) -> Result<(), SyntaxError> {
3954        // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
3955        // pattern accepts any iterable and closes the iterator when the pattern ends
3956        // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
3957        // first because it is on top.
3958        self.emit(Opcode::ForOfStart, &[]);
3959        for element in elements {
3960            self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
3961            self.emit(Opcode::Drop, &[]);
3962            match element {
3963                Some(PatternElement::Pattern(pattern)) => self.destructure(pattern, decl)?,
3964                Some(PatternElement::Property { span, .. }) => {
3965                    return Err(SyntaxError::new(
3966                        "a property pattern is not a valid array element",
3967                        *span,
3968                    ));
3969                }
3970                // An elision skips the value, which is already on the stack.
3971                None => self.emit(Opcode::Drop, &[]),
3972            }
3973        }
3974        if let Some(rest) = rest {
3975            // The remaining values go into a fresh array. The target and its running
3976            // index stay on the stack above the iterator, which is what the operand of
3977            // `for_of_next` accounts for: two values sit above the iterator triple.
3978            self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
3979            self.emit(Opcode::Push0, &[]);
3980            let top = self.new_label();
3981            self.place_label(top);
3982            self.emit(Opcode::ForOfNext, &[Op::Int(2)]);
3983            let done = self.new_label();
3984            self.emit_jump(Opcode::IfTrue, done, &[]);
3985            self.emit(Opcode::DefineArrayEl, &[]);
3986            self.emit(Opcode::Inc, &[]);
3987            self.emit_jump(Opcode::Goto, top, &[]);
3988            self.place_label(done);
3989            self.emit(Opcode::Drop, &[]);
3990            self.emit(Opcode::Drop, &[]);
3991            self.destructure_rest(rest, decl)?;
3992        }
3993        self.emit(Opcode::IteratorClose, &[]);
3994        Ok(())
3995    }
3996
3997    /// `{…}` on the left: read properties off one boxed source object.
3998    fn destructure_object(
3999        &mut self,
4000        properties: &[Option<PatternElement>],
4001        rest: &Option<Box<RestElement>>,
4002        decl: Option<VarDeclKind>,
4003        pattern: &Pattern,
4004    ) -> Result<(), SyntaxError> {
4005        // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
4006        // aside for the rest element below.
4007        self.emit(Opcode::ToObject, &[]);
4008        let mut taken: Vec<Wtf8> = Vec::new();
4009        // Whether any key was computed, which a rest element cannot exclude.
4010        let mut computed = false;
4011        for property in properties {
4012            let Some(PatternElement::Property {
4013                key, value, span, ..
4014            }) = property
4015            else {
4016                return Err(SyntaxError::new(
4017                    "a bare pattern is not a valid object property",
4018                    properties
4019                        .iter()
4020                        .flatten()
4021                        .map(|element| match element {
4022                            PatternElement::Pattern(pattern) => pattern.span,
4023                            PatternElement::Property { span, .. } => *span,
4024                        })
4025                        .next()
4026                        .unwrap_or(pattern.span),
4027                ));
4028            };
4029            // Every read needs the source twice: to read from, and to keep for the next
4030            // property. `get_field2` is that duplicate-and-read in one instruction, but it
4031            // leaves the copy *under* the value, so it is only usable when whatever
4032            // consumes the value tolerates that. See [`reads_with_get_field2`].
4033            let nested = reads_with_get_field2(decl, value);
4034            if !nested {
4035                self.emit(Opcode::Dup, &[]);
4036            }
4037            match key {
4038                PropName::Literal(literal) => {
4039                    let name = self.property_key_text(literal, *span)?;
4040                    taken.push(name.clone());
4041                    self.emit(
4042                        if nested {
4043                            Opcode::GetField2
4044                        } else {
4045                            Opcode::GetField
4046                        },
4047                        &[Op::Atom(Atom::from_wtf8(&name))],
4048                    );
4049                }
4050                PropName::Computed(index) => {
4051                    // A computed key has no name to exclude ahead of time, so a rest
4052                    // element that has to skip it is refused below rather than silently
4053                    // copying the property into the rest object.
4054                    computed = true;
4055                    self.expr(index)?;
4056                    self.emit(Opcode::GetArrayEl, &[]);
4057                }
4058                PropName::Private(_) => {
4059                    return Err(SyntaxError::new(
4060                        "private fields are not supported by the compiler yet",
4061                        value.span,
4062                    ));
4063                }
4064            }
4065            self.destructure(value, decl)?;
4066        }
4067        match rest {
4068            Some(rest) => {
4069                if computed {
4070                    return Err(SyntaxError::new(
4071                        "a computed key with a rest element is not supported by the compiler yet",
4072                        Self::rest_span(rest),
4073                    ));
4074                }
4075                // `target src exclude`: the exclusion list is an array of the keys the
4076                // literal part already took, so the rest object gets only the others.
4077                self.emit(Opcode::Object, &[]);
4078                self.emit(Opcode::Swap, &[]);
4079                for name in &taken {
4080                    self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
4081                }
4082                self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
4083                self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4084                self.emit(Opcode::Drop, &[]);
4085                self.emit(Opcode::Drop, &[]);
4086                self.destructure_rest(rest, decl)?;
4087            }
4088            // The source was only kept for a rest element.
4089            None => self.emit(Opcode::Drop, &[]),
4090        }
4091        Ok(())
4092    }
4093
4094    /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
4095    fn destructure_rest(
4096        &mut self,
4097        rest: &RestElement,
4098        decl: Option<VarDeclKind>,
4099    ) -> Result<(), SyntaxError> {
4100        match rest {
4101            RestElement::Pattern(pattern) => self.destructure(pattern, decl),
4102            // `[...a.b] = c` stores into a property.
4103            RestElement::Member(member) => {
4104                let pattern = Pattern {
4105                    kind: PatternKind::Member(member.clone()),
4106                    span: member.span,
4107                };
4108                self.destructure(&pattern, decl)
4109            }
4110        }
4111    }
4112
4113    /// The source range of a rest element, for error messages.
4114    fn rest_span(rest: &RestElement) -> Span {
4115        match rest {
4116            RestElement::Pattern(pattern) => pattern.span,
4117            RestElement::Member(member) => member.span,
4118        }
4119    }
4120
4121    /// Compile a function declaration and queue it for instantiation at scope
4122    /// entry.
4123    ///
4124    /// A declaration is visible before the statement that declares it, so the
4125    /// code that creates the function object belongs at the top of the enclosing
4126    /// scope, not at the declaration.
4127    fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
4128        let name = func.name.as_ref().expect("a declaration has a name");
4129        let function = self.compile_function(func)?;
4130        let pool_index = self.push_constant(Constant::Function(Box::new(function)));
4131        let target = self.hoist_target(&name.name);
4132        let block = self.cur().current_block;
4133        self.state().hoisted.push((block, target, pool_index));
4134        Ok(())
4135    }
4136
4137    /// Where a name lives, for a hoisted declaration.
4138    fn hoist_target(&self, name: &str) -> HoistTarget {
4139        let state = self.cur();
4140        if let Some(index) = state.args.iter().position(|a| a.name == name) {
4141            return HoistTarget::Arg(index as u32);
4142        }
4143        if let Some(index) = state.vars.iter().position(|v| v.name == name) {
4144            return HoistTarget::Loc(index as u32);
4145        }
4146        // A global function declaration is not a slot at all.
4147        HoistTarget::Global(name.to_string())
4148    }
4149
4150    // -- expressions -------------------------------------------------------
4151
4152    /// Compile one expression, recording where its instructions sit.
4153    ///
4154    /// The position is the node's operator when it has one and its first token
4155    /// otherwise, and it is restored on the way out so a parent's own instructions —
4156    /// which are emitted *after* its children — are blamed on the parent. Without the
4157    /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4158    fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4159        // `discard_value` belongs to the *statement* that is about to be compiled, so it
4160        // may only be honoured by that statement's own top-level expression. Taking it here
4161        // is what enforces that: `f(x = 1)` sets it for the call, and the assignment inside
4162        // the argument list is a different expression — it must still leave its value on the
4163        // stack. Without this the argument vanished, and `call` then consumed the callee as
4164        // its argument (`TypeError: undefined is not a function` from `f(x = 1)` inside any
4165        // function).
4166        self.discard_root = std::mem::take(&mut self.state().discard_value);
4167        let saved = self.cur().cur_pos;
4168        // Only the node kinds the reference calls `emit_source_pos` for record a position:
4169        // the operator a node exists for, and a variable *read*, which the reference
4170        // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4171        // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4172        // start, a parenthesised group, an anonymous function expression — leaves the
4173        // previous position in place, because a table entry the reference never writes is
4174        // one we must not write either: the instruction that inherits a position (the
4175        // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4176        // report a more recent token than the reference does.
4177        let pos = expr.op_pos.or(match &expr.kind {
4178            ExprKind::Ident(ident) => Some(ident.span.start),
4179            _ => None,
4180        });
4181        match pos {
4182            Some(pos) => self.state().cur_pos = Some(pos),
4183            // A node the reference records nothing for: its own instructions stay
4184            // unpositioned, so they inherit whatever was written last — which is what an
4185            // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4186            // enclosing position instead would blame them on a token the reference has not
4187            // reached yet: a spread's `iterator_open` reports the expression it follows, and
4188            // a template's `to_propkey` the interpolation.
4189            None => self.state().cur_pos = None,
4190        }
4191        // Note a direct `eval` call before compiling it, because the *whole* function
4192        // is affected: an eval can name any binding the function declares, so every one
4193        // of them has to live in a cell for a closure it creates to capture it.
4194        if Self::is_direct_eval(expr) {
4195            // Every enclosing function is affected too: the eval sees the whole scope
4196            // chain, and a closure it creates can capture a binding of any of them.
4197            // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a
4198            // cell, because the closure the eval builds outlives the loop iteration.
4199            for state in &mut self.stack {
4200                state.has_direct_eval = true;
4201            }
4202            let block = self.cur().current_block;
4203            let in_params = self.cur().in_params;
4204            self.state()
4205                .pending_eval_sites
4206                .push((expr.span, block, in_params));
4207        }
4208        let result = self.expr_inner(expr);
4209        self.discard_root = false;
4210        self.state().cur_pos = saved;
4211        result
4212    }
4213
4214    /// Record which bindings are in scope at a direct `eval` call.
4215    ///
4216    /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
4217    /// resolves names from a string at run time, so the only chance to pin down *which*
4218    /// slot a name means is here. Visibility is the lexical rule: a binding counts when
4219    /// its block is the current block, an enclosing one, or the function scope.
4220    fn materialize_eval_sites(&mut self) {
4221        let pending = std::mem::take(&mut self.state().pending_eval_sites);
4222        for (span, site_block, in_params) in pending {
4223            self.resolve_eval_site(span, site_block, in_params);
4224        }
4225    }
4226
4227    /// Resolve the bindings visible at one `eval` call.
4228    fn resolve_eval_site(&mut self, span: Span, site_block: u64, site_in_params: bool) {
4229        /// How near a binding is: function distance first, then block depth, then the
4230        /// later declaration (which shadows the earlier one in the same block).
4231        type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
4232
4233        // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
4234        // walked, innermost function first: a direct `eval` sees every enclosing
4235        // function's bindings, and none of them can be resolved at run time because the
4236        // runtime only has names to go on.
4237        let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
4238        let deepest = self.stack.len() - 1;
4239        for (level, state) in self.stack.iter().enumerate().rev() {
4240            let owner = (deepest - level) as u32;
4241            // The innermost function's block is the one the call sat in, which is not
4242            // the block the compiler is in now; the enclosing functions are still at
4243            // the point where this one was created.
4244            let here = if level == deepest {
4245                site_block
4246            } else {
4247                state.current_block
4248            };
4249            // The chain of live blocks, innermost first, with a depth for each. The walk
4250            // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
4251            // block can start at source offset zero.
4252            let mut live: Vec<(u64, usize)> = vec![(here, 0)];
4253            let mut block = here;
4254            while let Some(parent) = state
4255                .blocks
4256                .iter()
4257                .find(|candidate| candidate.key == block)
4258                .map(|candidate| candidate.parent)
4259                .filter(|parent| *parent != NO_PARENT)
4260                .filter(|parent| parent != &block)
4261            {
4262                live.push((parent, live.len()));
4263                block = parent;
4264            }
4265            let depth_of = |key: u64| {
4266                live.iter()
4267                    .find(|(candidate, _)| *candidate == key)
4268                    .map(|(_, depth)| *depth)
4269                    // The function scope is the outermost depth there is. A binding of a
4270                    // block this site is not inside lands here too, which pushes it
4271                    // behind every live one — the right answer: it is out of scope.
4272                    .unwrap_or(live.len())
4273            };
4274            for (index, arg) in state.args.iter().enumerate() {
4275                bindings.push((
4276                    (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
4277                    EvalVisible {
4278                        name: arg.name.clone(),
4279                        is_arg: true,
4280                        index: index as u32,
4281                        owner,
4282                    },
4283                ));
4284            }
4285            // A parameter list cannot see the body, so a body `var` is not a binding the
4286            // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
4287            // not let that eval write the body's `c`.
4288            let hides_body = if level == deepest {
4289                site_in_params
4290            } else {
4291                state.created_in_params
4292            };
4293            for (index, var) in state.vars.iter().enumerate() {
4294                let block = state
4295                    .var_block
4296                    .get(index)
4297                    .copied()
4298                    .unwrap_or(FUNCTION_SCOPE);
4299                if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
4300                    continue;
4301                }
4302                bindings.push((
4303                    (
4304                        owner as usize,
4305                        depth_of(block),
4306                        std::cmp::Reverse(index as u32),
4307                    ),
4308                    EvalVisible {
4309                        name: var.name.clone(),
4310                        is_arg: false,
4311                        index: index as u32,
4312                        owner,
4313                    },
4314                ));
4315            }
4316        }
4317        // Innermost function first, then innermost block, then the later declaration
4318        // (which shadows the earlier one within a block).
4319        bindings.sort_by_key(|(priority, _)| *priority);
4320        let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
4321        self.state().eval_sites.push(EvalSite {
4322            line: span.start.line,
4323            column: span.start.column,
4324            bindings,
4325        });
4326    }
4327
4328    /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
4329    ///
4330    /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
4331    /// a bare identifier callee counts.
4332    fn is_direct_eval(expr: &Expr) -> bool {
4333        matches!(
4334            &expr.kind,
4335            ExprKind::Call { callee, .. }
4336                if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
4337        )
4338    }
4339
4340    fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4341        match &expr.kind {
4342            ExprKind::Number(value) => self.push_number(*value),
4343            ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
4344            ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
4345            ExprKind::Null => self.emit(Opcode::Null, &[]),
4346            ExprKind::String(text) => self.push_string(text),
4347            ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
4348            ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
4349            ExprKind::This => self.this_expression(),
4350            ExprKind::NewTarget => self.new_target_expression(),
4351            ExprKind::Paren(inner) => self.expr(inner)?,
4352            ExprKind::Binary { op, left, right } => {
4353                self.expr(left)?;
4354                self.expr(right)?;
4355                self.emit(binary_opcode(*op), &[]);
4356            }
4357            ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
4358            ExprKind::Unary {
4359                op: UnaryOp::Minus,
4360                argument,
4361            } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
4362                let ExprKind::Number(value) = argument.unparen().kind else {
4363                    unreachable!("matched above")
4364                };
4365                // The reference folds a negative literal only when the negation is
4366                // exact in the integer range: `-1` becomes `push_minus1` and
4367                // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
4368                // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
4369                // `-Infinity`, not `Infinity` — and folding a fraction would change
4370                // which instruction the reference emits.
4371                let negated = -value;
4372                // `-2147483648` is deliberately excluded: its magnitude is one past
4373                // `i32::MAX`, so the reference sends it through the constant pool and
4374                // negates at run time instead.
4375                if value > 0.0
4376                    && negated == negated.trunc()
4377                    && negated >= -(i32::MAX as f64)
4378                    && negated < 0.0
4379                {
4380                    self.push_number(negated);
4381                } else {
4382                    self.push_number(value);
4383                    self.emit(Opcode::Neg, &[]);
4384                }
4385            }
4386            ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
4387            ExprKind::Conditional { test, cons, alt } => {
4388                let else_label = self.new_label();
4389                let end_label = self.new_label();
4390                self.expr(test)?;
4391                self.emit_jump(Opcode::IfFalse, else_label, &[]);
4392                self.expr(cons)?;
4393                self.emit_jump(Opcode::Goto, end_label, &[]);
4394                self.place_label(else_label);
4395                self.expr(alt)?;
4396                self.place_label(end_label);
4397            }
4398            ExprKind::Assign { op, target, value } => {
4399                let discard = std::mem::take(&mut self.discard_root);
4400                self.assign(*op, target, value, discard)?
4401            }
4402            ExprKind::Update {
4403                op,
4404                argument,
4405                prefix,
4406            } => self.update(*op, argument, *prefix)?,
4407            ExprKind::Sequence(items) => {
4408                for (index, item) in items.iter().enumerate() {
4409                    self.expr(item)?;
4410                    if index + 1 != items.len() {
4411                        self.emit(Opcode::Drop, &[]);
4412                    }
4413                }
4414            }
4415            ExprKind::Call { .. } => self.chain_link_top(expr)?,
4416            ExprKind::Member { .. } => self.chain_link_top(expr)?,
4417            ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
4418            ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
4419            ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
4420            ExprKind::Template(template) => self.template_literal(template)?,
4421            ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
4422            ExprKind::New { callee, arguments } => {
4423                // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
4424                // The `dup` is not redundant: `call_constructor` takes the
4425                // constructor twice, once as the target and once as `new.target`,
4426                // which is what makes `new.target === C` inside the body.
4427                self.expr(callee)?;
4428                self.emit(Opcode::Dup, &[]);
4429                let args = arguments.as_deref().unwrap_or(&[]);
4430                if Self::has_spread(args) {
4431                    // `C C array`: the duplicated callee is already both the target
4432                    // and `new.target`, so no reordering is needed before `apply 1`.
4433                    self.argument_array(args)?;
4434                    self.emit(Opcode::Apply, &[Op::Int(1)]);
4435                    return Ok(());
4436                }
4437                for argument in args {
4438                    self.expr(argument)?;
4439                }
4440                self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
4441            }
4442            ExprKind::Class(class) => self.class_definition(class, true)?,
4443            ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
4444            ExprKind::Yield { argument, delegate } => {
4445                self.yield_expression(argument.as_deref(), *delegate)?
4446            }
4447            ExprKind::Await(argument) => self.await_expression(argument)?,
4448            ExprKind::RegExp { pattern, flags } => {
4449                // A literal is compiled *here*, at parse time, not when the line runs. The
4450                // spec is explicit that an invalid pattern is an early error (§12.9.4:
4451                // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
4452                // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
4453                // also validates `\p{…}` names: 163 conformance cases are patterns that have
4454                // to be rejected before any code runs.
4455                //
4456                // This is the whole reason the engine lives in its own crate rather than
4457                // inside `quickjs-pure`: the compiler could not depend on the interpreter
4458                // (`pure` depends on `compile`), but both need this.
4459                // The lexer already rejected an unknown or repeated flag, so an unparsable
4460                // flag string here would be a bug in the lexer rather than in the script;
4461                // fall back to the default flags instead of inventing a second message.
4462                let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
4463                let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
4464                    SyntaxError::new(
4465                        format!("invalid regular expression: {}", error.message),
4466                        expr.span,
4467                    )
4468                })?;
4469                // The tree is thrown away and rebuilt when the literal first runs: keeping it
4470                // would mean serialising the syntax tree into the function's constant pool,
4471                // and a literal is created once per evaluation of its expression anyway.
4472                let _ = parsed;
4473                // The pattern and its flags travel as two string constants; `regexp` builds
4474                // the object. A dedicated opcode (rather than a call to the constructor) is
4475                // what the reference does too, so that a literal never goes through the
4476                // public `RegExp` function and its string-coercion rules.
4477                self.push_string(&Wtf8::new(pattern));
4478                self.push_string(&Wtf8::new(flags));
4479                self.emit(Opcode::Regexp, &[]);
4480            }
4481            ExprKind::Arrow(func) => {
4482                let function = self.compile_function(func)?;
4483                let index = self.push_constant(Constant::Function(Box::new(function)));
4484                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4485            }
4486            ExprKind::Function(func) => {
4487                let function = self.compile_function_with_name(func, true)?;
4488                let index = self.push_constant(Constant::Function(Box::new(function)));
4489                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4490            }
4491            // `import.meta`: the host fills a per-module object at link time.
4492            ExprKind::ImportMeta => {
4493                self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
4494            }
4495            // `import("x")` compiles to a two-slot push followed by one opcode: the
4496            // specifier, then the options object (`undefined` here, since this compiler
4497            // does not accept the second argument yet).
4498            ExprKind::ImportCall(specifier) => {
4499                self.expr(specifier)?;
4500                self.emit(Opcode::Undefined, &[]);
4501                self.emit(Opcode::Import, &[]);
4502            }
4503            ExprKind::PrivateIn { name, object } => {
4504                // `#x in o`: the object, then the binding, then one opcode which decides what
4505                // to do with the second operand. A field's binding holds a symbol and the
4506                // answer is an own-property test; a method's holds a function and the answer
4507                // is a brand check — both live in `private_in`, so the compiler emits the
4508                // same instruction for either.
4509                self.expr(object)?;
4510                self.emit_var(VarAction::Get, &format!("#{}", name.name));
4511                self.emit(Opcode::PrivateIn, &[]);
4512            }
4513            _ => {
4514                return Err(SyntaxError::new(
4515                    "this expression form is not supported by the compiler yet",
4516                    expr.span,
4517                ));
4518            }
4519        }
4520        Ok(())
4521    }
4522
4523    /// Build one array holding the evaluated call arguments, which is how a call
4524    /// containing a spread is compiled: the reference does the same, building the
4525    /// list on the stack and handing it to `apply`.
4526    fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
4527        let elements: Vec<Option<ArrayElement>> = arguments
4528            .iter()
4529            .map(|argument| match &argument.unparen().kind {
4530                ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
4531                _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
4532            })
4533            .collect();
4534        self.array_literal(&elements, Span::default())
4535    }
4536
4537    /// Whether any argument is a spread, which is what selects the `apply` form.
4538    fn has_spread(arguments: &[Expr]) -> bool {
4539        arguments
4540            .iter()
4541            .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
4542    }
4543
4544    /// Compile `a${x}b`.
4545    ///
4546    /// A template is a `+` chain built left to right: the leading chunk (or an empty
4547    /// string when the template starts with a substitution), then for each
4548    /// substitution its value, `to_propkey` and `add`, then the following chunk when
4549    /// it is not empty. `to_propkey` is what makes a number or object substitute the
4550    /// way `ToString` would while leaving the result a string for `add` to
4551    /// concatenate.
4552    ///
4553    /// The chunk is an atom rather than a constant-pool string, because a non-empty
4554    /// chunk always lands where a value is pushed and `push_atom_value` is the
4555    /// instruction the reference uses for it; the empty first chunk has its own
4556    /// zero-byte form.
4557    fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
4558        let first = template.quasis.first();
4559        match first.and_then(|quasi| quasi.cooked.clone()) {
4560            Some(text) if !text.is_empty() => {
4561                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4562            }
4563            // Either the template begins with a substitution, or the chunk is
4564            // empty — in both cases the chain needs a string to start from.
4565            _ => self.emit(Opcode::PushEmptyString, &[]),
4566        }
4567        for (index, expression) in template.expressions.iter().enumerate() {
4568            self.expr(expression)?;
4569            self.emit(Opcode::ToPropkey, &[]);
4570            self.emit(Opcode::Add, &[]);
4571            if let Some(text) = template
4572                .quasis
4573                .get(index + 1)
4574                .and_then(|quasi| quasi.cooked.clone())
4575                && !text.is_empty()
4576            {
4577                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4578                self.emit(Opcode::Add, &[]);
4579            }
4580        }
4581        Ok(())
4582    }
4583
4584    /// Compile an object literal.
4585    ///
4586    /// The object is built in place: `object` pushes it, and each property leaves it
4587    /// on the stack with one field more, so no temporary is needed and later
4588    /// properties can overwrite earlier ones.
4589    ///
4590    /// The instruction depends on *how* the property was written, not on what kind
4591    /// of value it holds:
4592    ///
4593    /// | source | instruction |
4594    /// |---|---|
4595    /// | `{ a: v }` | `define_field a` |
4596    /// | `{ __proto__: v }` | `set_proto` |
4597    /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
4598    /// | `{ m() {} }` | `define_method m,4` |
4599    /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
4600    /// | `{ [k]() {} }` | `define_method_computed 4` |
4601    /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
4602    ///
4603    /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
4604    /// key itself, which is why the trailing `drop` is absent there too.
4605    /// `tag`…``: a call whose first argument is the call site's template object.
4606    ///
4607    /// The template object is a frozen array of the cooked chunks with a frozen `raw`
4608    /// array beside it, so `String.raw` can read the source text back. It is a constant
4609    /// because its contents never change; the reference builds one per call site and
4610    /// reuses it, while this builds one per evaluation, which only `tag` code that
4611    /// compares template objects across calls could tell apart.
4612    fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
4613        let cooked = quasi
4614            .quasis
4615            .iter()
4616            .map(|chunk| chunk.cooked.clone())
4617            .collect();
4618        let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
4619        let index = self.push_constant(Constant::Template { cooked, raw });
4620        let count = quasi.expressions.len() + 1;
4621        // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
4622        if let ExprKind::Member {
4623            object, property, ..
4624        } = &tag.unparen().kind
4625        {
4626            self.expr(object)?;
4627            match property {
4628                MemberProp::Ident(name) => {
4629                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
4630                }
4631                MemberProp::Computed(key) => {
4632                    self.expr(key)?;
4633                    self.emit(Opcode::GetArrayEl2, &[]);
4634                }
4635                MemberProp::Private(name) => {
4636                    let binding = format!("#{}", name.name);
4637                    let (kind, _) = self.private_use(&binding, tag.span)?;
4638                    self.private_callee(&binding, kind)?;
4639                }
4640            }
4641            self.emit(Opcode::PushConst, &[Op::Const(index)]);
4642            for expression in &quasi.expressions {
4643                self.expr(expression)?;
4644            }
4645            self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
4646            return Ok(());
4647        }
4648        self.expr(tag)?;
4649        self.emit(Opcode::PushConst, &[Op::Const(index)]);
4650        for expression in &quasi.expressions {
4651            self.expr(expression)?;
4652        }
4653        self.emit(Opcode::Call, &[Op::Int(count as i32)]);
4654        Ok(())
4655    }
4656
4657    fn object_literal(
4658        &mut self,
4659        properties: &[ObjectProperty],
4660        span: Span,
4661    ) -> Result<(), SyntaxError> {
4662        self.emit(Opcode::Object, &[]);
4663        for property in properties {
4664            match property {
4665                ObjectProperty::Spread(value) => {
4666                    // `copy_data_properties` takes the target, the source and an
4667                    // exclusion list; a literal `null` means "exclude nothing".
4668                    // Flag bit 1 copies symbols, bits 2/5 pick the source and the
4669                    // exclusion list by stack offset.
4670                    self.expr(spread_argument(value))?;
4671                    self.emit(Opcode::Null, &[]);
4672                    self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4673                    self.emit(Opcode::Drop, &[]);
4674                    self.emit(Opcode::Drop, &[]);
4675                }
4676                ObjectProperty::Property {
4677                    key,
4678                    value,
4679                    kind,
4680                    shorthand,
4681                    span: property_span,
4682                } => match key {
4683                    PropName::Computed(key_expr) => {
4684                        self.expr(key_expr)?;
4685                        match kind {
4686                            PropertyKind::Value => {
4687                                self.emit(Opcode::ToPropkey, &[]);
4688                                self.expr(value)?;
4689                                self.set_name_if_anonymous_computed(value);
4690                                self.emit(Opcode::DefineArrayEl, &[]);
4691                                // `define_array_el` leaves the object and the key;
4692                                // the key is no longer needed.
4693                                self.emit(Opcode::Drop, &[]);
4694                            }
4695                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4696                                self.emit_method_function(value)?;
4697                                self.emit(
4698                                    Opcode::DefineMethodComputed,
4699                                    &[Op::Int(define_method_flags(*kind))],
4700                                );
4701                            }
4702                        }
4703                    }
4704                    PropName::Literal(key) => {
4705                        let name = self.property_key_text(key, *property_span)?;
4706                        match kind {
4707                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4708                                self.emit_method_function(value)?;
4709                                self.emit(
4710                                    Opcode::DefineMethod,
4711                                    &[
4712                                        Op::Atom(Atom::from_wtf8(&name)),
4713                                        Op::Int(define_method_flags(*kind)),
4714                                    ],
4715                                );
4716                            }
4717                            PropertyKind::Value => {
4718                                self.expr(value)?;
4719                                // `{__proto__: x}` sets the prototype instead of
4720                                // creating a property; the shorthand `{__proto__}`
4721                                // is an ordinary property and does not.
4722                                if name == "__proto__" && !shorthand {
4723                                    self.emit(Opcode::SetProto, &[]);
4724                                } else {
4725                                    self.set_name_if_anonymous(value, &name);
4726                                    self.emit(
4727                                        Opcode::DefineField,
4728                                        &[Op::Atom(Atom::from_wtf8(&name))],
4729                                    );
4730                                }
4731                            }
4732                        }
4733                    }
4734                    PropName::Private(_) => {
4735                        return Err(SyntaxError::new(
4736                            "private names are not valid in object literals",
4737                            *property_span,
4738                        ));
4739                    }
4740                },
4741            }
4742        }
4743        let _ = span;
4744        Ok(())
4745    }
4746
4747    /// Emit the function a method/accessor property defines.
4748    fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
4749        self.expr(value)
4750    }
4751
4752    /// The name a literal property key contributes.
4753    ///
4754    /// String keys are used as written. A numeric key is converted the way
4755    /// `ToString` would convert it, because the atom is made from that spelling:
4756    /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
4757    fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
4758        match key {
4759            PropKey::Str(text) => Ok(text.clone()),
4760            PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
4761        }
4762    }
4763
4764    /// Compile an optional chain.
4765    ///
4766    /// `?.` short-circuits the *whole remaining spine*, not just its own link:
4767    /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
4768    /// `undefined`. So the chain is compiled with one end label and every guard
4769    /// jumps to it. The parser hands us the extent of that spine as an
4770    /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
4771    /// exactly the scope the label has to cover.
4772    fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
4773        let end = self.new_label();
4774        self.chain_link(inner, end)?;
4775        self.place_label(end);
4776        Ok(())
4777    }
4778
4779    /// A member access or call reached from outside any optional chain.
4780    ///
4781    /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
4782    /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
4783    /// still created because [`Self::chain_link`] takes it, and placing it at the
4784    /// end is a no-op that keeps a single code path.
4785    fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4786        let end = self.new_label();
4787        self.chain_link(expr, end)?;
4788        self.place_label(end);
4789        Ok(())
4790    }
4791
4792    /// One link of a chain, where `end` is the label a `?.` guard jumps to.
4793    fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
4794        match &expr.kind {
4795            ExprKind::Member {
4796                object,
4797                property,
4798                optional,
4799            } => {
4800                // `super.x` is not a lookup on a value: it starts at the home object's
4801                // prototype and keeps `this` as the receiver, so it cannot go through
4802                // `chain_link` and the ordinary field read.
4803                if matches!(object.unparen().kind, ExprKind::SuperProp) {
4804                    self.super_base();
4805                    match property {
4806                        MemberProp::Ident(name) => self.emit(
4807                            Opcode::PushAtomValue,
4808                            &[Op::Atom(Atom::from_text(&name.name))],
4809                        ),
4810                        MemberProp::Computed(index) => self.expr(index)?,
4811                        MemberProp::Private(_) => {
4812                            return Err(SyntaxError::new(
4813                                "private fields are not supported by the compiler yet",
4814                                expr.span,
4815                            ));
4816                        }
4817                    }
4818                    self.emit(Opcode::GetSuperValue, &[]);
4819                    return Ok(());
4820                }
4821                self.chain_link(object, end)?;
4822                if *optional {
4823                    self.optional_guard(end);
4824                }
4825                match property {
4826                    // `.length` has its own opcode. The reference emits it for every
4827                    // object, not just arrays, so a name-based rule is right and
4828                    // cheaper than the generic field read.
4829                    MemberProp::Ident(name) if name.name == "length" => {
4830                        self.emit(Opcode::GetLength, &[]);
4831                    }
4832                    MemberProp::Ident(name) => {
4833                        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
4834                    }
4835                    MemberProp::Computed(index) => {
4836                        self.expr(index)?;
4837                        self.emit(Opcode::GetArrayEl, &[]);
4838                    }
4839                    MemberProp::Private(name) => {
4840                        // The binding comes from the class scope, so a read from outside the
4841                        // class cannot name it at all. `?.` checks the object, not the field:
4842                        // `o?.#x` guards on `o` being nullish.
4843                        let binding = format!("#{}", name.name);
4844                        let (kind, _) = self.private_use(&binding, expr.span)?;
4845                        self.private_load(&binding, kind, expr.span)?;
4846                    }
4847                }
4848                Ok(())
4849            }
4850            ExprKind::Call {
4851                callee,
4852                arguments,
4853                optional,
4854            } => {
4855                // `o.m(args)` has to pass `o` as `this`, which a plain `call`
4856                // cannot: it reads the function and then calls it with no
4857                // receiver at all. The reference's answer is to keep the object
4858                // under the function value — `get_field2` reads a field and leaves
4859                // its base in place — and to use `call_method`, which takes the
4860                // receiver from the stack. Missing this does not just cost an
4861                // instruction, it loses the `this` binding.
4862                if let ExprKind::Member {
4863                    object,
4864                    property,
4865                    optional: member_optional,
4866                } = &callee.unparen().kind
4867                {
4868                    // `super.m()` reads the method off the home object's prototype but
4869                    // calls it with `this`, so the receiver goes under the read instead of
4870                    // being replaced by it.
4871                    if matches!(object.unparen().kind, ExprKind::SuperProp) {
4872                        self.super_base();
4873                        match property {
4874                            MemberProp::Ident(name) => self.emit(
4875                                Opcode::PushAtomValue,
4876                                &[Op::Atom(Atom::from_text(&name.name))],
4877                            ),
4878                            MemberProp::Computed(index) => self.expr(index)?,
4879                            MemberProp::Private(_) => {
4880                                return Err(SyntaxError::new(
4881                                    "private fields are not supported by the compiler yet",
4882                                    expr.span,
4883                                ));
4884                            }
4885                        }
4886                        // The two-output form would drop the receiver; this one replaces
4887                        // the prototype and the key, leaving `this` underneath.
4888                        self.emit(Opcode::GetArrayEl, &[]);
4889                        if Self::has_spread(arguments) {
4890                            self.argument_array(arguments)?;
4891                            self.emit(Opcode::Perm3, &[]);
4892                            self.emit(Opcode::Apply, &[Op::Int(0)]);
4893                            return Ok(());
4894                        }
4895                        for argument in arguments {
4896                            self.expr(argument)?;
4897                        }
4898                        self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4899                        return Ok(());
4900                    }
4901                    self.chain_link(object, end)?;
4902                    if *member_optional {
4903                        self.optional_guard(end);
4904                    }
4905                    match property {
4906                        MemberProp::Ident(name) => {
4907                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4908                        }
4909                        MemberProp::Computed(index) => {
4910                            self.expr(index)?;
4911                            // The key is not needed after the read, so this is the
4912                            // two-output form: object, value.
4913                            self.emit(Opcode::GetArrayEl2, &[]);
4914                        }
4915                        MemberProp::Private(name) => {
4916                            // The receiver is already under the callee, which is exactly the
4917                            // shape `call_method` and `apply` want — so nothing is dropped.
4918                            let binding = format!("#{}", name.name);
4919                            let (kind, _) = self.private_use(&binding, expr.span)?;
4920                            self.private_callee(&binding, kind)?;
4921                        }
4922                    }
4923                    if Self::has_spread(arguments) {
4924                        // Stack is `obj func`; the array goes on top, then `perm3`
4925                        // reorders to the `func this array` that `apply` wants.
4926                        self.argument_array(arguments)?;
4927                        self.emit(Opcode::Perm3, &[]);
4928                        self.emit(Opcode::Apply, &[Op::Int(0)]);
4929                        return Ok(());
4930                    }
4931                    for argument in arguments {
4932                        self.expr(argument)?;
4933                    }
4934                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4935                    return Ok(());
4936                }
4937                // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
4938                // with `get_field2` so the base stays under it, and on the short-circuit
4939                // path pushes an extra `undefined` as a placeholder receiver — the call
4940                // then throws, which is what calling a missing optional chain should do.
4941                if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
4942                    && let ExprKind::Member {
4943                        object,
4944                        property,
4945                        optional: member_optional,
4946                    } = &inner.unparen().kind
4947                {
4948                    let call = self.new_label();
4949                    // A guard target of its own: the outer `end` skips the whole
4950                    // expression, and a short-circuited receiver still has to reach the
4951                    // call so that calling it throws.
4952                    let short = self.new_label();
4953                    self.chain_link(object, end)?;
4954                    if *member_optional {
4955                        self.optional_guard(short);
4956                    }
4957                    match property {
4958                        MemberProp::Ident(name) => {
4959                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4960                        }
4961                        MemberProp::Computed(index) => {
4962                            self.expr(index)?;
4963                            self.emit(Opcode::GetArrayEl2, &[]);
4964                        }
4965                        MemberProp::Private(name) => {
4966                            let binding = format!("#{}", name.name);
4967                            let (kind, _) = self.private_use(&binding, expr.span)?;
4968                            self.private_callee(&binding, kind)?;
4969                        }
4970                    }
4971                    self.emit_jump(Opcode::Goto, call, &[]);
4972                    self.place_label(short);
4973                    self.emit(Opcode::Undefined, &[]);
4974                    self.place_label(call);
4975                    if Self::has_spread(arguments) {
4976                        self.argument_array(arguments)?;
4977                        self.emit(Opcode::Perm3, &[]);
4978                        self.emit(Opcode::Apply, &[Op::Int(0)]);
4979                        return Ok(());
4980                    }
4981                    for argument in arguments {
4982                        self.expr(argument)?;
4983                    }
4984                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4985                    return Ok(());
4986                }
4987                self.chain_link(callee, end)?;
4988                if *optional {
4989                    self.optional_guard(end);
4990                }
4991                if Self::has_spread(arguments) {
4992                    // `func array -> func undefined array`, which is the plain-call
4993                    // form of `apply`: the receiver is `undefined`.
4994                    self.argument_array(arguments)?;
4995                    self.emit(Opcode::Undefined, &[]);
4996                    self.emit(Opcode::Swap, &[]);
4997                    self.emit(Opcode::Apply, &[Op::Int(0)]);
4998                    return Ok(());
4999                }
5000                for argument in arguments {
5001                    self.expr(argument)?;
5002                }
5003                self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
5004                Ok(())
5005            }
5006            _ => self.expr(expr),
5007        }
5008    }
5009
5010    /// Compile `expr` as a tail call when it is one, reporting whether it was.
5011    ///
5012    /// `tail_call` reuses the current frame instead of pushing a new one, so a
5013    /// tail-recursive function runs in constant stack space. It also has to be the
5014    /// *last* thing the function does, which is why only a `return` reaches here.
5015    fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
5016        let ExprKind::Call {
5017            callee,
5018            arguments,
5019            optional: false,
5020        } = &expr.unparen().kind
5021        else {
5022            return Ok(false);
5023        };
5024        // A spread call has no tail form: `tail_call` takes its arguments one at a time off
5025        // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
5026        // as an ordinary call costs the one frame the optimisation was saving and keeps the
5027        // semantics — the alternative was reaching the spread expression below and failing
5028        // with "this expression form is not supported", which is how `return super.m(...a)`
5029        // stopped compiling. Checked before anything is emitted, because the decision cannot
5030        // be taken back once `super_base` or a `get_field2` is on the stack.
5031        if Self::has_spread(arguments) {
5032            return Ok(false);
5033        }
5034        let end = self.new_label();
5035        if let ExprKind::Member {
5036            object,
5037            property,
5038            optional: false,
5039        } = &callee.unparen().kind
5040        {
5041            // `super.m()` in tail position is still an ordinary method call with `this`
5042            // as the receiver; only the read of the method differs.
5043            if matches!(object.unparen().kind, ExprKind::SuperProp) {
5044                self.super_base();
5045                match property {
5046                    MemberProp::Ident(name) => self.emit(
5047                        Opcode::PushAtomValue,
5048                        &[Op::Atom(Atom::from_text(&name.name))],
5049                    ),
5050                    MemberProp::Computed(index) => self.expr(index)?,
5051                    MemberProp::Private(_) => return Ok(false),
5052                }
5053                self.emit(Opcode::GetArrayEl, &[]);
5054                for argument in arguments {
5055                    self.expr(argument)?;
5056                }
5057                self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5058                self.place_label(end);
5059                return Ok(true);
5060            }
5061            self.chain_link(object, end)?;
5062            match property {
5063                MemberProp::Ident(name) => {
5064                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5065                }
5066                MemberProp::Computed(index) => {
5067                    self.expr(index)?;
5068                    self.emit(Opcode::GetArrayEl2, &[]);
5069                }
5070                MemberProp::Private(_) => return Ok(false),
5071            }
5072            for argument in arguments {
5073                self.expr(argument)?;
5074            }
5075            self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5076            self.place_label(end);
5077            return Ok(true);
5078        }
5079        self.chain_link(callee, end)?;
5080        for argument in arguments {
5081            self.expr(argument)?;
5082        }
5083        self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
5084        self.place_label(end);
5085        Ok(true)
5086    }
5087
5088    /// The `?.` guard: keep the value if it is neither null nor undefined,
5089    /// otherwise replace it with `undefined` and leave the whole chain.
5090    fn optional_guard(&mut self, end: Label) {
5091        let cont = self.new_label();
5092        self.emit(Opcode::Dup, &[]);
5093        self.emit(Opcode::IsUndefinedOrNull, &[]);
5094        self.emit_jump(Opcode::IfFalse, cont, &[]);
5095        self.emit(Opcode::Drop, &[]);
5096        self.emit(Opcode::Undefined, &[]);
5097        self.emit_jump(Opcode::Goto, end, &[]);
5098        self.place_label(cont);
5099    }
5100
5101    fn push_number(&mut self, value: f64) {
5102        // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
5103        // goes into the constant pool.
5104        if value == value.trunc() && value.abs() <= i32::MAX as f64 {
5105            let int = value as i32;
5106            if (-1..=7).contains(&int) {
5107                self.emit(Opcode::PushI32, &[Op::Int(int)]);
5108                return;
5109            }
5110            if (-128..=127).contains(&int) {
5111                self.emit(Opcode::PushI8, &[Op::Int(int)]);
5112                return;
5113            }
5114            if (-32768..=32767).contains(&int) {
5115                self.emit(Opcode::PushI16, &[Op::Int(int)]);
5116                return;
5117            }
5118            self.emit(Opcode::PushI32, &[Op::Int(int)]);
5119            return;
5120        }
5121        let index = self.push_constant(Constant::Number(value));
5122        self.emit(Opcode::PushConst, &[Op::Const(index)]);
5123    }
5124
5125    /// Push a `BigInt` literal.
5126    ///
5127    /// A value that fits an `i32` uses the immediate form, which is what the reference
5128    /// emits too; anything larger goes into the constant pool, because the operand of
5129    /// `push_bigint` is only four bytes wide.
5130    fn push_bigint(&mut self, digits: &str, radix: u32) {
5131        if radix == 10
5132            && let Ok(value) = digits.parse::<i64>()
5133            && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
5134        {
5135            self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
5136            return;
5137        }
5138        let index = self.push_constant(Constant::BigInt {
5139            digits: digits.to_string(),
5140            radix,
5141        });
5142        self.emit(Opcode::PushConst, &[Op::Const(index)]);
5143    }
5144
5145    fn push_string(&mut self, text: &Wtf8) {
5146        if text.is_empty() {
5147            self.emit(Opcode::PushEmptyString, &[]);
5148            return;
5149        }
5150        self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
5151    }
5152
5153    /// Name an anonymous function from the binding it is assigned to.
5154    ///
5155    /// `var f = function(){}` produces a function whose `name` is `f`, which the
5156    /// runtime cannot know without being told: the function object is created
5157    /// before the store. `set_name` carries the name across.
5158    fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
5159        if value.is_anonymous_function_definition() {
5160            self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
5161        }
5162    }
5163
5164    /// The same, for a computed key: the name comes from the value on the stack
5165    /// rather than from an atom, so a different instruction carries it.
5166    fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
5167        if value.is_anonymous_function_definition() {
5168            self.emit(Opcode::SetNameComputed, &[]);
5169        }
5170    }
5171
5172    /// Compile a function body that exists only in the compiler's head — a class's
5173    /// implicit constructor or its field initialiser.
5174    ///
5175    /// Everything structural is the same as a written function: a fresh `FnState`, its
5176    /// own body block, and resolution while the frame is still on the stack. Only the
5177    /// statements differ.
5178    fn compile_synthetic_function(
5179        &mut self,
5180        name: &str,
5181        strict: bool,
5182        span: Span,
5183        body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
5184    ) -> Result<CompiledFunction, SyntaxError> {
5185        let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
5186        state.span = Some((span.start.offset as usize, span.end.offset as usize));
5187        state.strict = strict;
5188        state.created_in_block = self.cur().current_block;
5189        state.with_names = self.cur().with_names.clone();
5190        state.line = span.start.line;
5191        state.column = span.start.column;
5192        let depth = self.stack.len();
5193        self.stack.push(state);
5194        let body_key = span.start.offset as u64;
5195        self.push_block(body_key, NO_PARENT);
5196        self.state().body_block = body_key;
5197        let result = (|| {
5198            self.emit_scope_enter(body_key);
5199            body(self)?;
5200            if self.end_is_reachable() {
5201                self.emit(Opcode::ReturnUndef, &[]);
5202            }
5203            Ok(())
5204        })();
5205        if result.is_err() {
5206            self.stack.truncate(depth);
5207            return result.map(|()| unreachable!());
5208        }
5209        Ok(self.finish_current())
5210    }
5211
5212    /// The implicit return of a class constructor.
5213    ///
5214    /// A constructor that falls off the end initialises its instance fields first, and a
5215    /// derived one returns `this` — which is what makes `new D()` the object `super()`
5216    /// built rather than `undefined`.
5217    fn emit_class_constructor_tail(&mut self) {
5218        match self.cur().ctor_kind {
5219            CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
5220            // Nothing to install: a base constructor did it in its prologue and a derived
5221            // one at each `super()` site, which is where `this` first exists.
5222            CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
5223            CtorKind::Derived => {
5224                // `get_loc_check` rather than `get_loc`: reaching the end without ever
5225                // running `super()` is a ReferenceError, not `undefined`.
5226                self.emit_var(VarAction::Get, "this");
5227                self.emit(Opcode::Return, &[]);
5228            }
5229        }
5230    }
5231
5232    /// `yield expr` / `yield* expr`.
5233    ///
5234    /// The suspension itself is one instruction: the value is on the stack, `yield` hands
5235    /// it to the caller and parks the frame. On resume the stack holds the value the
5236    /// caller passed *and* a "magic" number saying which method resumed it — `next`
5237    /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
5238    /// `if_false <continue>` asks whether this was an ordinary `next`:
5239    ///
5240    /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
5241    /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
5242    ///   and uses the value sitting under the magic number.
5243    ///
5244    /// A `throw` never reaches here: the interpreter unwinds instead (see
5245    /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
5246    fn yield_expression(
5247        &mut self,
5248        argument: Option<&Expr>,
5249        delegate: bool,
5250    ) -> Result<(), SyntaxError> {
5251        if delegate {
5252            return self.yield_star(argument);
5253        }
5254        // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
5255        // does the same for the `return(v)` that can resume it — which is why an async
5256        // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
5257        // generator's is just `yield`.
5258        let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
5259        match argument {
5260            Some(value) => self.expr(value)?,
5261            None => self.emit(Opcode::Undefined, &[]),
5262        }
5263        if is_async {
5264            self.emit(Opcode::Await, &[]);
5265            self.state().has_await = true;
5266        }
5267        self.emit(Opcode::Yield, &[]);
5268        let resume = self.new_label();
5269        self.emit_jump(Opcode::IfFalse, resume, &[]);
5270        // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
5271        // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
5272        // finished the generator and never ran the `finally`.
5273        if is_async {
5274            self.emit(Opcode::Await, &[]);
5275        }
5276        self.emit_unwind_for_return(true);
5277        self.emit(Opcode::ReturnAsync, &[]);
5278        self.place_label(resume);
5279        // Nothing is emitted here: the value the caller passed to `next` *is* the value
5280        // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
5281        // it through the ordinary expression-statement discard.
5282        Ok(())
5283    }
5284
5285    /// `yield* iterable`.
5286    ///
5287    /// The shape is the reference's, and it is a fall-through chain rather than a
5288    /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
5289    /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
5290    /// the inner iterator and finishes, `throw` forwards the exception into it and
5291    /// continues only if it has a `throw` method.
5292    ///
5293    /// The stack is `iter next catch value` throughout, `catch` being the offset
5294    /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
5295    fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
5296        match argument {
5297            Some(value) => self.expr(value)?,
5298            // The parser rejects a bare `yield*`, so this is unreachable in practice.
5299            None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
5300        }
5301        // `for await of` is the same protocol as `for of` with two differences that matter
5302        // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
5303        // every `next()` result is a promise the delegate has to await.
5304        let is_async = self.cur().kind.is_async();
5305        self.emit(
5306            if is_async {
5307                Opcode::ForAwaitOfStart
5308            } else {
5309                Opcode::ForOfStart
5310            },
5311            &[],
5312        );
5313        self.emit(Opcode::Drop, &[]);
5314        self.emit(Opcode::Undefined, &[]);
5315        self.emit(Opcode::Undefined, &[]);
5316        let next = self.new_label();
5317        let resume = self.new_label();
5318        let finished = self.new_label();
5319        let rethrow = self.new_label();
5320        let throw_no_method = self.new_label();
5321        let done = self.new_label();
5322        self.place_label(next);
5323        self.emit(Opcode::IteratorNext, &[]);
5324        if is_async {
5325            self.emit(Opcode::Await, &[]);
5326            self.state().has_await = true;
5327        }
5328        self.emit(Opcode::IteratorCheckObject, &[]);
5329        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5330        self.emit_jump(Opcode::IfTrue, done, &[]);
5331        // The suspension. `resume` is both the label the return path jumps back to in order
5332        // to yield one more value and where the caller's answer arrives, as the value
5333        // followed by the magic number.
5334        //
5335        // The two forms differ in what they hand the suspension: `yield_star` takes the
5336        // result object itself, `async_yield_star` takes `.value`, because an async
5337        // generator awaits and re-wraps whatever it yields.
5338        self.place_label(resume);
5339        if is_async {
5340            self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5341            self.emit(Opcode::AsyncYieldStar, &[]);
5342        } else {
5343            self.emit(Opcode::YieldStar, &[]);
5344        }
5345        self.emit(Opcode::Dup, &[]);
5346        self.emit_jump(Opcode::IfTrue, rethrow, &[]);
5347        self.emit(Opcode::Drop, &[]);
5348        self.emit_jump(Opcode::Goto, next, &[]);
5349
5350        // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
5351        self.place_label(rethrow);
5352        self.emit(Opcode::PushI32, &[Op::Int(2)]);
5353        self.emit(Opcode::StrictEq, &[]);
5354        self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
5355        // A `return` closes the inner iterator; if it had none, the delegate simply
5356        // finishes with the requested value. In an async generator both the call and its
5357        // result are awaited, because the inner `return` may itself be async.
5358        if is_async {
5359            self.emit(Opcode::Await, &[]);
5360        }
5361        self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
5362        self.emit_jump(Opcode::IfTrue, finished, &[]);
5363        if is_async {
5364            self.emit(Opcode::Await, &[]);
5365        }
5366        self.emit(Opcode::IteratorCheckObject, &[]);
5367        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5368        self.emit_jump(Opcode::IfFalse, resume, &[]);
5369        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5370        self.place_label(finished);
5371        self.emit(Opcode::Nip, &[]);
5372        self.emit(Opcode::Nip, &[]);
5373        self.emit(Opcode::Nip, &[]);
5374        // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
5375        // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
5376        // awaits the value in an async generator and then runs the same `finally`/iterator
5377        // unwinding a written `return` would. Skipping the unwinding made
5378        // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
5379        if is_async {
5380            self.emit(Opcode::Await, &[]);
5381        }
5382        self.emit_unwind_for_return(true);
5383        self.emit(Opcode::ReturnAsync, &[]);
5384
5385        // `throw(e)`: forward it into the inner iterator.
5386        self.place_label(throw_no_method);
5387        self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
5388        let no_throw = self.new_label();
5389        self.emit_jump(Opcode::IfTrue, no_throw, &[]);
5390        if is_async {
5391            self.emit(Opcode::Await, &[]);
5392        }
5393        self.emit(Opcode::IteratorCheckObject, &[]);
5394        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5395        self.emit_jump(Opcode::IfFalse, resume, &[]);
5396        self.emit_jump(Opcode::Goto, done, &[]);
5397        // No `throw` method: close the iterator, then report the spec's TypeError. The
5398        // `if_true` before the `await` is the reference's shape — the flag it consumes is
5399        // what `iterator_call` leaves behind, and a close that *did* find no `return`
5400        // method has nothing to await.
5401        self.place_label(no_throw);
5402        self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
5403        let no_close = self.new_label();
5404        self.emit_jump(Opcode::IfTrue, no_close, &[]);
5405        if is_async {
5406            self.emit(Opcode::Await, &[]);
5407        }
5408        self.place_label(no_close);
5409        self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
5410
5411        // The inner iterator finished: the delegate's value is the `yield*` expression's
5412        // value, so it is left on the stack for whatever consumes it.
5413        self.place_label(done);
5414        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5415        self.emit(Opcode::Nip, &[]);
5416        self.emit(Opcode::Nip, &[]);
5417        self.emit(Opcode::Nip, &[]);
5418        Ok(())
5419    }
5420
5421    /// `await expr`: exactly one instruction.
5422    ///
5423    /// No resume-magic branch follows it. The reference's `await` leaves a single value
5424    /// on the stack and completion is signalled by the `return_async` at the end of the
5425    /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
5426    /// reference never emits, and a `for await` loop — which reaches `await` through the
5427    /// same opcode — would then spill a value the loop's unpacking does not expect.
5428    fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
5429        self.expr(argument)?;
5430        self.emit(Opcode::Await, &[]);
5431        self.state().has_await = true;
5432        Ok(())
5433    }
5434
5435    /// The `super` base: the receiver followed by the home object's prototype.
5436    ///
5437    /// Everything `super` does needs both. A *read* starts at the prototype but reports
5438    /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
5439    /// prototype but calls it with the receiver.
5440    fn super_base(&mut self) {
5441        self.this_expression();
5442        self.home_object();
5443        self.emit(Opcode::GetSuper, &[]);
5444    }
5445
5446    /// `[[HomeObject]]` as `super` sees it.
5447    ///
5448    /// A method, a constructor and a field initialiser each carry one — `set_home_object`
5449    /// put it there — so for them the special object *is* the answer. An arrow and a
5450    /// static block have none: they read the enclosing function's, which has to be
5451    /// materialised into a local, exactly as `this` is for an arrow.
5452    ///
5453    /// The name matches what the reference stores, so the disassembly agrees; it is not a
5454    /// name any program can write.
5455    fn home_object(&mut self) {
5456        if !self.cur().is_arrow {
5457            self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
5458            return;
5459        }
5460        if let Some(target) = self.enclosing_function() {
5461            self.state_at(target).needs_home_object_local = true;
5462            self.declare_at(target, HOME_OBJECT);
5463        }
5464        self.emit_var(VarAction::Get, HOME_OBJECT);
5465    }
5466
5467    /// `super(args)`: construct the parent class and adopt the result as `this`.
5468    ///
5469    /// The parent is the prototype of the constructor that is running, which is exactly
5470    /// what `extends` set up. `new.target` is passed through unchanged so that
5471    /// `new.target` inside the parent is the class actually being constructed.
5472    fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5473        self.active_func_expression();
5474        self.emit(Opcode::GetSuper, &[]);
5475        self.new_target_expression();
5476        if Self::has_spread(arguments) {
5477            self.argument_array(arguments)?;
5478            self.emit(Opcode::Apply, &[Op::Int(1)]);
5479        } else {
5480            for argument in arguments {
5481                self.expr(argument)?;
5482            }
5483            self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
5484        }
5485        // The value stays on the stack: `super()` is an expression, and a derived
5486        // constructor's `this` may only be initialised once.
5487        self.emit(Opcode::Dup, &[]);
5488        self.emit_var(VarAction::PutInitChecked, "this");
5489        // Instance fields are installed here, not at the top of the body: a derived
5490        // constructor has no `this` to install them on until `super()` returns. The
5491        // reference emits the same call at every `super()` site.
5492        self.call_field_initialiser();
5493        Ok(())
5494    }
5495
5496    /// `this` as a local, which every class constructor and field initialiser needs.
5497    ///
5498    /// The reference materialises the receiver into a local rather than reading
5499    /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
5500    /// and a field initialiser has to see the final value.
5501    fn begin_this_local(&mut self) {
5502        self.declare_hidden_local("this", VarKind::Normal);
5503        self.emit(Opcode::PushThis, &[]);
5504        self.emit_var(VarAction::Put, "this");
5505        // The store is already at the top of the body, so `provide_this_local` has
5506        // nothing left to prepend. Without this the initialiser ended up with
5507        // `push_this; put_loc0 this` twice whenever the class also held a field
5508        // initialiser whose body read `this` through an arrow.
5509        self.state().has_this_prologue = true;
5510    }
5511
5512    /// Compile a constructor the class wrote.
5513    ///
5514    /// The flags have to be in place before the body is compiled, but
5515    /// `compile_function_with_name` creates its own state — so the caller's state is
5516    /// marked instead and the new one inherits it. That is the same trick the parameter
5517    /// prologue uses, and it keeps one code path for both.
5518    fn compile_class_constructor(
5519        &mut self,
5520        func: &ast::Function,
5521        has_heritage: bool,
5522    ) -> Result<CompiledFunction, SyntaxError> {
5523        let saved = self.cur().ctor_kind;
5524        self.state().class_ctor_pending = Some(if has_heritage {
5525            CtorKind::Derived
5526        } else {
5527            CtorKind::Base
5528        });
5529        let result = self.compile_function_with_name(func, false);
5530        self.state().ctor_kind = saved;
5531        self.state().class_ctor_pending = None;
5532        result
5533    }
5534
5535    /// The constructor a class gets when it does not declare one.
5536    ///
5537    /// A base class's is empty; a derived class's forwards every argument to the parent
5538    /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
5539    /// instance field initialiser afterwards when the class has fields, which is why the
5540    /// initialiser is captured rather than inlined.
5541    fn compile_implicit_constructor(
5542        &mut self,
5543        class: &Class,
5544        has_heritage: bool,
5545    ) -> Result<CompiledFunction, SyntaxError> {
5546        self.compile_synthetic_function(
5547            "",
5548            true,
5549            Span::new(class.body_end, class.body_end),
5550            |compiler| {
5551                if has_heritage {
5552                    // A derived constructor's `this` does not exist until `super()` returns,
5553                    // so it starts in the dead zone and `init_ctor` fills it.
5554                    compiler.declare("this", VarDef::lexical("this"));
5555                    compiler.emit(
5556                        Opcode::SetLocUninitialized,
5557                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5558                    );
5559                    compiler.emit(Opcode::InitCtor, &[]);
5560                    compiler.emit(
5561                        Opcode::PutLocCheckInit,
5562                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5563                    );
5564                } else {
5565                    compiler.begin_this_local();
5566                    compiler.emit(Opcode::CheckCtor, &[]);
5567                }
5568                compiler.call_field_initialiser();
5569                // A derived constructor returns `this`, the object `super()` built. Without
5570                // this the implicit constructor fell through to `return_undef`, and `new B()`
5571                // handed back the empty object `construct` had made instead of the one the
5572                // parent constructor initialised.
5573                if has_heritage {
5574                    compiler.emit_var(VarAction::Get, "this");
5575                    compiler.emit(Opcode::Return, &[]);
5576                }
5577                Ok(())
5578            },
5579        )
5580    }
5581
5582    /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
5583    ///
5584    /// A class with no instance fields leaves the binding `undefined`, and calling it
5585    /// would throw; the reference emits the same guard rather than branching at compile
5586    /// time because a class can be extended by a subclass whose fields still have to run.
5587    fn call_field_initialiser(&mut self) {
5588        let skip = self.new_label();
5589        self.emit_var(VarAction::Get, "<class_fields_init>");
5590        self.emit(Opcode::Dup, &[]);
5591        self.emit_jump(Opcode::IfFalse, skip, &[]);
5592        self.emit_var(VarAction::Get, "this");
5593        self.emit(Opcode::Swap, &[]);
5594        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
5595        self.place_label(skip);
5596        self.emit(Opcode::Drop, &[]);
5597    }
5598
5599    /// The function that defines one class's fields on `this`, and runs its static blocks.
5600    ///
5601    /// `define_field` rather than `put_field`: a field is an own property created
5602    /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
5603    /// `x = 1` field must not call the setter.
5604    ///
5605    /// One function serves the whole class: it is called once per instance (or once, for
5606    /// the static half) and walks the members in source order. Static blocks are compiled
5607    /// into the same function because they *are* part of the same sequence — `static a =
5608    /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
5609    /// different values, so the two kinds cannot be split apart.
5610    fn compile_field_initialiser(
5611        &mut self,
5612        items: &[StaticInitItem<'_>],
5613        span: Span,
5614        instance: bool,
5615        add_brand: bool,
5616    ) -> Result<CompiledFunction, SyntaxError> {
5617        self.compile_synthetic_function("", true, span, |compiler| {
5618            if instance {
5619                // An instance initialiser always carries a `<home_object>` local, because the
5620                // brand block below reads it — even when that block turns out to be dead. The
5621                // reference has the same artefact, and the store is visible in its dump.
5622                let current = compiler.stack.len() - 1;
5623                compiler.stack[current].needs_home_object_local = true;
5624            }
5625            compiler.begin_this_local();
5626            if instance {
5627                // `this` gets the brand the prototype created, before any field is defined —
5628                // which is what makes `#m()` usable from inside a field initialiser.
5629                //
5630                // The reference always emits `push_false; if_false L; this; home; add_brand;
5631                // L:` and patches the `push_false` to `push_true` from the class parse when
5632                // the class has private methods; either way the branch folds, but the *mark*
5633                // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
5634                // `this` local from being fused into a `set_loc`.
5635                let skip = compiler.new_label();
5636                if add_brand {
5637                    compiler.emit(Opcode::PushTrue, &[]);
5638                } else {
5639                    compiler.emit(Opcode::PushFalse, &[]);
5640                }
5641                compiler.emit_jump(Opcode::IfFalse, skip, &[]);
5642                compiler.emit_var(VarAction::Get, "this");
5643                compiler.emit_var(VarAction::Get, HOME_OBJECT);
5644                compiler.emit(Opcode::AddBrand, &[]);
5645                compiler.place_label(skip);
5646            }
5647            for item in items {
5648                match item {
5649                    StaticInitItem::Field(key, value) => {
5650                        // A private field is *defined*, not assigned: `define_private_field`
5651                        // reads `obj symbol value`, and its point is that it fails on a
5652                        // receiver that is not this class's — which `put_field` would not.
5653                        //
5654                        // The three shapes are the reference's: `define_field <atom>` for a
5655                        // static name, `define_array_el` for a key that is only known at run
5656                        // time (`obj key value`), `define_private_field` for `#x`, and a
5657                        // computed key is read from its binding rather than recomputed.
5658                        compiler.emit_var(VarAction::Get, "this");
5659                        match key {
5660                            FieldKey::Private(binding) | FieldKey::Computed(binding) => {
5661                                compiler.emit_var(VarAction::Get, binding);
5662                            }
5663                            FieldKey::Literal(_) => {}
5664                        }
5665                        match value {
5666                            Some(value) => compiler.expr(value)?,
5667                            None => compiler.emit(Opcode::Undefined, &[]),
5668                        }
5669                        match key {
5670                            FieldKey::Literal(literal) => {
5671                                let text = compiler.property_key_text(literal, span)?;
5672                                compiler
5673                                    .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
5674                            }
5675                            FieldKey::Computed(_) => {
5676                                compiler.emit(Opcode::DefineArrayEl, &[]);
5677                                // `define_array_el` leaves `obj key`; the key is consumed by
5678                                // the copy the pattern machinery wants, so both go.
5679                                compiler.emit(Opcode::Drop, &[]);
5680                            }
5681                            FieldKey::Private(_) => {
5682                                compiler.emit(Opcode::DefinePrivateField, &[]);
5683                            }
5684                        }
5685                        compiler.emit(Opcode::Drop, &[]);
5686                    }
5687                    StaticInitItem::Block { body, body_start } => {
5688                        let block = compiler.compile_static_block(body, *body_start)?;
5689                        let index = compiler.push_constant(Constant::Function(Box::new(block)));
5690                        // `this fclosure`, so `call_method` finds the receiver below the
5691                        // callee: the block runs with `this` bound to the class.
5692                        compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
5693                        compiler.emit_var(VarAction::Get, "this");
5694                        compiler.emit(Opcode::Swap, &[]);
5695                        compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
5696                        // Nothing the block evaluates is wanted; its effects are the point.
5697                        compiler.emit(Opcode::Drop, &[]);
5698                    }
5699                }
5700            }
5701            Ok(())
5702        })
5703    }
5704
5705    /// Compile a `static { … }` body into the function the class calls for it.
5706    ///
5707    /// Shaped like an arrow, because that is the one function form with no `this`,
5708    /// `new.target` or `arguments` of its own: all three reach the enclosing static
5709    /// initialiser, and through it the class. `arguments` never gets that far — the parser
5710    /// rejects the reference — but `this` and `super` both depend on it.
5711    ///
5712    /// The body is hoisted like a function body's, because the reference parses it as one:
5713    /// `var` inside a block is a local of the block's function, not of whatever encloses
5714    /// the class.
5715    fn compile_static_block(
5716        &mut self,
5717        body: &[Stmt],
5718        body_start: Position,
5719    ) -> Result<CompiledFunction, SyntaxError> {
5720        let mut state = FnState::new(String::new(), FunctionKind::Normal);
5721        // Class bodies are strict, so a static block is too.
5722        state.strict = true;
5723        // The one property that makes this an arrow: nothing of its own to bind `this` to,
5724        // so `this` and `super` come from the initialiser that calls it.
5725        state.is_arrow = true;
5726        state.created_in_block = self.cur().current_block;
5727        state.with_names = self.cur().with_names.clone();
5728        state.line = body_start.line;
5729        state.column = body_start.column;
5730        let depth = self.stack.len();
5731        self.stack.push(state);
5732        let body_key = body_start.offset as u64;
5733        self.push_block(body_key, NO_PARENT);
5734        self.state().body_block = body_key;
5735        let result = (|| {
5736            self.hoist(body, body_key)?;
5737            self.emit_scope_enter(body_key);
5738            for statement in body {
5739                self.stmt(statement)?;
5740            }
5741            if self.end_is_reachable() {
5742                self.emit(Opcode::ReturnUndef, &[]);
5743            }
5744            Ok(())
5745        })();
5746        if result.is_err() {
5747            self.stack.truncate(depth);
5748            return result.map(|()| unreachable!());
5749        }
5750        Ok(self.finish_current())
5751    }
5752
5753    /// Compile a class, leaving the constructor on the stack when `keep`.
5754    ///
5755    /// The shape follows the reference: the class body is its own scope holding the
5756    /// class's *inner* name as a `const` — which is what lets a method refer to the
5757    /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
5758    /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
5759    /// on the top of the stack: the prototype for instance members, the constructor
5760    /// itself for `static` ones, which is why a static member costs an extra `swap`.
5761    fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
5762        let parent_block = self.cur().current_block;
5763        let key = class.span.start.offset as u64;
5764        self.push_block(key, parent_block);
5765        let name = class.name.as_ref().map(|ident| ident.name.clone());
5766        // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
5767        // resolves `E` without a global lookup. An *unnamed* class expression has no such
5768        // binding, and `define_class` is handed the empty name.
5769        if let Some(name) = &name {
5770            self.declare(name, VarDef::constant(name.clone()));
5771        }
5772        self.emit_scope_enter(key);
5773
5774        // The heritage clause is evaluated outside the class's own scope: it cannot see
5775        // the class binding it is about to initialise.
5776        let saved_block = self.cur().current_block;
5777        self.state().current_block = parent_block;
5778        match &class.super_class {
5779            Some(parent) => self.expr(parent)?,
5780            None => self.emit(Opcode::Undefined, &[]),
5781        }
5782        self.state().current_block = saved_block;
5783        let has_heritage = class.super_class.is_some();
5784
5785        // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
5786        // lands after the heritage's code — which is where the reference puts it, because it
5787        // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
5788        // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
5789        // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
5790        // came out in the opposite order from the reference's.
5791        //
5792        // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
5793        // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
5794        // a const accepts — so the old comment's worry ("a const would refuse the second
5795        // store") did not apply: there is no second store.
5796        // Every `#name` the class declares gets a `const` binding in the class scope, and so
5797        // does every computed field key. That is how the reference does it
5798        // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
5799        // what makes a private name resolve like any other class-scope variable — including
5800        // through a nested function's closure — while remaining invisible outside.
5801        //
5802        // All of them are declared *before* `<class_fields_init>`, in member order, because
5803        // that is when the reference's parser creates them.
5804        let plan = ClassPlan::build(class);
5805        // The body's private names are visible from here to the end of the class, and shadow
5806        // any outer class's of the same spelling. Pushed *before* the constructor is compiled
5807        // — it is compiled first because `define_class` consumes it, but its body can name
5808        // `#x` like any other member's.
5809        self.private_scopes.push(plan.uses.clone());
5810        let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
5811        for binding in &plan.bindings {
5812            class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
5813        }
5814        let fci = self.declare(
5815            "<class_fields_init>",
5816            VarDef::constant("<class_fields_init>"),
5817        );
5818        // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
5819        // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
5820        // members' bindings follow in reverse.
5821        self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
5822        for slot in class_slots.iter().rev() {
5823            self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
5824        }
5825
5826        // The constructor is compiled before `define_class` because that instruction
5827        // consumes it; a class without one gets the implicit version.
5828        let constructor = class.elements.iter().find_map(|element| match element {
5829            ClassElement::Method {
5830                kind: MethodKind::Constructor,
5831                func,
5832                ..
5833            } => Some(&**func),
5834            _ => None,
5835        });
5836        // A constructor is compiled differently from a method: it owns `this`. The flags
5837        // go on the *enclosing* state because a constructor is a nested function and
5838        // `compile_function_with_name` starts a fresh one.
5839        let ctor = match constructor {
5840            Some(func) => self.compile_class_constructor(func, has_heritage)?,
5841            None => self.compile_implicit_constructor(class, has_heritage)?,
5842        };
5843        // A closure, not the bare constant: the constructor captures
5844        // `<class_fields_init>`, which is only filled after `define_class` has run, so it
5845        // has to hold the cell rather than a copy of its value.
5846        //
5847        // The pool slot is left unassigned for now, because the reference gives the
5848        // constructor the *last* index of the members' range: `js_parse_class` emits a
5849        // `push_const` whose operand is patched at the end of the class parse, after every
5850        // method has taken a slot. Emitting the members first and the constant second is how
5851        // the numbering comes out the same; the instruction itself stays where it is.
5852        let ctor_insn = self.cur().insns.len();
5853        self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
5854        let flags = if has_heritage { 1 } else { 0 };
5855        self.emit(
5856            Opcode::DefineClass,
5857            &[
5858                Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
5859                Op::Int(flags),
5860            ],
5861        );
5862
5863        // Instance fields and static fields are two different functions: the first runs
5864        // per instance from the constructor, the second runs once, here.
5865        let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
5866        let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
5867        for (index, element) in class.elements.iter().enumerate() {
5868            match element {
5869                ClassElement::Method {
5870                    key: member_key,
5871                    is_static,
5872                    kind,
5873                    func,
5874                    span,
5875                } => {
5876                    if *kind == MethodKind::Constructor {
5877                        continue;
5878                    }
5879                    // `static(x)` is a *method* named `static`, not a static method; the
5880                    // parser already decided which by putting it in `kind`.
5881                    if *is_static {
5882                        self.emit(Opcode::Swap, &[]);
5883                    }
5884                    // A computed key is evaluated *here*, before the method's closure
5885                    // exists, and stays under it: `define_method_computed` pops
5886                    // `function, key, object`, so the stack has to read
5887                    // `[class, prototype, key, function]`. Evaluating the key after the
5888                    // `fclosure` and swapping the two put the prototype *below* the
5889                    // closure, which defined the method on the function and lost the
5890                    // prototype: `class C { [k]() {} }` left `C` undefined. The order is
5891                    // also the spec's — a class body evaluates every element's name before
5892                    // that element's function.
5893                    if let PropName::Computed(key) = member_key {
5894                        self.expr(key)?;
5895                    }
5896                    let function = self.compile_function_with_name(func, true)?;
5897                    let index = self.push_constant(Constant::Function(Box::new(function)));
5898                    self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5899                    match member_key {
5900                        // A private method is not a property of the prototype: it is a
5901                        // closure in the class scope, which is why nothing outside can reach
5902                        // it and why a use site has to brand-check. `set_name` gives the
5903                        // function its `name` (`#m`), which an accessor does not get — the
5904                        // reference leaves that commented out.
5905                        PropName::Private(ident) => {
5906                            let name = format!("#{}", ident.name);
5907                            // `set_home_object` first: the brand check reads the function's
5908                            // home object, and for a method that is the prototype.
5909                            self.emit(Opcode::SetHomeObject, &[]);
5910                            let binding = if *kind == MethodKind::Set {
5911                                format!("{name}<set>")
5912                            } else {
5913                                name.clone()
5914                            };
5915                            if *kind == MethodKind::Method {
5916                                self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
5917                            }
5918                            self.emit_var(VarAction::PutInit, &binding);
5919                        }
5920                        PropName::Computed(_) => {
5921                            self.emit(
5922                                Opcode::DefineMethodComputed,
5923                                &[Op::Int(class_method_flags(*kind))],
5924                            );
5925                        }
5926                        PropName::Literal(literal) => {
5927                            let text = self.property_key_text(literal, *span)?;
5928                            self.emit(
5929                                Opcode::DefineMethod,
5930                                &[
5931                                    Op::Atom(Atom::from_wtf8(&text)),
5932                                    Op::Int(class_method_flags(*kind)),
5933                                ],
5934                            );
5935                        }
5936                    }
5937                    if *is_static {
5938                        self.emit(Opcode::Swap, &[]);
5939                    }
5940                }
5941                ClassElement::Field {
5942                    key: field_key,
5943                    is_static,
5944                    value,
5945                    ..
5946                } => {
5947                    // A private field's *symbol* is created here, at the member, and stored
5948                    // in its binding: the field's property is keyed by it, so it has to exist
5949                    // before any initialiser runs, and a fresh one per class body is what
5950                    // makes two classes that both write `#x` independent.
5951                    //
5952                    // A computed key is evaluated once, here, and `to_propkey`'d once — a key
5953                    // whose `toString` has a side effect must not run again per instance.
5954                    let key = match field_key {
5955                        PropName::Private(ident) => {
5956                            let binding = format!("#{}", ident.name);
5957                            if *is_static {
5958                                self.emit(Opcode::Swap, &[]);
5959                            }
5960                            self.emit(
5961                                Opcode::PrivateSymbol,
5962                                &[Op::Atom(Atom::from_text(&binding))],
5963                            );
5964                            self.emit_var(VarAction::PutInit, &binding);
5965                            if *is_static {
5966                                self.emit(Opcode::Swap, &[]);
5967                            }
5968                            FieldKey::Private(binding)
5969                        }
5970                        PropName::Computed(expression) => {
5971                            let binding = plan
5972                                .computed
5973                                .get(&index)
5974                                .cloned()
5975                                .expect("every computed key got a binding");
5976                            if *is_static {
5977                                self.emit(Opcode::Swap, &[]);
5978                            }
5979                            self.expr(expression)?;
5980                            self.emit(Opcode::ToPropkey, &[]);
5981                            self.emit_var(VarAction::PutInit, &binding);
5982                            if *is_static {
5983                                self.emit(Opcode::Swap, &[]);
5984                            }
5985                            FieldKey::Computed(binding)
5986                        }
5987                        PropName::Literal(literal) => FieldKey::Literal(literal),
5988                    };
5989                    if *is_static {
5990                        static_items.push(StaticInitItem::Field(key, value.as_deref()));
5991                    } else {
5992                        instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
5993                    }
5994                }
5995                ClassElement::StaticBlock {
5996                    body, body_start, ..
5997                } => static_items.push(StaticInitItem::Block {
5998                    body,
5999                    body_start: *body_start,
6000                }),
6001            }
6002        }
6003
6004        // Now that every member has its slot, the constructor can have the next one and the
6005        // `fclosure` above can name it.
6006        let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
6007        match self.state().insns.get_mut(ctor_insn) {
6008            Some(Insn::Fixed { operands, .. }) => {
6009                operands[0] = Op::Const(ctor_index);
6010            }
6011            // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
6012            // loudly beats emitting a `fclosure` of slot 4294967295.
6013            _ => {
6014                return Err(SyntaxError::new(
6015                    "the class constructor's fclosure went missing",
6016                    class.span,
6017                ));
6018            }
6019        }
6020
6021        // The instance brand: a symbol created once on the prototype, which every instance
6022        // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
6023        // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
6024        // copy is created. The prototype is on top of the stack at this point.
6025        if plan.instance_brand {
6026            self.emit(Opcode::Dup, &[]);
6027            self.emit(Opcode::Null, &[]);
6028            self.emit(Opcode::Swap, &[]);
6029            self.emit(Opcode::AddBrand, &[]);
6030        }
6031
6032        // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
6033        // class has no instance fields. The constructor calls it only when it is defined.
6034        //
6035        // A class with private *methods* but no fields still needs one, because adding the
6036        // brand to each new instance is the initialiser's job.
6037        if instance_fields.is_empty() && !plan.instance_brand {
6038            self.emit(Opcode::Undefined, &[]);
6039        } else {
6040            let initialiser = self.compile_field_initialiser(
6041                &instance_fields,
6042                class.span,
6043                true,
6044                plan.instance_brand,
6045            )?;
6046            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6047            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6048            // `set_home_object` reads `obj func`, so the prototype stays where it is.
6049            self.emit(Opcode::SetHomeObject, &[]);
6050        }
6051        self.emit_var(VarAction::PutInit, "<class_fields_init>");
6052        // The prototype has done its job: every instance member is defined on it. What
6053        // is left under it is the constructor.
6054        self.emit(Opcode::Drop, &[]);
6055
6056        // The static brand, for `static #m() {}`: same opcode, but the home object is the
6057        // constructor itself, so the symbol lands on the class and the class carries it.
6058        if plan.static_brand {
6059            self.emit(Opcode::Dup, &[]);
6060            self.emit(Opcode::Dup, &[]);
6061            self.emit(Opcode::AddBrand, &[]);
6062        }
6063
6064        // The class binding is initialised *before* static fields run, so a static field
6065        // can refer to the class by name (`static y = S.x`).
6066        // `set_loc` leaves the constructor on the stack, which is what the static field
6067        // call and the outer store both consume.
6068        //
6069        // Only when there *is* such a binding: an anonymous class expression declares no
6070        // class-scope name, and asking for one by the empty string resolved to nothing —
6071        // which made `var x = class {}` assign `undefined` and put a bogus global store in
6072        // the instruction stream.
6073        if let Some(name) = &name {
6074            self.emit_var(VarAction::SetInit, name);
6075        }
6076        if !static_items.is_empty() {
6077            // The static half has no brand prologue of its own: the constructor got its
6078            // brand above, before this runs.
6079            let initialiser =
6080                self.compile_field_initialiser(&static_items, class.span, false, false)?;
6081            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6082            self.emit(Opcode::Dup, &[]);
6083            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6084            self.emit(Opcode::SetHomeObject, &[]);
6085            self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6086            self.emit(Opcode::Drop, &[]);
6087        }
6088        // The body is over, and with it this class's private names.
6089        let _ = self.private_scopes.pop();
6090        self.emit_scope_leave(key);
6091        self.state().current_block = parent_block;
6092        if keep {
6093            // A class *expression* is its own value; the class-scope binding was only
6094            // ever an alias for it.
6095            return Ok(());
6096        }
6097        // A declaration stores into the binding the enclosing statement declared.
6098        self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
6099        Ok(())
6100    }
6101
6102    fn push_this(&mut self) {
6103        self.emit(Opcode::PushThis, &[]);
6104    }
6105
6106    /// `this`, which an arrow does not have of its own.
6107    ///
6108    /// The reference gives the enclosing function a local named `this`, initialised from
6109    /// `push_this` at the top of its body, and the arrow then reads it as a captured
6110    /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
6111    /// the arrow is called with none.
6112    fn this_expression(&mut self) {
6113        // In a class constructor `this` is a local: a derived constructor only gets one
6114        // when `super()` returns, and reading the raw receiver would give the *outer*
6115        // one instead.
6116        if self.cur().ctor_kind != CtorKind::None {
6117            self.emit_var(VarAction::Get, "this");
6118            return;
6119        }
6120        if !self.cur().is_arrow {
6121            self.push_this();
6122            return;
6123        }
6124        // An arrow at the **top level** of a script or module has no enclosing function,
6125        // but it still inherits `this` — the script's or module's own. Falling through to
6126        // `emit_var(Get, "this")` without a target made that a *global* lookup, so
6127        // `var f = () => typeof this` at top level reported
6128        // `ReferenceError: 'this' is not defined` instead of `"object"`
6129        // (`Set/prototype/forEach/this-arg-explicit-cannot-override-lexical-this-arrow`
6130        // is the test262 case that reaches it, through a native `forEach`).
6131        //
6132        // The script state is the bottom of the stack, so it is the fallback target. Its
6133        // own `provide_this_local` then prepends the `push_this` the arrow reads.
6134        let target = self.enclosing_function().unwrap_or(0);
6135        self.state_at(target).needs_this_local = true;
6136        self.declare_at(target, "this");
6137        self.emit_var(VarAction::Get, "this");
6138    }
6139
6140    /// `new.target`, which an arrow likewise does not own.
6141    fn new_target_expression(&mut self) {
6142        if !self.cur().is_arrow {
6143            self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
6144            return;
6145        }
6146        if let Some(target) = self.enclosing_function() {
6147            self.state_at(target).needs_new_target_local = true;
6148            self.declare_at(target, NEW_TARGET);
6149        }
6150        self.emit_var(VarAction::Get, NEW_TARGET);
6151    }
6152
6153    /// `this.active_func`: the function `super()` resolves against.
6154    ///
6155    /// In a constructor or a method that is the function being run, so the special object
6156    /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
6157    /// a closure variable — see [`FnState::needs_active_func_local`].
6158    fn active_func_expression(&mut self) {
6159        if !self.cur().is_arrow {
6160            self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
6161            return;
6162        }
6163        if let Some(target) = self.enclosing_function() {
6164            self.state_at(target).needs_active_func_local = true;
6165            self.declare_at(target, ACTIVE_FUNC);
6166        }
6167        self.emit_var(VarAction::Get, ACTIVE_FUNC);
6168    }
6169
6170    /// Give the function a local `<active_func>`, for an arrow inside it to capture.
6171    fn provide_active_func_local(&mut self) {
6172        let current = self.stack.len() - 1;
6173        if !self.stack[current].needs_active_func_local {
6174            return;
6175        }
6176        if !self.stack[current]
6177            .vars
6178            .iter()
6179            .any(|var| var.name == ACTIVE_FUNC)
6180        {
6181            self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
6182        }
6183        self.prepend_initialiser(
6184            ACTIVE_FUNC,
6185            Insn::Fixed {
6186                op: Opcode::SpecialObject,
6187                operands: vec![Op::Int(2)],
6188            },
6189        );
6190    }
6191
6192    /// Give the function a local `new.target`, for an arrow inside it to capture.
6193    fn provide_new_target_local(&mut self) {
6194        let current = self.stack.len() - 1;
6195        if !self.stack[current].needs_new_target_local {
6196            return;
6197        }
6198        if !self.stack[current]
6199            .vars
6200            .iter()
6201            .any(|var| var.name == NEW_TARGET)
6202        {
6203            self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
6204        }
6205        self.prepend_initialiser(
6206            NEW_TARGET,
6207            Insn::Fixed {
6208                op: Opcode::SpecialObject,
6209                operands: vec![Op::Int(3)],
6210            },
6211        );
6212    }
6213
6214    /// `arguments` reached from an arrow, which likewise belongs to the enclosing
6215    /// function.
6216    fn ensure_enclosing_arguments(&mut self) {
6217        // An arrow created in a parameter list needs the *parameter* scope's
6218        // `arguments`, not the body's: the two are separate bindings and the arrow was
6219        // born before the body existed.
6220        let from_params = self.cur().created_in_params;
6221        if let Some(target) = self.enclosing_function() {
6222            self.state_at(target).needs_arguments_local = true;
6223            if from_params {
6224                self.state_at(target).needs_param_arguments = true;
6225                // Declare it now, not at the enclosing function's `finish_current`: the
6226                // arrow resolves its own `arguments` before that runs, and a binding that
6227                // does not exist yet resolves as a global.
6228                declare_param_var_at(&mut self.stack[target], "arguments");
6229            }
6230            self.declare_at(target, "arguments");
6231        }
6232    }
6233
6234    /// The innermost enclosing frame that is a real function — an arrow inherits from it
6235    /// rather than starting a scope of its own.
6236    fn enclosing_function(&self) -> Option<usize> {
6237        (0..self.stack.len())
6238            .rev()
6239            .find(|index| !self.stack[*index].is_arrow && !self.stack[*index].is_script)
6240    }
6241
6242    fn state_at(&mut self, index: usize) -> &mut FnState {
6243        &mut self.stack[index]
6244    }
6245
6246    /// Declare a `var` binding directly in a specific frame.
6247    fn declare_at(&mut self, index: usize, name: &str) {
6248        let state = &mut self.stack[index];
6249        if state.vars.iter().any(|var| var.name == name) {
6250            return;
6251        }
6252        state.var_block.push(FUNCTION_SCOPE);
6253        state.vars.push(VarDef::var(name));
6254    }
6255
6256    /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
6257    /// the reference calls a `special_object` gets initialised on entry.
6258    fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
6259        let current = self.stack.len() - 1;
6260        let init = [
6261            producer,
6262            Insn::Var {
6263                action: VarAction::Put,
6264                name: name.to_string(),
6265                block: 0,
6266                // A prologue initialiser runs before the body proper, but it is body
6267                // code: `this` and `arguments` are provided for it, not by it.
6268                in_params: false,
6269            },
6270        ];
6271        let inserted = init.len();
6272        for (index, instruction) in init.into_iter().enumerate() {
6273            self.stack[current].insns.insert(index, instruction);
6274        }
6275        for placed in self.stack[current].labels.iter_mut().flatten() {
6276            *placed += inserted;
6277        }
6278        self.stack[current].label_since_insn = true;
6279    }
6280
6281    fn push_constant(&mut self, constant: Constant) -> u32 {
6282        let state = self.state();
6283        let index = state.cpool.len() as u32;
6284        state.cpool.push(constant);
6285        index
6286    }
6287
6288    /// Compile `a && b`, `a || b`, `a ?? b`.
6289    ///
6290    /// A run of the *same* operator shares one end label, so `a || b || c` tests
6291    /// `a` once and jumps past everything when it is truthy, instead of falling
6292    /// into `b`'s test. The parser builds such a run left-associated —
6293    /// `((a || b) || c)` — so the operands are collected off the left spine.
6294    ///
6295    /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
6296    /// `||`'s label, because the inner chain really does end before `&&` begins.
6297    fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
6298        let mut operands = Vec::new();
6299        collect_same_operator(op, left, &mut operands);
6300        operands.push(right);
6301
6302        let end = self.new_label();
6303        // Every operand but the last decides whether the chain stops here.
6304        let last = operands.pop().expect("the right operand is always present");
6305        for operand in operands {
6306            self.expr(operand)?;
6307            self.emit(Opcode::Dup, &[]);
6308            match op {
6309                LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
6310                LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
6311                // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
6312                // `0 || b` is `b`. The dedicated test keeps the value unless it is
6313                // null-ish, so the jump is taken on `false`.
6314                LogicalOp::Coalesce => {
6315                    self.emit(Opcode::IsUndefinedOrNull, &[]);
6316                    self.emit_jump(Opcode::IfFalse, end, &[]);
6317                }
6318            }
6319            self.emit(Opcode::Drop, &[]);
6320        }
6321        self.expr(last)?;
6322        self.place_label(end);
6323        Ok(())
6324    }
6325
6326    fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
6327        match op {
6328            UnaryOp::Typeof => {
6329                // `typeof x` must not throw on an undeclared name.
6330                if let ExprKind::Ident(name) = &argument.kind {
6331                    self.emit_var(VarAction::GetUndef, &name.name);
6332                } else {
6333                    self.expr(argument)?;
6334                }
6335                self.emit(Opcode::Typeof, &[]);
6336            }
6337            UnaryOp::Delete => {
6338                // `delete obj.prop` really deletes, and answers whether it could.
6339                // Deleting a *binding* is always `false`: a local, an argument and a
6340                // declared global are all non-configurable, which the reference encodes
6341                // as a constant `push_false` rather than a runtime check. Only a
6342                // property access has anything to do at run time.
6343                // `delete super.x` is not a delete at all: the spec refuses it, and the
6344                // reference encodes the refusal as a `throw_error`. The receiver and the
6345                // key are still evaluated first, which is what keeps the evaluation order
6346                // of the operand intact.
6347                // `delete z?.b.c` answers `true` when the chain short-circuits: there is
6348                // nothing to delete, and a failed delete is not the same as a skipped
6349                // one. The reference emits the guards so they land on a `drop; push_true`
6350                // tail, which is what this reproduces.
6351                if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
6352                    && let ExprKind::Member {
6353                        object, property, ..
6354                    } = &inner.unparen().kind
6355                {
6356                    let end = self.new_label();
6357                    let done = self.new_label();
6358                    self.chain_link(object, end)?;
6359                    match property {
6360                        MemberProp::Ident(name) => self.emit(
6361                            Opcode::PushAtomValue,
6362                            &[Op::Atom(Atom::from_text(&name.name))],
6363                        ),
6364                        MemberProp::Computed(index) => self.expr(index)?,
6365                        MemberProp::Private(_) => {
6366                            return Err(SyntaxError::new(
6367                                "deleting a private field is not allowed",
6368                                argument.span,
6369                            ));
6370                        }
6371                    }
6372                    self.emit(Opcode::Delete, &[]);
6373                    self.emit_jump(Opcode::Goto, done, &[]);
6374                    self.place_label(end);
6375                    self.emit(Opcode::Drop, &[]);
6376                    self.emit(Opcode::PushTrue, &[]);
6377                    self.place_label(done);
6378                    return Ok(());
6379                }
6380                if let ExprKind::Member { object, .. } = &argument.unparen().kind
6381                    && matches!(object.unparen().kind, ExprKind::SuperProp)
6382                {
6383                    self.super_base();
6384                    self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
6385                    return Ok(());
6386                }
6387                match &argument.kind {
6388                    ExprKind::Member {
6389                        object, property, ..
6390                    } => {
6391                        self.expr(object)?;
6392                        match property {
6393                            MemberProp::Ident(name) => {
6394                                self.emit(
6395                                    Opcode::PushAtomValue,
6396                                    &[Op::Atom(Atom::from_text(&name.name))],
6397                                );
6398                            }
6399                            MemberProp::Computed(index) => self.expr(index)?,
6400                            MemberProp::Private(_) => {
6401                                return Err(SyntaxError::new(
6402                                    "deleting a private field is not allowed",
6403                                    argument.span,
6404                                ));
6405                            }
6406                        }
6407                        self.emit(Opcode::Delete, &[]);
6408                    }
6409                    ExprKind::Ident(name) => {
6410                        // `delete name`: a declared global, a local and an argument all
6411                        // answer `false`, but an *implicit* global (`x = 1` with no
6412                        // declaration) is a configurable property of the global object
6413                        // and really goes away. Which of those a name is only the
6414                        // resolver knows, so the decision waits for it.
6415                        let pos = self.cur().cur_pos;
6416                        self.state().insns.push(Insn::DeleteVar {
6417                            name: name.name.clone(),
6418                        });
6419                        self.state().insn_pos.push(pos);
6420                    }
6421                    _ => self.emit(Opcode::PushFalse, &[]),
6422                }
6423            }
6424            UnaryOp::Void => {
6425                self.expr(argument)?;
6426                self.emit(Opcode::Drop, &[]);
6427                self.emit(Opcode::Undefined, &[]);
6428            }
6429            UnaryOp::Minus => {
6430                self.expr(argument)?;
6431                self.emit(Opcode::Neg, &[]);
6432            }
6433            UnaryOp::Plus => {
6434                self.expr(argument)?;
6435                self.emit(Opcode::Plus, &[]);
6436            }
6437            UnaryOp::Not => {
6438                self.expr(argument)?;
6439                self.emit(Opcode::Lnot, &[]);
6440            }
6441            UnaryOp::BitNot => {
6442                self.expr(argument)?;
6443                self.emit(Opcode::Not, &[]);
6444            }
6445        }
6446        Ok(())
6447    }
6448
6449    /// Compile an assignment.
6450    ///
6451    /// Three operator families, three shapes:
6452    ///
6453    /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
6454    ///   the value is kept, because `put_field`/`put_array_el` consume both the
6455    ///   object and the value: `insert2` is `obj a -> a obj a`, so the store sees
6456    ///   the pair it wants and leaves a copy on top.
6457    /// * **compound** `+=` … — read the place, apply the operator, store. A member
6458    ///   reads through `get_field2`/`get_array_el3`, which leave the object (and
6459    ///   index) underneath the value precisely so the store can follow.
6460    /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
6461    ///   right-hand side. The test *keeps* the current value and skips the store
6462    ///   entirely, which is the whole point: `a ||= b` must not evaluate `b` when
6463    ///   `a` is already truthy.
6464    fn assign(
6465        &mut self,
6466        op: AssignOp,
6467        target: &Pattern,
6468        value: &Expr,
6469        discard: bool,
6470    ) -> Result<(), SyntaxError> {
6471        // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
6472        // about, so it is set only when this assignment *is* that expression.
6473        let keep = !discard;
6474        match &target.kind {
6475            PatternKind::Ident(name) => {
6476                // A *simple* store is blamed on the identifier, not on the `=`: a
6477                // strict-mode `not_def = 1` raises when the name is written, which the
6478                // reference reports at the name's column. A compound store is blamed on
6479                // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
6480                // which the reference reports at the `+=`), so only the simple case
6481                // moves the position.
6482                let saved = self.cur().cur_pos;
6483                let name_pos = Some(name.span.start);
6484                if matches!(op, AssignOp::Assign) {
6485                    self.state().cur_pos = name_pos;
6486                }
6487                // A *compound* store reads the binding before it combines, and that read
6488                // is blamed on the identifier: `not_def += 2` fails while reading
6489                // `not_def`, so the position is the name's, not the `+=`'s. The
6490                // combination that follows is blamed on the operator, which is why
6491                // `cur_pos` is put back to the operator position before it is emitted.
6492                self.state().cur_pos = name_pos;
6493                match op {
6494                    AssignOp::Assign => {
6495                        self.expr(value)?;
6496                        self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
6497                        // A discarded store to a *slot* consumes its value, so no copy
6498                        // is needed. A global store goes through `put_var`, which the
6499                        // reference always pairs with a `dup` — matching it keeps the
6500                        // bytecode identical. Getting this wrong is not only an extra
6501                        // instruction: a stray copy gives the peephole a chance to fold
6502                        // the store into an unrelated later read.
6503                        let slot = self.is_slot(&name.name);
6504                        if keep || !slot {
6505                            self.emit(Opcode::Dup, &[]);
6506                        }
6507                        self.state().no_value = !keep && slot;
6508                        self.emit_var(VarAction::Put, &name.name);
6509                    }
6510                    AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6511                        let end = self.new_label();
6512                        self.emit_var(VarAction::Get, &name.name);
6513                        self.state().cur_pos = saved;
6514                        self.emit(Opcode::Dup, &[]);
6515                        self.emit_logical_test(op);
6516                        self.emit_jump(logical_jump(op), end, &[]);
6517                        self.emit(Opcode::Drop, &[]);
6518                        self.expr(value)?;
6519                        self.emit(Opcode::Dup, &[]);
6520                        self.emit_var(VarAction::Put, &name.name);
6521                        self.place_label(end);
6522                    }
6523                    _ => {
6524                        self.emit_var(VarAction::Get, &name.name);
6525                        self.expr(value)?;
6526                        self.state().cur_pos = saved;
6527                        self.emit(compound_opcode(op), &[]);
6528                        self.emit(Opcode::Dup, &[]);
6529                        self.emit_var(VarAction::Put, &name.name);
6530                    }
6531                }
6532                self.state().cur_pos = saved;
6533                Ok(())
6534            }
6535            PatternKind::Member(member) => {
6536                // `super.x = v` is not a store through a value: it starts at the home
6537                // object's prototype but writes to `this`, so it goes through
6538                // `put_super_value` rather than `put_field`. The receiver, prototype, key
6539                // and value are handed over together.
6540                if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
6541                    return self.assign_super(member, op, value);
6542                }
6543                // A store is blamed on the selector punctuator (`.` or `[`), the same
6544                // token a load is blamed on — the reference records `put_field obj.a`
6545                // at the `.`, so a setter that throws reports that column and not the
6546                // `=` of the assignment it sits in. The inner expressions restore their
6547                // own positions, so the selector's sticks for the store instructions.
6548                let saved = self.cur().cur_pos;
6549                self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6550                self.expr(&member.object)?;
6551                match &member.property {
6552                    MemberProp::Ident(property) => {
6553                        let atom = Atom::from_text(&property.name);
6554                        match op {
6555                            AssignOp::Assign => {
6556                                self.expr(value)?;
6557                                // `put_field` consumes the object and the value, so
6558                                // without `insert2` nothing is left over for the
6559                                // statement to drop.
6560                                self.state().no_value = !keep;
6561                                if keep {
6562                                    self.emit(Opcode::Insert2, &[]);
6563                                }
6564                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6565                            }
6566                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6567                                // `get_field2` leaves the object under the value, so
6568                                // the keep path has an object to dispose of. The store
6569                                // path must jump *over* that cleanup: falling into it
6570                                // would `nip` a stack that only holds the value.
6571                                let (keep_label, end) = (self.new_label(), self.new_label());
6572                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6573                                self.emit(Opcode::Dup, &[]);
6574                                self.emit_logical_test(op);
6575                                self.emit_jump(logical_jump(op), keep_label, &[]);
6576                                self.emit(Opcode::Drop, &[]);
6577                                self.expr(value)?;
6578                                self.emit(Opcode::Insert2, &[]);
6579                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6580                                self.emit_jump(Opcode::Goto, end, &[]);
6581                                self.place_label(keep_label);
6582                                self.emit(Opcode::Nip, &[]);
6583                                self.place_label(end);
6584                            }
6585                            _ => {
6586                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6587                                self.expr(value)?;
6588                                self.emit(compound_opcode(op), &[]);
6589                                self.state().no_value = !keep;
6590                                if keep {
6591                                    self.emit(Opcode::Insert2, &[]);
6592                                }
6593                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6594                            }
6595                        }
6596                    }
6597                    MemberProp::Computed(index) => {
6598                        self.expr(index)?;
6599                        match op {
6600                            AssignOp::Assign => {
6601                                self.expr(value)?;
6602                                self.state().no_value = !keep;
6603                                if keep {
6604                                    self.emit(Opcode::Insert3, &[]);
6605                                }
6606                                self.emit(Opcode::PutArrayEl, &[]);
6607                            }
6608                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6609                                let (keep_label, end) = (self.new_label(), self.new_label());
6610                                self.emit(Opcode::GetArrayEl3, &[]);
6611                                self.emit(Opcode::Dup, &[]);
6612                                self.emit_logical_test(op);
6613                                self.emit_jump(logical_jump(op), keep_label, &[]);
6614                                self.emit(Opcode::Drop, &[]);
6615                                self.expr(value)?;
6616                                self.emit(Opcode::Insert3, &[]);
6617                                self.emit(Opcode::PutArrayEl, &[]);
6618                                self.emit_jump(Opcode::Goto, end, &[]);
6619                                self.place_label(keep_label);
6620                                // Both the object and the index are left over.
6621                                self.emit(Opcode::Nip, &[]);
6622                                self.emit(Opcode::Nip, &[]);
6623                                self.place_label(end);
6624                            }
6625                            _ => {
6626                                self.emit(Opcode::GetArrayEl3, &[]);
6627                                self.expr(value)?;
6628                                self.emit(compound_opcode(op), &[]);
6629                                self.state().no_value = !keep;
6630                                if keep {
6631                                    self.emit(Opcode::Insert3, &[]);
6632                                }
6633                                self.emit(Opcode::PutArrayEl, &[]);
6634                            }
6635                        }
6636                    }
6637                    MemberProp::Private(name) => {
6638                        // `obj value` is on the stack, and every private store wants exactly
6639                        // that. A top-level private name cannot be assigned (the parser rejects
6640                        // `#x = 1`), so the only way here is `this.#x = …` inside the class.
6641                        //
6642                        // The reference emits `insert2` whether or not the value is wanted,
6643                        // so this does too: the copy left behind is the assignment expression's
6644                        // value, and a discarded one is simply never read.
6645                        let binding = format!("#{}", name.name);
6646                        let (kind, setter) = self.private_use(&binding, member.span)?;
6647                        match op {
6648                            AssignOp::Assign => {
6649                                self.expr(value)?;
6650                                if keep {
6651                                    self.emit(Opcode::Insert2, &[]);
6652                                }
6653                                self.private_store(&binding, kind, setter.as_deref())?;
6654                                self.state().no_value = !keep;
6655                            }
6656                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6657                                let (keep_label, end) = (self.new_label(), self.new_label());
6658                                self.emit(Opcode::Dup, &[]);
6659                                self.private_load(&binding, kind, member.span)?;
6660                                self.emit(Opcode::Dup, &[]);
6661                                self.emit_logical_test(op);
6662                                self.emit_jump(logical_jump(op), keep_label, &[]);
6663                                self.emit(Opcode::Drop, &[]);
6664                                self.expr(value)?;
6665                                self.emit(Opcode::Insert2, &[]);
6666                                self.private_store(&binding, kind, setter.as_deref())?;
6667                                self.emit_jump(Opcode::Goto, end, &[]);
6668                                self.place_label(keep_label);
6669                                self.emit(Opcode::Nip, &[]);
6670                                self.place_label(end);
6671                            }
6672                            _ => {
6673                                self.emit(Opcode::Dup, &[]);
6674                                self.private_load(&binding, kind, member.span)?;
6675                                self.expr(value)?;
6676                                self.emit(compound_opcode(op), &[]);
6677                                self.emit(Opcode::Insert2, &[]);
6678                                self.private_store(&binding, kind, setter.as_deref())?;
6679                            }
6680                        }
6681                    }
6682                }
6683                self.state().cur_pos = saved;
6684                Ok(())
6685            }
6686            // A destructuring assignment: the right-hand side is the expression's own
6687            // value, so it is evaluated once and kept under the pattern's stores.
6688            PatternKind::Array { .. } | PatternKind::Object { .. } => {
6689                self.expr(value)?;
6690                if keep {
6691                    self.emit(Opcode::Dup, &[]);
6692                }
6693                self.destructure(target, None)?;
6694                self.state().no_value = !keep;
6695                Ok(())
6696            }
6697            _ => Err(SyntaxError::new(
6698                "this assignment target is not supported by the compiler yet",
6699                target.span,
6700            )),
6701        }
6702    }
6703
6704    /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
6705    ///
6706    /// The stack has to carry four values — receiver, prototype, key, value — because
6707    /// `put_super_value` takes them together; the receiver is what makes a setter found on
6708    /// the prototype run with `this`, and the key has to survive until the store, which is
6709    /// why a compound form converts it to a property key once and `dup3`s rather than
6710    /// evaluating it twice.
6711    fn assign_super(
6712        &mut self,
6713        member: &MemberPattern,
6714        op: AssignOp,
6715        value: &Expr,
6716    ) -> Result<(), SyntaxError> {
6717        let saved = self.cur().cur_pos;
6718        self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6719        self.super_base();
6720        match &member.property {
6721            MemberProp::Ident(property) => self.emit(
6722                Opcode::PushAtomValue,
6723                &[Op::Atom(Atom::from_text(&property.name))],
6724            ),
6725            MemberProp::Computed(index) => self.expr(index)?,
6726            MemberProp::Private(_) => {
6727                return Err(SyntaxError::new(
6728                    "private fields are not supported by the compiler yet",
6729                    member.span,
6730                ));
6731            }
6732        }
6733        match op {
6734            AssignOp::Assign => {
6735                // The key is only converted once, by `put_super_value` itself, so a
6736                // computed key's `toString` runs exactly once.
6737                self.expr(value)?;
6738                self.emit(Opcode::Insert4, &[]);
6739                self.emit(Opcode::PutSuperValue, &[]);
6740            }
6741            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6742                let (keep_label, end) = (self.new_label(), self.new_label());
6743                self.emit(Opcode::ToPropkey, &[]);
6744                self.emit(Opcode::Dup3, &[]);
6745                self.emit(Opcode::GetSuperValue, &[]);
6746                self.emit(Opcode::Dup, &[]);
6747                self.emit_logical_test(op);
6748                self.emit_jump(logical_jump(op), keep_label, &[]);
6749                self.emit(Opcode::Drop, &[]);
6750                self.expr(value)?;
6751                self.emit(Opcode::Insert4, &[]);
6752                self.emit(Opcode::PutSuperValue, &[]);
6753                self.emit_jump(Opcode::Goto, end, &[]);
6754                self.place_label(keep_label);
6755                // The prototype and the key are still under the value that was read.
6756                self.emit(Opcode::Nip, &[]);
6757                self.emit(Opcode::Nip, &[]);
6758                self.emit(Opcode::Nip, &[]);
6759                self.place_label(end);
6760            }
6761            _ => {
6762                self.emit(Opcode::ToPropkey, &[]);
6763                self.emit(Opcode::Dup3, &[]);
6764                self.emit(Opcode::GetSuperValue, &[]);
6765                self.expr(value)?;
6766                self.emit(compound_opcode(op), &[]);
6767                self.emit(Opcode::Insert4, &[]);
6768                self.emit(Opcode::PutSuperValue, &[]);
6769            }
6770        }
6771        // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
6772        // is still on the stack when the store finishes, and the expression statement is
6773        // what disposes of it — the same arrangement as `put_field`, reached from the other
6774        // side: there the store consumes the value (`no_value`), here it leaves it
6775        // (`keep` already false, so nothing tells the statement otherwise).
6776        self.state().cur_pos = saved;
6777        Ok(())
6778    }
6779
6780    /// The test a logical assignment applies to the current value.
6781    ///
6782    /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
6783    /// assign, while `0 ||= b` must not.
6784    fn emit_logical_test(&mut self, op: AssignOp) {
6785        if op == AssignOp::Coalesce {
6786            self.emit(Opcode::IsUndefinedOrNull, &[]);
6787        }
6788    }
6789
6790    /// The private name `#name` this use site resolves against.
6791    ///
6792    /// The parser has already rejected a name no enclosing class declares, so a miss here
6793    /// means the compiler lost track of a class scope — which is worth a real error rather
6794    /// than an `unwrap`.
6795    fn private_use(
6796        &self,
6797        binding: &str,
6798        span: Span,
6799    ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
6800        ClassPlan::find(self, binding)
6801            .map(|use_| (use_.kind, use_.setter.clone()))
6802            .ok_or_else(|| {
6803                SyntaxError::new(
6804                    format!("the private name '{binding}' is out of scope here"),
6805                    span,
6806                )
6807            })
6808    }
6809
6810    /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
6811    ///
6812    /// The three readable kinds take three different instructions, because a private name
6813    /// holds three different things — a symbol, a method function, a getter function — and
6814    /// only the first one is a property read at all.
6815    fn private_load(
6816        &mut self,
6817        binding: &str,
6818        kind: PrivateKind,
6819        span: Span,
6820    ) -> Result<(), SyntaxError> {
6821        match kind {
6822            PrivateKind::Field => {
6823                self.emit_var(VarAction::Get, binding);
6824                self.emit(Opcode::GetPrivateField, &[]);
6825            }
6826            PrivateKind::Method => {
6827                self.emit_var(VarAction::Get, binding);
6828                self.emit(Opcode::CheckBrand, &[]);
6829                // `check_brand` reads `obj func` and leaves both; the method itself is what
6830                // `this.#m` evaluates to.
6831                self.emit(Opcode::Nip, &[]);
6832            }
6833            PrivateKind::Getter => {
6834                self.emit_var(VarAction::Get, binding);
6835                self.emit(Opcode::CheckBrand, &[]);
6836                self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6837            }
6838            // `#a` is declared but never filled when only a setter exists, so reading it is
6839            // the same refusal as assigning to a `const`. The reference reports it with the
6840            // generic read-only wording and leaves the better message as a `XXX`.
6841            PrivateKind::Setter => self.emit(
6842                Opcode::ThrowError,
6843                &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
6844            ),
6845        }
6846        let _ = span;
6847        Ok(())
6848    }
6849
6850    /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
6851    fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
6852        match kind {
6853            // A method *is* the callee, so only the check goes in between.
6854            PrivateKind::Method => {
6855                self.emit_var(VarAction::Get, binding);
6856                self.emit(Opcode::CheckBrand, &[]);
6857            }
6858            _ => self.private_load(binding, kind, Span::default())?,
6859        }
6860        Ok(())
6861    }
6862
6863    /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
6864    /// wanted back.
6865    ///
6866    /// A getter/setter pair is a *method call*, not a property store: the reference reads
6867    /// the setter out of its own binding and calls it with the receiver, which is why the
6868    /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
6869    /// keeps the assignment's value for an expression context.
6870    fn private_store(
6871        &mut self,
6872        binding: &str,
6873        kind: PrivateKind,
6874        setter: Option<&str>,
6875    ) -> Result<(), SyntaxError> {
6876        match kind {
6877            PrivateKind::Field => {
6878                self.emit_var(VarAction::Get, binding);
6879                self.emit(Opcode::PutPrivateField, &[]);
6880            }
6881            PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
6882                Some(setter) => {
6883                    self.emit_var(VarAction::Get, setter);
6884                    // `obj func value` -> `value obj func` for the check, and back again for
6885                    // the call, which wants `obj func arg`.
6886                    self.emit(Opcode::Swap, &[]);
6887                    self.emit(Opcode::Rot3r, &[]);
6888                    self.emit(Opcode::CheckBrand, &[]);
6889                    self.emit(Opcode::Rot3l, &[]);
6890                    self.emit(Opcode::CallMethod, &[Op::Int(1)]);
6891                    // The setter's return value is discarded; the assignment's own value is
6892                    // whatever the caller left underneath.
6893                    self.emit(Opcode::Drop, &[]);
6894                }
6895                None => self.emit(
6896                    Opcode::ThrowError,
6897                    &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
6898                ),
6899            },
6900        }
6901        Ok(())
6902    }
6903
6904    fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
6905        let instruction = match (op, prefix) {
6906            (UpdateOp::Increment, true) => Opcode::Inc,
6907            (UpdateOp::Increment, false) => Opcode::PostInc,
6908            (UpdateOp::Decrement, true) => Opcode::Dec,
6909            (UpdateOp::Decrement, false) => Opcode::PostDec,
6910        };
6911        if let ExprKind::Member {
6912            object,
6913            property,
6914            optional: _,
6915        } = &argument.kind
6916        {
6917            // `o.x++` needs the receiver twice, so the last link is read with the
6918            // `get_*2`/`get_*3` form that keeps it, and the update is written back
6919            // with `put_field`/`put_array_el`. The reordering in between is what puts
6920            // the old value below the receiver for a postfix update and the new one
6921            // above it for a prefix one:
6922            //
6923            //   `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
6924            //   `obj val` → `inc`      → `obj new new` → `insert2` → `new obj new`
6925            //
6926            // This mirrors the reference instruction for instruction.
6927            self.expr(object)?;
6928            match property {
6929                MemberProp::Ident(name) => {
6930                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
6931                    self.emit(instruction, &[]);
6932                    self.emit(
6933                        if prefix {
6934                            Opcode::Insert2
6935                        } else {
6936                            Opcode::Perm3
6937                        },
6938                        &[],
6939                    );
6940                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
6941                }
6942                MemberProp::Computed(index) => {
6943                    self.expr(index)?;
6944                    self.emit(Opcode::GetArrayEl3, &[]);
6945                    self.emit(instruction, &[]);
6946                    self.emit(
6947                        if prefix {
6948                            Opcode::Insert3
6949                        } else {
6950                            Opcode::Perm4
6951                        },
6952                        &[],
6953                    );
6954                    self.emit(Opcode::PutArrayEl, &[]);
6955                }
6956                MemberProp::Private(name) => {
6957                    // The receiver is duplicated and the read keeps it, exactly as `get_field2`
6958                    // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
6959                    // `perm3` -> `old obj new` -> store.
6960                    let binding = format!("#{}", name.name);
6961                    let (kind, setter) = self.private_use(&binding, argument.span)?;
6962                    self.emit(Opcode::Dup, &[]);
6963                    self.private_load(&binding, kind, argument.span)?;
6964                    self.emit(instruction, &[]);
6965                    self.emit(
6966                        if prefix {
6967                            Opcode::Insert2
6968                        } else {
6969                            Opcode::Perm3
6970                        },
6971                        &[],
6972                    );
6973                    self.private_store(&binding, kind, setter.as_deref())?;
6974                }
6975            }
6976            return Ok(());
6977        }
6978        let ExprKind::Ident(name) = &argument.kind else {
6979            return Err(SyntaxError::new(
6980                "increment of a non-variable is not supported by the compiler yet",
6981                argument.span,
6982            ));
6983        };
6984        // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
6985        // reference's `inc_loc` folds those three into one, but it does so only in some
6986        // positions (a `for` update and not a bare statement, and never for a lexical
6987        // binding), so emitting it unconditionally would move *away* from its output.
6988        // The instruction is equivalent either way; matching the reference matters more
6989        // than saving two instructions.
6990        let _ = !std::mem::take(&mut self.state().discard_value);
6991        self.emit_var(VarAction::Get, &name.name);
6992        self.emit(instruction, &[]);
6993        if prefix {
6994            self.emit(Opcode::Dup, &[]);
6995        }
6996        self.emit_var(VarAction::Put, &name.name);
6997        Ok(())
6998    }
6999
7000    /// Compile an array literal.
7001    ///
7002    /// The reference splits this into three phases, and the split is load-bearing
7003    /// rather than an optimisation detail:
7004    ///
7005    /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
7006    ///    the array in one instruction.
7007    /// 2. **Everything up to the first spread** is appended with explicit indices
7008    ///    (`define_field <index>`), because a hole has no element to pass to
7009    ///    `array_from`. A hole here is what makes `length` need fixing up: an
7010    ///    explicit index does not extend the array the way a pushed element does.
7011    /// 3. **From the first spread on** the index lives on the stack, so `append` and
7012    ///    `define_array_el` can consume it and `inc` advances it.
7013    ///
7014    /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
7015    /// forces phase 2, and `[...a]` forces phase 3.
7016    fn array_literal(
7017        &mut self,
7018        elements: &[Option<ArrayElement>],
7019        span: Span,
7020    ) -> Result<(), SyntaxError> {
7021        let _ = span;
7022        let mut index: u32 = 0;
7023        let mut cursor = 0usize;
7024
7025        // Phase 1: a leading run of plain elements, at most 32 of them.
7026        while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
7027            if index >= 32 {
7028                break;
7029            }
7030            self.expr(element)?;
7031            index += 1;
7032            cursor += 1;
7033        }
7034        self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
7035
7036        // Phase 2: explicit indices, up to the first spread.
7037        let mut need_length = false;
7038        while let Some(element) = elements.get(cursor) {
7039            if matches!(element, Some(ArrayElement::Spread(_))) {
7040                break;
7041            }
7042            need_length = true;
7043            if let Some(ArrayElement::Expr(expression)) = element {
7044                self.expr(expression)?;
7045                self.emit_define_index(index);
7046                need_length = false;
7047            }
7048            index += 1;
7049            cursor += 1;
7050        }
7051
7052        if cursor >= elements.len() {
7053            if need_length {
7054                // `define_field` cannot set `length`, which is not configurable.
7055                self.emit(Opcode::Dup, &[]);
7056                self.push_number(index as f64);
7057                self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7058            }
7059            return Ok(());
7060        }
7061
7062        // Phase 3: the index moves onto the stack for the spreading tail.
7063        //
7064        // `need_length` deliberately carries over from phase 2: a hole before the
7065        // first spread still has to be reflected in `length`, and only the final
7066        // check can do it because the array is not finished until the tail is
7067        // appended.
7068        self.push_number(index as f64);
7069        while let Some(element) = elements.get(cursor) {
7070            match element {
7071                Some(ArrayElement::Spread(expression)) => {
7072                    // `append` copies an iterable and leaves the next index behind,
7073                    // so no `inc` is needed here.
7074                    self.expr(spread_argument(expression))?;
7075                    self.emit(Opcode::Append, &[]);
7076                }
7077                None | Some(ArrayElement::Expr(_)) => {
7078                    need_length = true;
7079                    if let Some(ArrayElement::Expr(expression)) = element {
7080                        self.expr(expression)?;
7081                        self.emit(Opcode::DefineArrayEl, &[]);
7082                        need_length = false;
7083                    }
7084                    self.emit(Opcode::Inc, &[]);
7085                }
7086            }
7087            cursor += 1;
7088        }
7089        if need_length {
7090            self.emit(Opcode::Dup1, &[]);
7091            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7092        } else {
7093            self.emit(Opcode::Drop, &[]);
7094        }
7095        Ok(())
7096    }
7097
7098    /// `define_field` with an array-index atom, which is how phase 2 stores elements.
7099    fn emit_define_index(&mut self, index: u32) {
7100        self.emit(
7101            Opcode::DefineField,
7102            &[Op::Atom(Atom::from_text(&index.to_string()))],
7103        );
7104    }
7105
7106    // -- functions ---------------------------------------------------------
7107
7108    fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
7109        self.compile_function_with_name(func, false)
7110    }
7111
7112    /// Compile a function, recording whether it is a *named function expression*.
7113    ///
7114    /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
7115    /// must not leak outside. The reference does that by declaring `g` as a local of
7116    /// the function itself and initialising it with `special_object 2` (the current
7117    /// function), which is why this has to be known at compile time.
7118    fn compile_function_with_name(
7119        &mut self,
7120        func: &ast::Function,
7121        is_expression: bool,
7122    ) -> Result<CompiledFunction, SyntaxError> {
7123        let kind = match (func.is_generator, func.is_async) {
7124            (false, false) => FunctionKind::Normal,
7125            (true, false) => FunctionKind::Generator,
7126            (false, true) => FunctionKind::Async,
7127            (true, true) => FunctionKind::AsyncGenerator,
7128        };
7129        let mut state = FnState::new(
7130            func.name
7131                .as_ref()
7132                .map(|n| n.name.clone())
7133                .unwrap_or_default(),
7134            kind,
7135        );
7136        // The function's own mode, recorded by the parser. Inheriting the enclosing
7137        // function's instead let a nested `"use strict"` directive be ignored, so the
7138        // body ran with sloppy `this`, sloppy `arguments` and no const checks.
7139        state.strict = func.strict;
7140        // A function defined inside a `with` block keeps seeing that object: the guard
7141        // chain names the enclosing `<with>` locals, which resolve outward into closure
7142        // variables exactly like any other captured binding.
7143        state.with_names = self.cur().with_names.clone();
7144        state.is_arrow = func.is_arrow;
7145        state.created_in_block = self.cur().current_block;
7146        // A default anywhere in the parameter list is what gives the function two
7147        // variable environments. The reference decides this the same way: it scans the
7148        // parenthesis for a top-level `=`, so a destructured name without a default
7149        // stays a plain function-scope binding.
7150        state.in_params = false;
7151        // The reference scans the parenthesis for *any* `=`, including one nested inside
7152        // a pattern, so `function f({a = 1})` has parameter expressions even though the
7153        // parameter itself carries no initialiser.
7154        state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
7155        // `IsSimpleParameterList`: no default, no rest, no destructuring. Unlike the
7156        // flag above this looks at the *shape* of each parameter, not just for `=`.
7157        state.simple_parameter_list = func
7158            .params
7159            .iter()
7160            .all(|pattern| matches!(pattern.kind, PatternKind::Ident(_)));
7161        // A function born inside a parameter list inherits the prohibition: it must not
7162        // see the body bindings of the function it was created in.
7163        state.created_in_params = self.cur().in_params || self.cur().created_in_params;
7164        // A class constructor knows what it is only because the class told it.
7165        if let Some(kind) = self.cur().class_ctor_pending {
7166            state.ctor_kind = kind;
7167        }
7168        // A named *expression* binds its own name; a declaration's name is already
7169        // bound in the enclosing scope.
7170        state.self_name = if is_expression && !func.is_arrow {
7171            func.name.as_ref().map(|n| n.name.clone())
7172        } else {
7173            None
7174        };
7175        // Keep the written range so `Function.prototype.toString` can answer with the
7176        // original text rather than `[native code]`.
7177        //
7178        // It starts at the *parameter list*, not at the function: §20.2.3.5 removes the
7179        // accessor and generator prefixes, and for a method it must not include the name
7180        // or a leading `static`. `params_span` is exactly that boundary.
7181        // A *method* keeps the old `[native code]` answer: its reported text is defined
7182        // by the method-definition grammar (no name, no `static`, no `get`/`set`, but
7183        // the comments in between kept verbatim), and reconstructing that from a byte
7184        // span got it wrong in more cases than it got right. A plain function and an
7185        // arrow are the shapes libraries actually introspect, and those are exact.
7186        // A method's reported text starts at its **key** — `m(){}`, `[expr](){}`,
7187        // `#f /* a */ ( /* b */ ) {}` — which is exactly where the parser put `span.start`,
7188        // so the same slice works for every form. (`Params_span` is the boundary that
7189        // excludes `static`/`async`/`get`, which the spec's method grammar also omits.)
7190        // `source_span` is set only where the reported text is not the function's own
7191        // range — a class's constructor reports the whole class definition.
7192        let reported = func.source_span.unwrap_or(func.span);
7193        state.span = Some((reported.start.offset as usize, reported.end.offset as usize));
7194        state.line = func.span.start.line;
7195        state.column = func.span.start.column;
7196        // A function body has no hidden `<ret>` local; the value comes back on
7197        // the stack. Only a script keeps one.
7198        // Parameters are positional, so even a pattern occupies one argument slot. A
7199        // simple name is that slot itself; anything else (a pattern, a default, a rest
7200        // parameter) takes an anonymous slot and is unpicked into locals at the top of
7201        // the body, which is the only way one argument can bind several names.
7202        let mut prologue: Vec<(usize, Pattern)> = Vec::new();
7203        // `.length` stops at the first parameter that can be substituted: a default
7204        // fills a missing argument in, and a rest parameter absorbs the rest.
7205        let mut defined_args = func.params.len() as u32;
7206        for (index, param) in func.params.iter().enumerate() {
7207            match simple_parameter(param) {
7208                Some(name) => state.args.push(VarDef::var(name.name.clone())),
7209                None => {
7210                    state.args.push(VarDef::var(ANONYMOUS_BINDING));
7211                    prologue.push((index, param.clone()));
7212                }
7213            }
7214        }
7215        // A default anywhere before the end also ends the count, which the loop above
7216        // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
7217        for (position, param) in func.params.iter().enumerate() {
7218            if matches!(
7219                param.kind,
7220                PatternKind::Assign { .. } | PatternKind::Rest(_)
7221            ) {
7222                defined_args = position as u32;
7223                break;
7224            }
7225        }
7226        state.defined_args = defined_args;
7227        state.param_prologue = prologue;
7228        let depth = self.stack.len();
7229        self.stack.push(state);
7230        let result = self.compile_function_body(func);
7231        if result.is_err() {
7232            // A failed compile must not leave its `FnState` behind. Every caller
7233            // reads `self.state()` as "the function being compiled", so a leftover
7234            // frame silently retargets all later bookkeeping at a dead function.
7235            self.stack.truncate(depth);
7236        }
7237        result
7238    }
7239
7240    /// The body of a function, with its frame already pushed.
7241    fn compile_function_body(
7242        &mut self,
7243        func: &ast::Function,
7244    ) -> Result<CompiledFunction, SyntaxError> {
7245        let body_key = func.params_span.end.offset as u64;
7246        // Where the body begins, in source order. The runtime needs this to tell a
7247        // closure created by a default expression from one the body creates — the two see
7248        // different variable environments — and a bytecode offset would not survive the
7249        // instruction shuffling that building the frame does. Positions are in source
7250        // order, so a comparison answers it.
7251        self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
7252        self.push_block(body_key, NO_PARENT);
7253        self.state().body_block = body_key;
7254        // An arrow with an expression body has no statements; the expression is
7255        // its `return`. Building the statement here keeps one code path below, and
7256        // matters for correctness beyond convenience: returning early with the new
7257        // `FnState` still on the stack would leave the compiler looking at the
7258        // wrong function, which surfaces as an unrelated underflow later.
7259        let concise = match &func.body {
7260            js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
7261                StmtKind::Return(Some(Box::new((**value).clone()))),
7262                value.span,
7263            )),
7264            js_parse::ast::FunctionBody::Block(_) => None,
7265        };
7266        let body: &[Stmt] = match &concise {
7267            Some(stmt) => std::slice::from_ref(stmt),
7268            None => func
7269                .body
7270                .statements()
7271                .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
7272        };
7273        let prologue = std::mem::take(&mut self.state().param_prologue);
7274        let has_param_scope = self.cur().has_parameter_expressions;
7275        // The parameter scope's own bindings, declared in source order.
7276        //
7277        // With parameter expressions the list gets a variable environment of its own, and
7278        // every name it binds is a `let` there. That is what puts the *list* in the
7279        // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
7280        // and `function f(x = y, y){}` does the same, where a single shared environment
7281        // would answer `undefined` to both.
7282        if has_param_scope {
7283            let mut declared: Vec<String> = Vec::new();
7284            for param in &func.params {
7285                let mut names = Vec::new();
7286                param.bound_names(&mut names);
7287                for name in names {
7288                    if declared.contains(&name.name) {
7289                        continue;
7290                    }
7291                    declared.push(name.name.clone());
7292                    self.declare_param_binding(&name.name);
7293                }
7294            }
7295        }
7296        // A pattern parameter binds its names as function-scope locals, so they have to
7297        // exist — and be unpicked from the argument — before the body runs. With a
7298        // parameter scope these are the *second* environment: the pattern fills the
7299        // parameter's copy, and the body's binding is filled from it afterwards.
7300        for (_, pattern) in &prologue {
7301            let mut names = Vec::new();
7302            pattern.bound_names(&mut names);
7303            for name in names {
7304                self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
7305            }
7306        }
7307        self.hoist(body, body_key)?;
7308        // A constructor's prologue is not a parameter unpacking but the `this` binding:
7309        // a base constructor takes the receiver, a derived one starts in the dead zone
7310        // because only `super()` may produce it.
7311        match self.cur().ctor_kind {
7312            CtorKind::None => {}
7313            CtorKind::Base => {
7314                self.begin_this_local();
7315                self.emit(Opcode::CheckCtor, &[]);
7316                // Instance fields are installed at the top of a base constructor's body,
7317                // before any statement — `class C { x = 1; constructor() { this.x } }` sees
7318                // `1`. This used to be emitted at the *tail*, which made every field read
7319                // `undefined` inside the constructor that declared it.
7320                self.call_field_initialiser();
7321            }
7322            CtorKind::Derived => {
7323                self.declare("this", VarDef::lexical("this"));
7324                let slot = self.cur().vars.len() as u32 - 1;
7325                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7326                self.emit(Opcode::CheckCtor, &[]);
7327            }
7328        }
7329        // Entering the parameter list: everything it binds starts in the dead zone.
7330        // The order is the reference's — it walks the scope chain, which is prepended, so
7331        // the bindings come out newest first.
7332        for name in self.param_binding_names().into_iter().rev() {
7333            if let Some(slot) = self.param_binding_slot(&name) {
7334                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7335            }
7336        }
7337        // The whole parameter list is one scope, and nothing in the body exists yet, so
7338        // every name it mentions resolves against the parameter bindings and outward.
7339        self.state().in_params = has_param_scope;
7340        for (index, param) in func.params.iter().enumerate() {
7341            if let Some(pattern) = prologue_pattern(&prologue, index) {
7342                // A destructuring parameter *initialises* its bindings: with a parameter
7343                // scope they are the list's own `let`s, which is why the stores skip the
7344                // dead-zone check, and why the reference reads their properties with
7345                // `get_field2` — a `let` needs no reference.
7346                let kind = if has_param_scope {
7347                    VarDeclKind::Let
7348                } else {
7349                    VarDeclKind::Var
7350                };
7351                match &pattern.kind {
7352                    // `...rest` collects what is left rather than reading one slot.
7353                    PatternKind::Rest(inner) => {
7354                        self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7355                        self.destructure(inner, Some(kind))?;
7356                    }
7357                    _ => {
7358                        self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7359                        self.destructure(pattern, Some(kind))?;
7360                    }
7361                }
7362                continue;
7363            }
7364            // A plain name binds straight from its argument slot. With a parameter scope
7365            // the slot is also copied into the parameter binding, which is what a later
7366            // default (or a closure made among the defaults) reads.
7367            let Some(name) = simple_parameter(param) else {
7368                continue;
7369            };
7370            let target = self.param_binding_slot(&name.name);
7371            if matches!(param.kind, PatternKind::Rest(_)) {
7372                self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7373                if let Some(slot) = target {
7374                    self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
7375                }
7376                // `put_arg` rather than `set_arg`: the array is the last thing on the
7377                // stack and nothing keeps it. Named by hand because a name in the
7378                // parameter list resolves to the parameter binding, and this store has to
7379                // reach the *argument* — that is what the body reads.
7380                self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
7381                continue;
7382            }
7383            if let PatternKind::Assign { default, .. } = &param.kind {
7384                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7385                let has_value = self.new_label();
7386                self.emit(Opcode::Dup, &[]);
7387                self.emit(Opcode::IsUndefined, &[]);
7388                self.emit_jump(Opcode::IfFalse, has_value, &[]);
7389                self.emit(Opcode::Drop, &[]);
7390                self.expr(default)?;
7391                self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
7392                // The argument slot keeps the substituted value, because the *body* reads
7393                // the slot rather than the parameter binding — so this store is named
7394                // explicitly, like the rest parameter's.
7395                self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7396                self.place_label(has_value);
7397                if let Some(slot) = target {
7398                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7399                }
7400                continue;
7401            }
7402            if let Some(slot) = target {
7403                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7404                self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7405            }
7406        }
7407        // Copy the parameter scope into the body. A plain parameter needs nothing: the
7408        // body reads its argument slot, and the list kept the two in step. A name a
7409        // pattern bound has no argument slot of its own, so the body gets a `var` filled
7410        // from the parameter's copy — and *that* is why an assignment inside a default
7411        // does not reach the body.
7412        if has_param_scope {
7413            for (_, pattern) in &prologue {
7414                let mut names = Vec::new();
7415                pattern.bound_names(&mut names);
7416                for name in names {
7417                    let Some(slot) = self.param_binding_slot(&name.name) else {
7418                        continue;
7419                    };
7420                    let Some(body) = self.body_var_slot(&name.name) else {
7421                        continue;
7422                    };
7423                    self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
7424                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
7425                }
7426            }
7427        }
7428        // The parameter list is over; from here on a direct `eval` belongs to the body.
7429        self.state().in_params = false;
7430        // Entering the body's own scope comes *after* the parameter list: the body's
7431        // `let`s are not in existence while the defaults run, and the reference emits
7432        // their `set_loc_uninitialized` only once the parameters are bound.
7433        self.emit_scope_enter(body_key);
7434        // A generator starts suspended: `initial_yield` parks the body so that creating one
7435        // runs no body code until the first `next()`.
7436        //
7437        // It comes *after* the parameter unpacking, not before, because a parameter
7438        // initialiser is not body code — `function* g(a = sideEffect())` must run
7439        // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
7440        // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
7441        // until the first `next()` and 29 test262 cases that check for a synchronous throw
7442        // saw none at all.
7443        //
7444        // An async function does **not** get one. Its body runs synchronously up to the
7445        // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
7446        // before its caller's next statement — so an `initial_yield` here would park the
7447        // body before it started, which is not fixable at run time: the suspension looks
7448        // exactly like a real `await`.
7449        if self.cur().kind.is_generator() {
7450            self.emit(Opcode::InitialYield, &[]);
7451        }
7452        // Through `stmts`: the body is a block, and a `using` declaration in it is a
7453        // disposal region.
7454        self.stmts(body)?;
7455        // The implicit return only exists if control can actually get here: an
7456        // infinite loop never falls off the end.
7457        if self.end_is_reachable() {
7458            if self.cur().is_suspending() {
7459                // Falling off the end finishes the generator with `undefined`, and the
7460                // value is what tells the resume machinery "completed" rather than
7461                // "suspended".
7462                self.emit(Opcode::Undefined, &[]);
7463                self.emit(Opcode::ReturnAsync, &[]);
7464            } else {
7465                self.emit_class_constructor_tail();
7466            }
7467        }
7468        // Resolution runs while this function is still on the stack: capturing a
7469        // variable from an enclosing function means reaching into that
7470        // function's state, which requires the whole chain to be present.
7471        Ok(self.finish_current())
7472    }
7473
7474    /// Put every binding of a function that contains a direct `eval` into a cell.
7475    ///
7476    /// A direct eval can name any binding in scope, and any closure it creates has to
7477    /// keep sharing that binding after the function returns — `for (let i …)
7478    /// eval("push(() => i)")` collects one closure per iteration and each must read its
7479    /// own `i`. A copy in a side table would freeze the value, so the binding has to be
7480    /// a cell. Doing this unconditionally for such functions is the cheap, honest
7481    /// answer: the alternative is knowing at compile time which names a string will
7482    /// mention.
7483    fn capture_everything_for_eval(&mut self) {
7484        let current = self.stack.len() - 1;
7485        if !self.stack[current].has_direct_eval {
7486            return;
7487        }
7488        for arg in &mut self.stack[current].args {
7489            arg.is_captured = true;
7490        }
7491        for var in &mut self.stack[current].vars {
7492            var.is_captured = true;
7493        }
7494    }
7495
7496    /// Whether the current position in the instruction stream can be reached.
7497    ///
7498    /// A walk over the control-flow graph, using labels as instruction indices.
7499    /// The reference does the same thing to decide whether an implicit
7500    /// `return_undef` is needed.
7501    fn end_is_reachable(&self) -> bool {
7502        let state = self.cur();
7503        reachable_instructions(state, state.insns.len())[state.insns.len()]
7504    }
7505
7506    /// Resolve and assemble the function on top of the compiler stack, then pop
7507    /// it.
7508    fn finish_current(&mut self) -> CompiledFunction {
7509        self.provide_param_arguments();
7510        self.provide_arguments();
7511        self.provide_this_local();
7512        self.provide_new_target_local();
7513        self.provide_home_object_local();
7514        self.provide_active_func_local();
7515        self.provide_self_name();
7516        self.materialize_eval_sites();
7517        self.capture_everything_for_eval();
7518        let (mut resolved, resolved_pos) = resolve(&mut self.stack);
7519        // Captured bindings need a reference cell; the count goes in the header so
7520        // the runtime knows how many cells to allocate on entry.
7521        let current = self.stack.len() - 1;
7522        let captured = self.stack[current]
7523            .args
7524            .iter()
7525            .filter(|a| a.is_captured)
7526            .count()
7527            + self.stack[current]
7528                .vars
7529                .iter()
7530                .filter(|v| v.is_captured)
7531                .count();
7532        self.stack[current].var_ref_count = captured as u32;
7533        // The scope chain is only final now that every binding is known.
7534        rebuild_scope_chain(&mut self.stack[current]);
7535        let (code, stack_size, positions) =
7536            assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
7537        let _ = &mut resolved;
7538        let mut state = self.stack.pop().expect("a function is being compiled");
7539        CompiledFunction {
7540            name: state.name,
7541            kind: state.kind,
7542            strict: state.strict,
7543            is_derived_constructor: matches!(state.ctor_kind, CtorKind::Derived),
7544            is_arrow: state.is_arrow,
7545            has_parameter_expressions: state.has_parameter_expressions,
7546            simple_parameter_list: state.simple_parameter_list,
7547            body_start: state.body_start,
7548            args: state.args,
7549            defined_args: state.defined_args,
7550            vars: state.vars,
7551            closure_vars: state.closure_vars,
7552            cpool: state.cpool,
7553            atoms: state.atoms,
7554            code,
7555            stack_size,
7556            var_ref_count: state.var_ref_count,
7557            positions,
7558            source: self.function_source(state.span, state.line, state.column),
7559            line: state.line,
7560            column: state.column,
7561            filename: None,
7562            eval_sites: state.eval_sites,
7563            module: state.module.take().map(Box::new),
7564        }
7565    }
7566}
7567
7568/// Assign each binding a scope level and rebuild the scope chains.
7569///
7570/// Levels are numbered in the order the blocks appear, with 0 reserved for the
7571/// function scope where `var` and hoisted functions live. Every binding outside
7572/// level 0 gets a `scope_next` link to the next binding visible from the same
7573/// point, so walking a block's chain enumerates exactly the bindings live there.
7574///
7575/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
7576/// point at `b`, which is declared later in the source but earlier in the chain.
7577fn rebuild_scope_chain(state: &mut FnState) {
7578    // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
7579    // real block that happens to start at offset zero keeps its own level instead of
7580    // being merged into the function scope.
7581    let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
7582    for block in &state.blocks {
7583        if !levels.contains(&block.key) {
7584            levels.push(block.key);
7585        }
7586    }
7587    let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
7588    let parent_level = |level: usize| -> usize {
7589        if level == 0 {
7590            return 0;
7591        }
7592        let key = levels[level];
7593        let parent = state
7594            .blocks
7595            .iter()
7596            .find(|b| b.key == key)
7597            .map(|b| b.parent)
7598            .unwrap_or(FUNCTION_SCOPE);
7599        level_of(parent)
7600    };
7601
7602    // Own bindings per level, in declaration order.
7603    let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
7604    let keys: Vec<u64> = (0..state.vars.len())
7605        .map(|index| {
7606            state
7607                .var_block
7608                .get(index)
7609                .copied()
7610                .unwrap_or(FUNCTION_SCOPE)
7611        })
7612        .collect();
7613    for (index, key) in keys.into_iter().enumerate() {
7614        // The parameter scope is not a block: it is a level of its own with no parent,
7615        // assigned below. Letting it land in level 0 would chain the body's bindings onto
7616        // it, which the reference does not do — the two environments are siblings.
7617        if key == PARAM_SCOPE {
7618            continue;
7619        }
7620        let level = level_of(key);
7621        state.vars[index].scope_level = level as u32;
7622        // A `catch` parameter is part of the runtime scope chain even though it is
7623        // not lexical: the handler's own bindings chain on to it, which is why the
7624        // reference prints `let y [next:1]` with `e` at 1.
7625        if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
7626        {
7627            own[level].push(index);
7628        }
7629    }
7630
7631    // A scope's chain is its own bindings in reverse declaration order followed
7632    // by the enclosing scope's chain.
7633    let mut head = vec![-1i32; levels.len()];
7634    for level in 0..levels.len() {
7635        let inherited = if level == 0 {
7636            -1
7637        } else {
7638            head[parent_level(level)]
7639        };
7640        let chain: Vec<usize> = own[level].iter().rev().copied().collect();
7641        head[level] = chain.first().map_or(inherited, |first| *first as i32);
7642        for (position, &index) in chain.iter().enumerate() {
7643            let next = chain
7644                .get(position + 1)
7645                .map_or(inherited, |next| *next as i32);
7646            state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
7647        }
7648    }
7649    state.block_heads = head;
7650
7651    // The parameter list is a scope of its own, and it has no parent: the reference pops
7652    // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
7653    // the `-1` a block uses. A level past every real block keeps it out of the walk above
7654    // — nothing but the dump reads it — and the links run newest-to-oldest through the
7655    // bindings themselves, which is the order `set_loc_uninitialized` walks.
7656    let param_level = levels.len() as u32;
7657    let mut previous: Option<usize> = None;
7658    for index in 0..state.vars.len() {
7659        if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
7660        {
7661            continue;
7662        }
7663        state.vars[index].scope_level = param_level;
7664        state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
7665        previous = Some(index);
7666    }
7667}
7668
7669/// This is where names become slots and where the temporal dead zone shows up in
7670/// the instruction stream: a read of a `let`/`const` binding compiles to
7671/// `get_loc_check`, which throws if the binding is still uninitialised.
7672///
7673/// The peephole pass from the reference implementation is applied at the end,
7674/// for the same reason it is applied to resolved bytecode there: the patterns are
7675/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
7676/// resolution. Deleted instructions stay in the list as `None` so that label
7677/// indices remain valid; [`Assembler`] maps them to byte offsets.
7678/// A resolved instruction and the source position it came from.
7679type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
7680
7681/// A resolved instruction paired with its position, which is what `assemble` consumes.
7682type PositionedInsn = (Opcode, Vec<Op>);
7683
7684fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
7685    let current = stack.len() - 1;
7686    // Dead-code elimination, on the symbolic form where labels are still
7687    // instruction indices. A `break` inside a loop leaves the trailing `goto`
7688    // unreachable, and a `return` leaves everything after it unreachable; the
7689    // reference drops both. Doing it here means the emitter never has to think
7690    // about reachability.
7691    strip_empty_gosubs(stack, current);
7692    eliminate_dead_code(stack, current);
7693    let insns = std::mem::take(&mut stack[current].insns);
7694    // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
7695    // `insns`, and every arm below pushes exactly one instruction, so the positions
7696    // stay aligned with `out`.
7697    let positions = std::mem::take(&mut stack[current].insn_pos);
7698    let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
7699    let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
7700    for (index, insn) in insns.iter().enumerate() {
7701        let pos = positions.get(index).copied().flatten();
7702        out_pos.push(pos);
7703        match insn {
7704            Insn::Fixed { op, operands } => {
7705                let operands = operands
7706                    .iter()
7707                    .map(|operand| match operand {
7708                        Op::Atom(atom) => {
7709                            Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
7710                        }
7711                        other => other.clone(),
7712                    })
7713                    .collect();
7714                out.push(Some((*op, operands)));
7715            }
7716            Insn::Var {
7717                action,
7718                name,
7719                block,
7720                in_params,
7721            } => {
7722                // Both reads and writes in the parameter list address the parameter
7723                // scope. That is what puts the list in the temporal dead zone — a read of
7724                // a later parameter is `get_loc_check` on an uninitialised slot — and it
7725                // is also what keeps an assignment made inside a default away from the
7726                // body, which sees a separate environment.
7727                let slot = resolve_slot(stack, current, name, *block, *in_params);
7728                // A store to the name of a named function expression is special: the
7729                // reference drops it in sloppy mode and throws in strict mode, because
7730                // the binding is immutable but only *checked* when the body is strict.
7731                // The same rule applies when the name is reached through a closure:
7732                // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
7733                // the store in the arrow too, not just in the function that owns the
7734                // binding. Reaching the owner means walking the chain of closure
7735                // entries, which is what `self_name_binding` does.
7736                let self_name = matches!(action, VarAction::Put | VarAction::Set)
7737                    .then(|| {
7738                        // A local of this function is the common case and needs no
7739                        // chain walk; only an access that resolves elsewhere can be
7740                        // pointing at an enclosing function's name binding.
7741                        if let Slot::Loc(index) = slot {
7742                            stack[current]
7743                                .vars
7744                                .get(index as usize)
7745                                .filter(|var| var.kind == VarKind::FunctionName)
7746                                .map(|var| var.is_const)
7747                        } else {
7748                            self_name_binding(stack, current, name, *block)
7749                        }
7750                    })
7751                    .flatten();
7752                if let Some(is_const) = self_name {
7753                    out.push(Some(if is_const {
7754                        (
7755                            Opcode::ThrowError,
7756                            vec![
7757                                Op::AtomId(intern_atom(&mut stack[current], name)),
7758                                Op::Int(0),
7759                            ],
7760                        )
7761                    } else {
7762                        (Opcode::Drop, Vec::new())
7763                    }));
7764                    continue;
7765                }
7766                out.push(Some(variable_instruction(stack, current, *action, slot)));
7767            }
7768            Insn::CloseCaptured { name, block } => {
7769                // The block matters: a loop variable is scoped to the `for` head's own
7770                // block, so resolving it against block 0 would miss it entirely and
7771                // silently emit nothing.
7772                let slot = resolve_slot(stack, current, name, *block, false);
7773                // Only a local with a reference cell has anything to close. A global
7774                // or a never-captured local resolves to no instruction at all, which
7775                // keeps the bytecode identical to the reference's.
7776                if let Slot::Loc(index) = slot
7777                    && stack[current]
7778                        .vars
7779                        .get(index as usize)
7780                        .is_some_and(|v| v.is_captured)
7781                {
7782                    out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
7783                } else {
7784                    out.push(None);
7785                }
7786            }
7787            Insn::DeleteVar { name } => {
7788                // A binding — a local, an argument, or a declared global — cannot be
7789                // deleted, and the reference encodes that as a constant `push_false`.
7790                // Only an implicit global needs the runtime lookup.
7791                if matches!(
7792                    resolve_slot(stack, current, name, 0, false),
7793                    Slot::Global(_)
7794                ) {
7795                    let atom = intern_atom(&mut stack[current], name);
7796                    out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
7797                } else {
7798                    out.push(Some((Opcode::PushFalse, Vec::new())));
7799                }
7800            }
7801            Insn::Dead => out.push(None),
7802        }
7803    }
7804    // Which label (if any) sits on each instruction, so the jump patterns can
7805    // tell whether they would cross a jump target.
7806    let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
7807    for (id, placed) in stack[current].labels.iter().enumerate() {
7808        if let Some(index) = *placed
7809            && index < label_at.len()
7810            && label_at[index].is_none()
7811        {
7812            label_at[index] = Some(id as u32);
7813        }
7814    }
7815    if std::env::var_os("QJS_DEBUG").is_some() {
7816        eprintln!("--- peephole entry ---");
7817        for (i, e) in out.iter().enumerate() {
7818            eprintln!("{i}: {e:?}");
7819        }
7820        eprintln!("label_at: {label_at:?}");
7821    }
7822    peephole(&mut out, &label_at, &stack[current].labels);
7823    (out, out_pos)
7824}
7825
7826/// Find where `name` lives, capturing it in an enclosing function when needed.
7827///
7828/// The search runs outward through the enclosing functions' states, which are
7829/// still on the compiler stack while a nested function is resolved. Finding the
7830/// name in an enclosing function is what creates a closure reference, and every
7831/// function in between has to forward it — a function can only reach its own
7832/// parent's frame.
7833///
7834/// A name declared nowhere is a global. The reference does *not* look it up by
7835/// name from the inner function: the top-level function gets one `[global]`
7836/// entry and every nested function gets a `[global_ref<n>]` pointing at its
7837/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
7838/// rather than `[global]`.
7839/// The lexical blocks enclosing `block`, innermost first.
7840fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
7841    let mut chain = Vec::new();
7842    let mut current = Some(block);
7843    while let Some(key) = current {
7844        // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
7845        // explicitly (rather than on "no block with this key") is what keeps a block
7846        // that happens to sit at offset zero from being mistaken for the terminator.
7847        if key == NO_PARENT || chain.contains(&key) {
7848            break;
7849        }
7850        chain.push(key);
7851        current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
7852    }
7853    chain
7854}
7855
7856/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
7857///
7858/// The binding may be several functions away: an arrow nested in `function myfunc`
7859/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
7860/// means following `Ref` entries down and then reading the owning function's var table.
7861fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
7862    let state = stack.get(current)?;
7863    // A parameter shadows everything and is never a function-expression name.
7864    if state.args.iter().any(|arg| arg.name == name) {
7865        return None;
7866    }
7867    // A local of this very function: the answer is in its var table.
7868    if let Some(index) = local_slot_index(state, name, block) {
7869        let var = state.vars.get(index)?;
7870        return (var.kind == VarKind::FunctionName).then_some(var.is_const);
7871    }
7872    // Otherwise the name lives further out, and the closure entry says how to get
7873    // there. `Local` names the owner's slot directly; `Ref` names the next level's
7874    // closure entry, so the walk continues downwards.
7875    let mut level = current;
7876    let mut index = state
7877        .closure_vars
7878        .iter()
7879        .position(|closure| closure.name == name)?;
7880    loop {
7881        let state = stack.get(level)?;
7882        let closure = state.closure_vars.get(index)?;
7883        match closure.closure_type {
7884            ClosureType::Local => {
7885                let owner = stack.get(level.checked_sub(1)?)?;
7886                let var = owner.vars.get(closure.var_idx as usize)?;
7887                return (var.kind == VarKind::FunctionName).then_some(var.is_const);
7888            }
7889            ClosureType::Arg => return None,
7890            ClosureType::Ref => {
7891                level -= 1;
7892                index = closure.var_idx as usize;
7893            }
7894            // A global is never a function-expression name.
7895            ClosureType::Global
7896            | ClosureType::GlobalDecl
7897            | ClosureType::GlobalRef
7898            | ClosureType::ModuleDecl
7899            | ClosureType::ModuleImport => return None,
7900        }
7901    }
7902}
7903
7904/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
7905fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
7906    block_chain(state, block).into_iter().find_map(|scope| {
7907        state.vars.iter().enumerate().find_map(|(index, var)| {
7908            (var.name == name && state.var_block.get(index).copied() == Some(scope))
7909                .then_some(index)
7910        })
7911    })
7912}
7913
7914/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
7915fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
7916    if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
7917        var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
7918    }) {
7919        return index as u32;
7920    }
7921    state.var_block.push(PARAM_SCOPE);
7922    state.vars.push(VarDef::var(name));
7923    state.vars.len() as u32 - 1
7924}
7925
7926/// The name a parameter binds straight from its argument slot, if it has one.
7927///
7928/// A plain name does — with or without a default, and with or without `...`. Everything
7929/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
7930/// reference names the argument in the first case and leaves it `<null>` in the second,
7931/// so both the dump and the closures that capture the argument depend on this.
7932fn simple_parameter(param: &Pattern) -> Option<&Ident> {
7933    match &param.kind {
7934        PatternKind::Ident(name) => Some(name),
7935        PatternKind::Assign { target, .. } => match &target.kind {
7936            PatternKind::Ident(name) => Some(name),
7937            _ => None,
7938        },
7939        PatternKind::Rest(inner) => match &inner.kind {
7940            PatternKind::Ident(name) => Some(name),
7941            _ => None,
7942        },
7943        _ => None,
7944    }
7945}
7946
7947/// The pattern a parameter list has to unpick, if `index` is one of them.
7948fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
7949    prologue
7950        .iter()
7951        .find(|(at, _)| *at == index)
7952        .map(|(_, pattern)| pattern)
7953}
7954
7955fn pattern_has_default(pattern: &Pattern) -> bool {
7956    match &pattern.kind {
7957        PatternKind::Assign { .. } => true,
7958        PatternKind::Rest(inner) => pattern_has_default(inner),
7959        PatternKind::Array { elements, rest } => {
7960            elements.iter().flatten().any(element_has_default)
7961                || rest.as_deref().is_some_and(rest_has_default)
7962        }
7963        PatternKind::Object { properties, rest } => {
7964            properties.iter().flatten().any(element_has_default)
7965                || rest.as_deref().is_some_and(rest_has_default)
7966        }
7967        _ => false,
7968    }
7969}
7970
7971fn element_has_default(element: &PatternElement) -> bool {
7972    match element {
7973        PatternElement::Pattern(pattern) => pattern_has_default(pattern),
7974        PatternElement::Property { value, .. } => pattern_has_default(value),
7975    }
7976}
7977
7978fn rest_has_default(rest: &RestElement) -> bool {
7979    match rest {
7980        RestElement::Pattern(pattern) => pattern_has_default(pattern),
7981        RestElement::Member(_) => false,
7982    }
7983}
7984
7985/// Whether a function-scope binding is visible to the parameter list.
7986///
7987/// The parameter list runs before the body, so the body's `var`s and function
7988/// declarations do not exist yet — a name that only the body declares has to resolve
7989/// outward instead. What *does* exist by then is the compiler's own prologue: the
7990/// self-name of a named function expression (bound by `special_object 2` before anything
7991/// else), `this` and `new.target`. Those stay visible, which is what makes
7992/// `function f(a = this)` and `var f = function f(a = f)` work.
7993///
7994/// `arguments` is handled separately, as a binding of the parameter scope itself: with
7995/// parameter expressions the reference creates two of them, and the one the parameter
7996/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
7997fn visible_in_params(var: &VarDef) -> bool {
7998    var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
7999}
8000
8001fn resolve_slot(
8002    stack: &mut [FnState],
8003    current: usize,
8004    name: &str,
8005    block: u64,
8006    in_params: bool,
8007) -> Slot {
8008    // The parameter list's own bindings. They are consulted first because they shadow
8009    // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
8010    // `a` in the parameter scope, so a closure made there reads the parameter even after
8011    // the body assigns to its own `a`.
8012    if in_params
8013        && let Some(index) = stack[current]
8014            .vars
8015            .iter()
8016            .enumerate()
8017            .position(|(index, var)| {
8018                var.name == name
8019                    && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
8020            })
8021    {
8022        return Slot::Loc(index as u32);
8023    }
8024    // A name can be bound more than once: two `catch` parameters in nested
8025    // handlers are two slots. The binding that wins is the one whose scope encloses
8026    // the access, and among those the innermost — so the blocks are walked outward
8027    // and the first binding found on the way is the one that counts. A binding in
8028    // no block (`var`) is reachable from anywhere, which is why the function scope
8029    // is the end of the walk.
8030    //
8031    // The block walk comes *before* the argument slots, because a block may shadow a
8032    // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
8033    // slot is only the answer once nothing nearer claims the name.
8034    let chain = block_chain(&stack[current], block);
8035    for scope in &chain {
8036        let found = stack[current]
8037            .vars
8038            .iter()
8039            .enumerate()
8040            .find(|(index, var)| {
8041                var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
8042            })
8043            .map(|(index, _)| index);
8044        if let Some(index) = found {
8045            return Slot::Loc(index as u32);
8046        }
8047    }
8048    // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
8049    // its own slot, and `var` of the same name in the body is the same binding.
8050    if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
8051        return Slot::Arg(index as u32);
8052    }
8053    // Function-scope bindings — `var` and function declarations — are recorded with
8054    // the sentinel block `0`, which no real scope uses, so the walk above cannot see
8055    // them. They are reachable from anywhere in the function, which is exactly what
8056    // the sentinel means.
8057    //
8058    // This pass is *only* for those. A lexical binding has to be found through the
8059    // chain or not at all, and looking a name up without its block is precisely how
8060    // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
8061    // block leaked out of it.
8062    let function_scoped = stack[current]
8063        .vars
8064        .iter()
8065        .enumerate()
8066        .find(|(index, var)| {
8067            var.name == name
8068                && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
8069                && (!in_params || visible_in_params(var))
8070        })
8071        .map(|(index, _)| index);
8072    if let Some(index) = function_scoped {
8073        return Slot::Loc(index as u32);
8074    }
8075    if let Some(index) = stack[current]
8076        .closure_vars
8077        .iter()
8078        .position(|c| c.name == name)
8079    {
8080        return slot_for_closure(&stack[current].closure_vars[index], index as u32);
8081    }
8082
8083    for owner in (0..current).rev() {
8084        // The nested function was created inside one of this frame's blocks, and the
8085        // outermost visible binding is the innermost block on that chain — not whatever
8086        // comes first in the variable table. `function f(){ class S{} }` has two `S`
8087        // bindings: the `let S` inside `f` and the `const S` inside the class body, and
8088        // the class body is the one a method may see.
8089        let entry = stack
8090            .get(owner + 1)
8091            .map(|s| s.created_in_block)
8092            .unwrap_or(0);
8093        let lexical = block_chain(&stack[owner], entry)
8094            .into_iter()
8095            .find_map(|scope| {
8096                stack[owner]
8097                    .vars
8098                    .iter()
8099                    .enumerate()
8100                    .find(|(index, var)| {
8101                        var.name == name
8102                            && stack[owner].var_block.get(*index).copied() == Some(scope)
8103                    })
8104                    .map(|(index, _)| index)
8105            });
8106        // A function born in a parameter list sees that list's bindings, not the body's:
8107        // the parameter scope is the environment it was created in.
8108        let in_param_scope = stack
8109            .get(owner + 1)
8110            .is_some_and(|child| child.created_in_params)
8111            .then(|| {
8112                stack[owner]
8113                    .vars
8114                    .iter()
8115                    .enumerate()
8116                    .position(|(index, var)| {
8117                        var.name == name
8118                            && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
8119                    })
8120            })
8121            .flatten();
8122        let found = if let Some(index) = in_param_scope {
8123            let var = &stack[owner].vars[index];
8124            Some(Found::Local(
8125                ClosureType::Local,
8126                index as u32,
8127                var.is_const,
8128                var.needs_check(),
8129            ))
8130        } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
8131            Some(Found::Local(ClosureType::Arg, index as u32, false, false))
8132        } else if let Some(index) = lexical {
8133            let var = &stack[owner].vars[index];
8134            Some(Found::Local(
8135                ClosureType::Local,
8136                index as u32,
8137                var.is_const,
8138                var.needs_check(),
8139            ))
8140        } else if let Some(index) = stack[owner]
8141            .vars
8142            .iter()
8143            .enumerate()
8144            .find_map(|(index, var)| {
8145                // A function created inside a parameter list must not see the body of the
8146                // function it was born in; see [`FnState::created_in_params`].
8147                let hidden = stack
8148                    .get(owner + 1)
8149                    .is_some_and(|child| child.created_in_params);
8150                (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
8151            })
8152        {
8153            let var = &stack[owner].vars[index];
8154            Some(Found::Local(
8155                ClosureType::Local,
8156                index as u32,
8157                var.is_const,
8158                var.needs_check(),
8159            ))
8160        } else if stack[owner].self_name.as_deref() == Some(name) {
8161            // A named function expression's own name. The reference declares it here,
8162            // on the first lookup that fails, rather than up front — and that is what
8163            // makes it reachable from a *nested* function: the nested lookup is what
8164            // walks out and creates the binding. A direct reference in the body is
8165            // caught the same way, which is why `provide_self_name` only has to add
8166            // the prologue.
8167            let strict = stack[owner].strict;
8168            stack[owner].var_block.push(FUNCTION_SCOPE);
8169            stack[owner].vars.push(VarDef {
8170                kind: VarKind::FunctionName,
8171                // In strict mode the name is immutable, so a store raises; sloppy
8172                // mode drops the store instead (see `variable_instruction`).
8173                is_const: strict,
8174                ..VarDef::var(name)
8175            });
8176            let index = stack[owner].vars.len() as u32 - 1;
8177            Some(Found::Local(ClosureType::Local, index, strict, false))
8178        } else if let Some(index) = stack[owner]
8179            .closure_vars
8180            .iter()
8181            .position(|c| c.name == name)
8182        {
8183            let closure = &stack[owner].closure_vars[index];
8184            Some(match closure.closure_type {
8185                // `GlobalRef` belongs here too: it is a *global* reached through this
8186                // frame's reference table, so treating it as a `Ref` to a local cell makes
8187                // the reader look for a cell no frame ever fills. That is how a second
8188                // function using `eval` in its parameter list read `undefined` after a
8189                // sibling had already made `eval` a closure entry.
8190                ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
8191                    Found::Global(index as u32)
8192                }
8193                // A module variable is a cell in the *module's* environment, which is
8194                // the module body's parent as far as a nested function is concerned — so
8195                // it is captured as a plain reference, not looked up as a global.
8196                ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
8197                    ClosureType::Ref,
8198                    index as u32,
8199                    closure.is_const,
8200                    closure.is_lexical,
8201                ),
8202                _ => Found::Local(
8203                    ClosureType::Ref,
8204                    index as u32,
8205                    closure.is_const,
8206                    closure.is_lexical,
8207                ),
8208            })
8209        } else {
8210            None
8211        };
8212        let Some(found) = found else { continue };
8213
8214        let (is_const, is_lexical) = match found {
8215            Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
8216            Found::Global(_) => (false, false),
8217        };
8218        // Mark the owner's binding as captured so it moves into a reference cell.
8219        if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
8220            let slot = match found {
8221                Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
8222                _ => &mut stack[owner].vars[index as usize],
8223            };
8224            slot.is_captured = true;
8225        }
8226        // Forward the reference through every function in between.
8227        let mut previous = match found {
8228            Found::Local(kind, index, _, _) => (kind, index),
8229            Found::Global(index) => (ClosureType::Global, index),
8230        };
8231        for level in owner + 1..=current {
8232            let kind = match (previous.0, level) {
8233                // A global stays a global at *every* level. Without `GlobalRef` in
8234                // this arm the second nested function over the same global got a
8235                // `Ref` to a cell no frame ever held, so the innermost closure read
8236                // `undefined` — which is how a two-deep getter lost its outer
8237                // variable.
8238                (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
8239                    ClosureType::GlobalRef
8240                }
8241                (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
8242                _ => ClosureType::Ref,
8243            };
8244            let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
8245            previous = (kind, index);
8246        }
8247        let index = previous.1;
8248        return slot_for_closure(&stack[current].closure_vars[index as usize], index);
8249    }
8250
8251    // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
8252    // creating a property. The top-level function holds the entry.
8253    let mut previous = (
8254        ClosureType::Global,
8255        ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
8256    );
8257    for level in 1..=current {
8258        let index = ensure_closure(
8259            stack,
8260            level,
8261            name,
8262            false,
8263            false,
8264            ClosureType::GlobalRef,
8265            previous.1,
8266        );
8267        previous = (ClosureType::GlobalRef, index);
8268    }
8269    Slot::Global(previous.1)
8270}
8271
8272/// What an outward search turned up.
8273#[derive(Debug, Clone, Copy)]
8274enum Found {
8275    /// A binding in an enclosing function, reachable through a closure of this
8276    /// type, with its const/lexical flags.
8277    Local(ClosureType, u32, bool, bool),
8278    /// A global, reached through the enclosing function's closure entry.
8279    Global(u32),
8280}
8281
8282/// Add a closure entry to `level` if it is not there yet.
8283fn ensure_closure(
8284    stack: &mut [FnState],
8285    level: usize,
8286    name: &str,
8287    is_const: bool,
8288    is_lexical: bool,
8289    closure_type: ClosureType,
8290    var_idx: u32,
8291) -> u32 {
8292    if let Some(index) = stack[level]
8293        .closure_vars
8294        .iter()
8295        .position(|c| c.name == name)
8296    {
8297        return index as u32;
8298    }
8299    stack[level].closure_vars.push(ClosureVar {
8300        name: name.to_string(),
8301        is_const,
8302        is_lexical,
8303        closure_type,
8304        var_idx: var_idx as u16,
8305    });
8306    stack[level].closure_vars.len() as u32 - 1
8307}
8308
8309fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
8310    match closure.closure_type {
8311        // A `global_ref` only says *how* the binding is found (through the
8312        // parent's closure table); the access itself is an ordinary global one.
8313        ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
8314        ClosureType::GlobalDecl => Slot::GlobalDecl(index),
8315        // A module variable is a real cell in the module's environment, so it is reached
8316        // exactly like a captured local — the host, not the global object, is what fills
8317        // the slot.
8318        ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
8319        _ => Slot::VarRef(index),
8320    }
8321}
8322
8323/// Pick the opcode for one variable access.
8324///
8325/// The `_check` variants are what enforce the temporal dead zone. They are used
8326/// for every access to a `let`/`const` binding except its own initialisation —
8327/// which is exactly the operation that takes the binding out of the dead zone.
8328fn variable_instruction(
8329    stack: &[FnState],
8330    current: usize,
8331    action: VarAction,
8332    slot: Slot,
8333) -> (Opcode, Vec<Op>) {
8334    let lexical = match slot {
8335        Slot::Loc(index) => stack[current]
8336            .vars
8337            .get(index as usize)
8338            .is_some_and(|v| v.needs_check()),
8339        Slot::VarRef(index) => stack[current]
8340            .closure_vars
8341            .get(index as usize)
8342            .is_some_and(|c| c.is_lexical),
8343        _ => false,
8344    };
8345    let operand = vec![Op::Slot(slot)];
8346    match (action, slot) {
8347        (VarAction::Get, Slot::Loc(index)) => (
8348            if lexical {
8349                Opcode::GetLocCheck
8350            } else {
8351                Opcode::GetLoc
8352            },
8353            vec![Op::Slot(Slot::Loc(index))],
8354        ),
8355        (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
8356        (VarAction::Get, Slot::VarRef(index)) => (
8357            if lexical {
8358                Opcode::GetVarRefCheck
8359            } else {
8360                Opcode::GetVarRef
8361            },
8362            vec![Op::Slot(Slot::VarRef(index))],
8363        ),
8364        (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
8365        (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
8366        (VarAction::GetUndef, Slot::Loc(_)) => (Opcode::GetLoc, operand),
8367        (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
8368        (VarAction::GetUndef, Slot::VarRef(_)) => (Opcode::GetVarRef, operand),
8369        (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8370            (Opcode::GetVarUndef, operand)
8371        }
8372
8373        (VarAction::Put, Slot::Loc(_)) => (
8374            if lexical {
8375                Opcode::PutLocCheck
8376            } else {
8377                Opcode::PutLoc
8378            },
8379            operand,
8380        ),
8381        (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
8382        (VarAction::Put, Slot::VarRef(_)) => (
8383            if lexical {
8384                Opcode::PutVarRefCheck
8385            } else {
8386                Opcode::PutVarRef
8387            },
8388            operand,
8389        ),
8390        (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
8391        (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8392        // Initialisation is what ends the dead zone, so it never checks.
8393        (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8394        (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
8395        // `this` in a derived constructor is always a local, so these cannot happen;
8396        // routing them to the ordinary forms keeps the match total without inventing
8397        // opcodes the reference does not have.
8398        (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
8399        (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8400        (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8401            (Opcode::PutVarInit, operand)
8402        }
8403        (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
8404        (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8405        (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8406            (Opcode::PutVarInit, operand)
8407        }
8408        (VarAction::Set, Slot::Loc(_)) => (
8409            if lexical {
8410                Opcode::SetLocCheck
8411            } else {
8412                Opcode::SetLoc
8413            },
8414            operand,
8415        ),
8416        (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
8417        (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
8418        (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8419        (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8420        (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
8421        (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8422        (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
8423        (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
8424        (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8425        (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
8426        (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8427        (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
8428    }
8429}
8430
8431/// The instruction-rewriting pass.
8432///
8433/// These are the reference implementation's patterns, restricted to the ones the
8434/// constructs this compiler supports can produce. Each entry is a comment on the
8435/// bytecode it removes, because the whole point is that the result is one
8436/// instruction shorter than the literal translation of the AST.
8437fn peephole(
8438    insns: &mut [Option<(Opcode, Vec<Op>)>],
8439    label_at: &[Option<u32>],
8440    placed: &[Option<usize>],
8441) {
8442    fold_dup_patterns(insns, label_at);
8443
8444    // `drop` before `return_undef` is dead: the return discards the whole frame
8445    // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
8446    // consumes its own `drop`; removing the drop first would leave the `dup` and
8447    // produce a `set_` where the reference has a `put_`.
8448    for index in 0..insns.len() {
8449        if opcode_at(insns, index) != Some(Opcode::Drop) {
8450            continue;
8451        }
8452        // Skip over a run of drops, but stop at a jump target: removing code on
8453        // one side of a label would silently retarget the jump.
8454        let mut next = index + 1;
8455        while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
8456            next += 1;
8457        }
8458        if is_label_at(label_at, next) {
8459            continue;
8460        }
8461        if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
8462            for entry in &mut insns[index..next] {
8463                *entry = None;
8464            }
8465        }
8466    }
8467
8468    // The rewrites below all decide against one fixed snapshot, which is what the
8469    // reference sees: `code_match` reads the bytecode buffer as it was on entry to
8470    // the pass, so a rule never observes what an earlier rule removed. Gathering
8471    // every deletion first and applying them together reproduces that.
8472    let snapshot: Vec<Option<Opcode>> = insns
8473        .iter()
8474        .map(|entry| entry.as_ref().map(|(op, _)| *op))
8475        .collect();
8476    // The next instruction that is still there. Holes left by dead-code
8477    // elimination are not instructions, so a rule looks past them.
8478    let next_op = |index: usize| -> Option<usize> {
8479        (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
8480    };
8481
8482    let mut doomed = vec![false; insns.len()];
8483    for index in 0..insns.len() {
8484        // A constant pushed only to be dropped does nothing at all. This is what a
8485        // comma expression with a literal left operand compiles to — `(0, f)()` — and
8486        // the reference removes the pair rather than making the reader step over it.
8487        let constant = matches!(
8488            snapshot[index],
8489            Some(
8490                Opcode::Undefined
8491                    | Opcode::Null
8492                    | Opcode::PushMinus1
8493                    | Opcode::Push0
8494                    | Opcode::Push1
8495                    | Opcode::Push2
8496                    | Opcode::Push3
8497                    | Opcode::Push4
8498                    | Opcode::Push5
8499                    | Opcode::Push6
8500                    | Opcode::Push7
8501                    | Opcode::PushTrue
8502                    | Opcode::PushFalse
8503                    | Opcode::PushI32
8504            )
8505        );
8506        if constant
8507            && let Some(next) = next_op(index)
8508            && snapshot[next] == Some(Opcode::Drop)
8509        {
8510            doomed[index] = true;
8511            doomed[next] = true;
8512        }
8513    }
8514    for (index, entry) in insns.iter_mut().enumerate() {
8515        if doomed[index] {
8516            *entry = None;
8517        }
8518    }
8519
8520    // A conditional whose destination is the very next instruction just pops its
8521    // condition, so it becomes a plain `drop`. This is what an empty `case` clause
8522    // compiles to.
8523    //
8524    // Order matters, and it is the reference's order: this runs *before* the
8525    // folding below, on the instruction the conditional originally had. Folding
8526    // moves a conditional's destination, and the reference never re-examines it
8527    // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
8528    // a conditional even though folding leaves it pointing at the next
8529    // instruction.
8530    for (index, entry) in insns.iter_mut().enumerate() {
8531        let Some((op, operands)) = entry.clone() else {
8532            continue;
8533        };
8534        if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
8535            continue;
8536        }
8537        let Some(id) = label_id(&operands) else {
8538            continue;
8539        };
8540        if placed.get(id as usize).copied().flatten() == Some(index + 1) {
8541            *entry = Some((Opcode::Drop, Vec::new()));
8542        }
8543    }
8544
8545    // A constant condition is decided here rather than at run time.
8546    fold_constant_conditions(insns);
8547    // The conditional folding below is about pairs of *real* branches, so it runs
8548    // before a jump to the next instruction is dropped: `do { … if (c) continue }
8549    // while (t)` puts `continue` exactly on the condition, and the reference inverts
8550    // the branch first and only then notices the jump goes nowhere.
8551    fold_conditional_jumps(insns, label_at, placed);
8552
8553    // A jump whose destination is the very next instruction does nothing, which is
8554    // what constant folding leaves behind for `while (1) { … }`.
8555    remove_jump_to_next(insns, placed);
8556
8557    // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
8558    // a use of the same variable boils down to.
8559    for index in 0..insns.len() {
8560        let Some((put_op, _)) = insns[index].clone() else {
8561            continue;
8562        };
8563        if !is_foldable_put(put_op) {
8564            continue;
8565        }
8566        if is_label_at(label_at, index + 1) {
8567            continue;
8568        }
8569        let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
8570            continue;
8571        };
8572        if get_op != get_form_of(put_op) {
8573            continue;
8574        }
8575        let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
8576        if put_slot.is_none() || put_slot != get_operands.first().cloned() {
8577            continue;
8578        }
8579        insns[index] = Some((set_form_of(put_op), get_operands));
8580        insns[index + 1] = None;
8581    }
8582}
8583
8584/// Drop `gosub`s that call an empty subroutine.
8585///
8586/// A `gosub` whose target starts with `ret` returns immediately, so the reference
8587/// drops the call. This is how `try`/`catch` without a `finally` loses its
8588/// finalizer plumbing: the finalizer block is empty, its first instruction is
8589/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
8590/// [`eliminate_dead_code`] then removes.
8591fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
8592    let state = &stack[current];
8593    let mut targets = Vec::new();
8594    for insn in &state.insns {
8595        if let Insn::Fixed { op, operands } = insn
8596            && *op == Opcode::Gosub
8597            && let Some(id) = label_id(operands)
8598            && let Some(target) = state.labels.get(id as usize).copied().flatten()
8599        {
8600            targets.push(target);
8601        }
8602    }
8603    let empty: Vec<usize> = targets
8604        .into_iter()
8605        .filter(|target| {
8606            stack[current]
8607                .insns
8608                .get(*target)
8609                .map(|insn| {
8610                    matches!(
8611                        insn,
8612                        Insn::Fixed {
8613                            op: Opcode::Ret,
8614                            ..
8615                        }
8616                    )
8617                })
8618                .unwrap_or(false)
8619        })
8620        .collect();
8621    if empty.is_empty() {
8622        return;
8623    }
8624    for insn in stack[current].insns.iter_mut() {
8625        if let Insn::Fixed { op, operands } = insn
8626            && *op == Opcode::Gosub
8627            && let Some(id) = label_id(operands)
8628            && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
8629            && empty.contains(&target)
8630        {
8631            *insn = Insn::Dead;
8632        }
8633    }
8634}
8635
8636/// Replace unreachable instructions with [`Insn::Dead`].
8637fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
8638    let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
8639    for (index, insn) in stack[current].insns.iter_mut().enumerate() {
8640        if !reachable[index] {
8641            *insn = Insn::Dead;
8642        }
8643    }
8644}
8645
8646/// Mark every instruction index reachable from the entry, plus the index one past
8647/// the last instruction.
8648///
8649/// `seen[len]` answers "can control reach the end of this function", and the
8650/// entries before it identify dead code. Both DCE and the implicit-return decision
8651/// read the same result, which keeps them from disagreeing.
8652fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
8653    let mut seen = vec![false; count + 1];
8654    let mut worklist = vec![0usize];
8655    while let Some(index) = worklist.pop() {
8656        if index > count || seen[index] {
8657            continue;
8658        }
8659        seen[index] = true;
8660        if index == count {
8661            continue;
8662        }
8663        let (op, operands) = match &state.insns[index] {
8664            Insn::Fixed { op, operands } => (*op, operands.as_slice()),
8665            // A variable access never transfers control, and a removed
8666            // instruction is only reachable if it is already marked.
8667            Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
8668                worklist.push(index + 1);
8669                continue;
8670            }
8671        };
8672        match op {
8673            // A return, a throw and a `ret` all leave this instruction stream: the
8674            // first two give control to the caller or the handler, and `ret`
8675            // returns to a `gosub` elsewhere.
8676            // A tail call leaves the function too: the callee's result becomes this
8677            // function's result, so nothing after it runs.
8678            Opcode::Return
8679            | Opcode::ReturnUndef
8680            | Opcode::ReturnAsync
8681            | Opcode::TailCall
8682            | Opcode::TailCallMethod
8683            | Opcode::Throw
8684            | Opcode::ThrowError
8685            | Opcode::Ret => {}
8686            // A `catch` records where exceptions from the code that follows go.
8687            // That code is not reachable through normal control flow, but it is
8688            // reachable — through the exception edge — so the walk has to follow
8689            // it, or dead-code elimination would delete every handler.
8690            Opcode::Catch => {
8691                if let Some(target) = placed_label(state, operands) {
8692                    worklist.push(target);
8693                }
8694                worklist.push(index + 1);
8695            }
8696            // A `gosub` calls a subroutine and then continues, so both edges count.
8697            Opcode::Gosub => {
8698                if let Some(target) = placed_label(state, operands) {
8699                    worklist.push(target);
8700                }
8701                worklist.push(index + 1);
8702            }
8703            Opcode::Goto => {
8704                if let Some(target) = placed_label(state, operands) {
8705                    worklist.push(target);
8706                }
8707            }
8708            Opcode::IfTrue | Opcode::IfFalse => {
8709                if let Some(target) = placed_label(state, operands) {
8710                    worklist.push(target);
8711                }
8712                worklist.push(index + 1);
8713            }
8714            _ => worklist.push(index + 1),
8715        }
8716    }
8717    seen
8718}
8719
8720/// The instruction index a jump operand points at, resolved through the label
8721/// placement table.
8722fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
8723    let id = label_id(operands)?;
8724    state.labels.get(id as usize).copied().flatten()
8725}
8726
8727/// The label an instruction refers to.
8728fn label_id(operands: &[Op]) -> Option<u32> {
8729    operands.iter().find_map(|operand| match operand {
8730        Op::Label(label) => Some(label.0),
8731        _ => None,
8732    })
8733}
8734
8735/// Turn `if_false L; goto M; L:` into `if_true M`.
8736///
8737/// A conditional whose alternate branch is an unconditional jump needs one jump,
8738/// not two. This is the shape `if (c) break;` produces, so folding it removes an
8739/// instruction and a label from every conditional `break`.
8740/// The boolean a constant-push instruction produces, or `None` if it is not one.
8741///
8742/// Only the operators whose truthiness is decided by the opcode are covered; a
8743/// constant that needs the constant pool (a string) is left alone, because reading it
8744/// would mean threading the pool through the peephole for a case the reference also
8745/// skips.
8746fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
8747    match op {
8748        // `push_0` returns -1 for zero, `push_1` 1, and so on.
8749        Opcode::PushMinus1 => Some(true),
8750        Opcode::Push0 => Some(false),
8751        Opcode::Push1
8752        | Opcode::Push2
8753        | Opcode::Push3
8754        | Opcode::Push4
8755        | Opcode::Push5
8756        | Opcode::Push6
8757        | Opcode::Push7 => Some(true),
8758        Opcode::PushTrue => Some(true),
8759        Opcode::PushFalse => Some(false),
8760        Opcode::Undefined | Opcode::Null => Some(false),
8761        Opcode::PushI32 => match operands.first() {
8762            Some(Op::Int(value)) => Some(*value != 0),
8763            _ => None,
8764        },
8765        _ => None,
8766    }
8767}
8768
8769/// Fold a branch on a constant condition.
8770///
8771/// `if (0) a() else b()` must not test anything at run time, and the reference
8772/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
8773/// which is why the bytecode for a `while (1)` loop has no condition at all.
8774///
8775/// Two instructions become one, so the slot the test occupied is left empty rather
8776/// than shifting everything after it: labels have already been resolved to indices.
8777fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>]) {
8778    for index in 0..insns.len() {
8779        let Some((push_op, push_operands)) = insns[index].clone() else {
8780            continue;
8781        };
8782        let Some(truth) = constant_truth(push_op, &push_operands) else {
8783            continue;
8784        };
8785        let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
8786            continue;
8787        };
8788        let (destination, taken) = match branch_op {
8789            Opcode::IfTrue => (branch_operands.first().cloned(), truth),
8790            Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
8791            _ => continue,
8792        };
8793        let Some(destination) = destination else {
8794            continue;
8795        };
8796        insns[index] = if taken {
8797            // The branch is always taken, so it becomes an unconditional jump.
8798            Some((Opcode::Goto, vec![destination]))
8799        } else {
8800            // The branch never runs: both instructions disappear and control falls
8801            // through to what came after.
8802            None
8803        };
8804        insns[index + 1] = None;
8805    }
8806}
8807
8808/// Remove a jump whose destination is the instruction right after it.
8809///
8810/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
8811/// its test into nothing, and the loop-end jump then points at the following
8812/// instruction. The reference drops them, so `stack_size` and the listing agree.
8813fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
8814    for index in 0..insns.len() {
8815        let Some((op, operands)) = insns[index].clone() else {
8816            continue;
8817        };
8818        if !is_goto(op) {
8819            continue;
8820        }
8821        let Some(id) = label_id(&operands) else {
8822            continue;
8823        };
8824        // The next instruction that still exists, which is what "the instruction
8825        // after this jump" means once earlier folds have punched holes.
8826        let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
8827        if placed.get(id as usize).copied().flatten() == next {
8828            insns[index] = None;
8829        }
8830    }
8831}
8832
8833fn fold_conditional_jumps(
8834    insns: &mut [Option<(Opcode, Vec<Op>)>],
8835    label_at: &[Option<u32>],
8836    placed: &[Option<usize>],
8837) {
8838    for index in 0..insns.len() {
8839        let Some((op, operands)) = insns[index].clone() else {
8840            continue;
8841        };
8842        let inverted = match op {
8843            Opcode::IfFalse => Opcode::IfTrue,
8844            Opcode::IfTrue => Opcode::IfFalse,
8845            _ => continue,
8846        };
8847        // Next must be an unconditional jump that is not itself a target, and the
8848        // instruction after it must be exactly where the conditional goes.
8849        let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
8850            continue;
8851        };
8852        if !is_goto(next_op) || is_label_at(label_at, index + 1) {
8853            continue;
8854        }
8855        // The conditional must land on the instruction *after* the jump. Several
8856        // labels can share a position, so this asks where *this* label was put
8857        // rather than what label happens to sit there.
8858        let Some(taken) = label_id(&operands) else {
8859            continue;
8860        };
8861        if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
8862            continue;
8863        }
8864        let Some(destination) = next_operands.first().cloned() else {
8865            continue;
8866        };
8867        insns[index] = Some((inverted, vec![destination]));
8868        insns[index + 1] = None;
8869    }
8870}
8871
8872/// Whether a jump target is placed at this instruction index.
8873fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
8874    label_at.get(index).copied().flatten().is_some()
8875}
8876
8877fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
8878    // `dup put_x(n)` -> `set_x(n)`
8879    // `dup put_x(n) drop` -> `put_x(n)`
8880    // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
8881    for index in 0..insns.len() {
8882        if opcode_at(insns, index) != Some(Opcode::Dup) {
8883            continue;
8884        }
8885        if is_label_at(label_at, index + 1) {
8886            continue;
8887        }
8888        let Some((put_op, put_operands)) = insns[index + 1].clone() else {
8889            continue;
8890        };
8891        if !is_foldable_put(put_op) {
8892            continue;
8893        }
8894        let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
8895            continue;
8896        };
8897        let mut new_op = set_form_of(put_op);
8898        let mut end = index + 2;
8899        if is_label_at(label_at, end) {
8900            // The `put` has to stay as it is; only the `dup` can be folded.
8901            insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
8902            insns[index + 1] = None;
8903            continue;
8904        }
8905        // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
8906        // Deleting it moves the label's target onto whatever follows, and the code that
8907        // jumps there arrives with a different stack than the fall-through path: that is
8908        // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
8909        // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
8910        // an empty stack. The store had already consumed the value it was supposed to
8911        // leave behind.
8912        if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
8913            new_op = put_op;
8914            end += 1;
8915            if opcode_at(insns, end) == Some(get_form_of(put_op))
8916                && !is_label_at(label_at, end)
8917                && insns[end]
8918                    .as_ref()
8919                    .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
8920            {
8921                new_op = set_form_of(put_op);
8922                end += 1;
8923            }
8924        }
8925        insns[index] = Some((new_op, vec![Op::Slot(slot)]));
8926        for entry in &mut insns[index + 1..end] {
8927            *entry = None;
8928        }
8929    }
8930}
8931
8932fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
8933    insns
8934        .get(index)
8935        .and_then(|entry| entry.as_ref())
8936        .map(|(op, _)| *op)
8937}
8938
8939/// The four `put_` families that have a `set_` twin. Deliberately not including
8940/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
8941/// these, and folding the others would produce instructions that do not exist.
8942fn is_foldable_put(op: Opcode) -> bool {
8943    matches!(
8944        op,
8945        Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
8946    )
8947}
8948
8949fn set_form_of(op: Opcode) -> Opcode {
8950    match op {
8951        Opcode::PutLoc => Opcode::SetLoc,
8952        Opcode::PutLocCheck => Opcode::SetLocCheck,
8953        Opcode::PutArg => Opcode::SetArg,
8954        Opcode::PutVarRef => Opcode::SetVarRef,
8955        other => other,
8956    }
8957}
8958
8959fn get_form_of(op: Opcode) -> Opcode {
8960    match op {
8961        Opcode::PutLoc => Opcode::GetLoc,
8962        Opcode::PutLocCheck => Opcode::GetLocCheck,
8963        Opcode::PutArg => Opcode::GetArg,
8964        Opcode::PutVarRef => Opcode::GetVarRef,
8965        other => other,
8966    }
8967}
8968
8969/// Atom interning, per function.
8970///
8971/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
8972/// identifiers, so the array-index rule applies here rather than at the handful of
8973/// call sites that build property keys.
8974fn intern_atom(state: &mut FnState, name: &str) -> u32 {
8975    intern_atom_value(state, Atom::from_text(name))
8976}
8977
8978/// [`intern_atom`] for an operand that is already an [`Atom`].
8979///
8980/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
8981/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
8982/// would have looked up.
8983fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
8984    if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
8985        return index as u32;
8986    }
8987    state.atoms.push(atom);
8988    state.atoms.len() as u32 - 1
8989}
8990
8991fn binary_opcode(op: BinaryOp) -> Opcode {
8992    match op {
8993        BinaryOp::Add => Opcode::Add,
8994        BinaryOp::Sub => Opcode::Sub,
8995        BinaryOp::Mul => Opcode::Mul,
8996        BinaryOp::Div => Opcode::Div,
8997        BinaryOp::Mod => Opcode::Mod,
8998        BinaryOp::Pow => Opcode::Pow,
8999        BinaryOp::BitOr => Opcode::Or,
9000        BinaryOp::BitXor => Opcode::Xor,
9001        BinaryOp::BitAnd => Opcode::And,
9002        BinaryOp::Shl => Opcode::Shl,
9003        BinaryOp::Shr => Opcode::Sar,
9004        BinaryOp::UShr => Opcode::Shr,
9005        BinaryOp::Lt => Opcode::Lt,
9006        BinaryOp::LtEq => Opcode::Lte,
9007        BinaryOp::Gt => Opcode::Gt,
9008        BinaryOp::GtEq => Opcode::Gte,
9009        BinaryOp::Eq => Opcode::Eq,
9010        BinaryOp::NotEq => Opcode::Neq,
9011        BinaryOp::StrictEq => Opcode::StrictEq,
9012        BinaryOp::StrictNotEq => Opcode::StrictNeq,
9013        BinaryOp::In => Opcode::In,
9014        BinaryOp::Instanceof => Opcode::Instanceof,
9015    }
9016}
9017
9018fn compound_opcode(op: AssignOp) -> Opcode {
9019    match op {
9020        AssignOp::Add => Opcode::Add,
9021        AssignOp::Sub => Opcode::Sub,
9022        AssignOp::Mul => Opcode::Mul,
9023        AssignOp::Div => Opcode::Div,
9024        AssignOp::Mod => Opcode::Mod,
9025        AssignOp::Pow => Opcode::Pow,
9026        AssignOp::Shl => Opcode::Shl,
9027        AssignOp::Shr => Opcode::Sar,
9028        AssignOp::UShr => Opcode::Shr,
9029        AssignOp::BitOr => Opcode::Or,
9030        AssignOp::BitXor => Opcode::Xor,
9031        AssignOp::BitAnd => Opcode::And,
9032        AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
9033    }
9034}
9035
9036/// Encode the resolved instruction stream, choosing short forms where possible.
9037///
9038/// The peephole pass leaves holes in the instruction list so that label indices
9039/// stay valid. A label names an *instruction index*, and an index that was
9040/// deleted has to resolve to the next surviving instruction, which is what
9041/// [`resolve_label`] does before the byte offsets are known.
9042fn assemble(
9043    insns: &mut [Option<(Opcode, Vec<Op>)>],
9044    insn_pos: &[Option<Position>],
9045    state: &mut FnState,
9046) -> (Vec<u8>, u32, Vec<LineCol>) {
9047    // Compaction: surviving instructions in order, plus the index mapping.
9048    //
9049    // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
9050    // point below where instructions are removed — otherwise a stack trace would point
9051    // at the wrong source line as soon as dead-code elimination kicked in.
9052    let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
9053    let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
9054    let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
9055    for (original, entry) in insns.iter_mut().enumerate() {
9056        if let Some((op, operands)) = entry.take() {
9057            original_to_kept[original] = Some(kept.len());
9058            kept.push((op, operands));
9059            spans.push(insn_pos.get(original).copied().flatten());
9060        }
9061    }
9062
9063    if std::env::var_os("QJS_DEBUG").is_some() {
9064        eprintln!("--- assemble entry --- {kept:?}");
9065    }
9066    // How many labels are real, as opposed to the per-instruction ones allocated
9067    // just below. Only a real label marks a spot in the source program.
9068    let real_labels = state.labels.len();
9069
9070    // Give every surviving instruction a label of its own. Jump cleanup below
9071    // redirects jumps to arbitrary instructions, and a jump target has to be a
9072    // label; pre-allocating one per index means a redirect never has to invent
9073    // anything.
9074    let existing = state.labels.len();
9075    let base = kept.len();
9076    let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
9077    for offset in 0..=kept.len() {
9078        state.labels.push(Some(0));
9079        index_label.push(Label((existing + offset) as u32));
9080    }
9081    // Point each pre-allocated label at its instruction, reusing the count from
9082    // `original_to_kept` so the mapping survives compaction.
9083    let place_index_labels = |state: &mut FnState,
9084                              original_to_kept: &[Option<usize>],
9085                              kept_len: usize,
9086                              index_label: &[Label]| {
9087        for (original, mapped) in original_to_kept.iter().enumerate() {
9088            if let Some(kept_index) = mapped {
9089                let label = index_label[*kept_index].0 as usize;
9090                state.labels[label] = Some(original);
9091            }
9092        }
9093        state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
9094    };
9095    place_index_labels(state, &original_to_kept, base, &index_label);
9096
9097    // Resolve every label to a kept index once; the placement table maps labels
9098    // to original indices, so a second hop lands in kept space.
9099    let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
9100    for (id, placed) in state.labels.iter().enumerate() {
9101        let Some(original) = placed else { continue };
9102        label_kept[id] = if *original == usize::MAX {
9103            Some(base)
9104        } else {
9105            (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
9106        };
9107    }
9108
9109    // Code after an unconditional transfer is unreachable, and the reference drops it
9110    // as it walks past the transfer — the `skip_dead_code` in its first pass. It
9111    // scans forward until it finds a label something still jumps to, so a run of
9112    // dead instructions between a `throw` and the next live target disappears.
9113    //
9114    // The scan repeats because dropping a jump lowers the reference count of the
9115    // label it pointed at, which can strand what follows. Only a real label keeps an
9116    // instruction alive here; the per-instruction labels allocated above belong to
9117    // this pass, not to the program.
9118    loop {
9119        let mut references = vec![false; kept.len() + 1];
9120        for (_, operands) in &kept {
9121            if let Some(target) = target_kept_index(operands, &label_kept)
9122                && target < references.len()
9123            {
9124                references[target] = true;
9125            }
9126        }
9127        let mut doomed = vec![false; kept.len()];
9128        let mut any = false;
9129        for (index, (op, _)) in kept.iter().enumerate() {
9130            if !is_transfer(*op) {
9131                continue;
9132            }
9133            for next in index + 1..kept.len() {
9134                if references[next] {
9135                    break;
9136                }
9137                doomed[next] = true;
9138                any = true;
9139            }
9140        }
9141        if !any {
9142            break;
9143        }
9144        (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
9145    }
9146
9147    // A label that lands on an unconditional jump stands for wherever that jump
9148    // goes, so retarget it once and every jump to the label follows for free.
9149    // This is what makes `continue` in a `for` head reach the loop top instead of
9150    // stopping at the update's trailing jump.
9151    let folded: Vec<Option<usize>> = label_kept
9152        .iter()
9153        .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
9154        .collect();
9155    label_kept = folded;
9156
9157    // Jump cleanup, in compacted index space. Two rewrites the reference also
9158    // applies while it resolves labels:
9159    //   * a jump whose destination is the very next instruction does nothing;
9160    //   * a jump to a jump is redirected to its final destination.
9161    // The second can expose the first, so this repeats until it settles.
9162    loop {
9163        let mut delete = vec![false; kept.len()];
9164        let mut changed = false;
9165        for index in 0..kept.len() {
9166            let (op, operands) = &kept[index];
9167            if !is_goto(*op) {
9168                continue;
9169            }
9170            let Some(immediate) = target_kept_index(operands, &label_kept) else {
9171                continue;
9172            };
9173            let target = follow_jump_chain(&kept, &label_kept, immediate);
9174            if target == index + 1 {
9175                delete[index] = true;
9176                changed = true;
9177            } else if matches!(
9178                kept.get(target).map(|(op, _)| *op),
9179                Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
9180            ) {
9181                // Jumping straight to a return or throw is the same as doing it
9182                // here, so the jump becomes that instruction.
9183                kept[index] = (kept[target].0, Vec::new());
9184                changed = true;
9185            } else if target != immediate {
9186                // Redirect to the end of the chain.
9187                let label = index_label[target];
9188                kept[index].1 = vec![Op::Label(label)];
9189                changed = true;
9190            }
9191        }
9192        if !changed {
9193            break;
9194        }
9195        if !delete.iter().any(|deleted| *deleted) {
9196            break;
9197        }
9198        // Drop the deleted instructions and renumber everything.
9199        let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9200        let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9201        let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9202        for (old, entry) in kept.into_iter().enumerate() {
9203            if delete[old] {
9204                continue;
9205            }
9206            moved[old] = Some(next.len());
9207            next.push(entry);
9208            next_spans.push(spans[old]);
9209        }
9210        for (id, slot) in label_kept.iter_mut().enumerate() {
9211            let Some(old) = *slot else { continue };
9212            *slot = match moved.get(old).copied().flatten() {
9213                Some(new) => Some(new),
9214                // The target was deleted: the jump now lands on whatever follows.
9215                None => (old..moved.len())
9216                    .find_map(|i| moved[i])
9217                    .or(Some(next.len())),
9218            };
9219            let _ = id;
9220        }
9221        kept = next;
9222        spans = next_spans;
9223    }
9224
9225    // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
9226    // jump to the next instruction and is deleted, leaving the label at the end with
9227    // nothing pointing at it. If that also strands the last instruction, it goes
9228    // too — which is how a `try` whose body always returns ends on its `ret` rather
9229    // than an implicit `return_undef`.
9230    // Which instructions something still jumps to. Reading the surviving jumps is
9231    // what the reference's reference counts amount to: once a jump has been folded
9232    // away the label it named is unreferenced, even though the program still has a
9233    // label there.
9234    let mut references = vec![false; kept.len() + 1];
9235    let _ = real_labels;
9236    for (_, operands) in &kept {
9237        if let Some(target) = target_kept_index(operands, &label_kept)
9238            && target < references.len()
9239        {
9240            references[target] = true;
9241        }
9242    }
9243    let mut end = kept.len();
9244    while end > 0 {
9245        let last = end - 1;
9246        let reachable = references[last] || end < kept.len();
9247        if reachable {
9248            break;
9249        }
9250        let after_transfer = last
9251            .checked_sub(1)
9252            .map(|previous| {
9253                matches!(
9254                    kept[previous].0,
9255                    Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
9256                )
9257            })
9258            .unwrap_or(false);
9259        if !after_transfer {
9260            break;
9261        }
9262        end = last;
9263    }
9264    kept.truncate(end);
9265    spans.truncate(end);
9266
9267    // Choose an opcode for each instruction and its size, so label offsets can be
9268    // computed.
9269    let chosen = choose_opcodes(&kept, &label_kept);
9270    let offsets = instruction_offsets(&chosen);
9271    let offset = *offsets.last().unwrap_or(&0);
9272
9273    let mut code = Vec::with_capacity(offset);
9274    for (position, (_, operands)) in kept.iter().enumerate() {
9275        let op = chosen[position];
9276        code.push(op as u8);
9277        let operands = retarget_labels(operands, &label_kept, kept.len());
9278        encode_operands(&mut code, op, &operands, offsets[position], &offsets);
9279    }
9280    let stack_size = compute_stack_size(&code);
9281    // Keep only the offsets where the position actually changes: a run of
9282    // instructions on one line is one table entry, and the runtime binary searches
9283    // the table for the frame's pc.
9284    //
9285    // The table always starts at pc 0 with the *function's own* position, because the
9286    // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
9287    // last_line_num)` from `fd->source_pos`, the token the function definition starts at
9288    // (`function`, `async`, a method's property name). An instruction before the first
9289    // recorded operator therefore reports the function's own start, which is what makes a
9290    // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
9291    let mut positions: Vec<LineCol> = vec![LineCol {
9292        pc: 0,
9293        line: state.line,
9294        column: state.column,
9295    }];
9296    let mut last: Option<Position> = None;
9297    for (index, span) in spans.iter().enumerate() {
9298        let Some(pos) = *span else { continue };
9299        if last == Some(pos) {
9300            continue;
9301        }
9302        last = Some(pos);
9303        if pos.line == state.line && pos.column == state.column {
9304            // Already the seed entry above.
9305            continue;
9306        }
9307        positions.push(LineCol {
9308            pc: offsets[index] as u32,
9309            line: pos.line,
9310            column: pos.column,
9311        });
9312    }
9313    (code, stack_size, positions)
9314}
9315
9316/// Whether an instruction always transfers control away, so anything after it in the
9317/// same stream is unreachable.
9318fn is_transfer(op: Opcode) -> bool {
9319    matches!(
9320        op,
9321        Opcode::Goto
9322            | Opcode::Goto8
9323            | Opcode::Goto16
9324            | Opcode::Return
9325            | Opcode::ReturnUndef
9326            | Opcode::Throw
9327            | Opcode::ThrowError
9328            | Opcode::Ret
9329    )
9330}
9331
9332/// Remove the marked instructions and renumber the label table so it keeps pointing
9333/// at the same instructions. A label whose instruction went away moves to whatever
9334/// follows it, since a jump is never left with nowhere to land.
9335fn drop_instructions(
9336    kept: Vec<(Opcode, Vec<Op>)>,
9337    spans: Vec<Option<Position>>,
9338    label_kept: &mut [Option<usize>],
9339    doomed: &[bool],
9340) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
9341    let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9342    let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9343    let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9344    for (old, entry) in kept.into_iter().enumerate() {
9345        if doomed.get(old).copied().unwrap_or(false) {
9346            continue;
9347        }
9348        moved[old] = Some(result.len());
9349        result.push(entry);
9350        result_spans.push(spans[old]);
9351    }
9352    for slot in label_kept.iter_mut() {
9353        let Some(old) = *slot else { continue };
9354        *slot = match moved.get(old).copied().flatten() {
9355            Some(new) => Some(new),
9356            None => (old..moved.len())
9357                .find_map(|i| moved[i])
9358                .or(Some(result.len())),
9359        };
9360    }
9361    (result, result_spans)
9362}
9363
9364fn is_goto(op: Opcode) -> bool {
9365    matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
9366}
9367
9368/// The kept index a jump operand points at.
9369fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
9370    let id = label_id(operands)?;
9371    label_kept.get(id as usize).copied().flatten()
9372}
9373
9374/// Follow a chain of unconditional jumps to its first real destination.
9375fn follow_jump_chain(
9376    kept: &[(Opcode, Vec<Op>)],
9377    label_kept: &[Option<usize>],
9378    start: usize,
9379) -> usize {
9380    let mut current = start;
9381    // `for(;;)` jumps to itself, so the walk has to be bounded.
9382    for _ in 0..kept.len() {
9383        let Some((op, operands)) = kept.get(current) else {
9384            return current;
9385        };
9386        if !is_goto(*op) {
9387            return current;
9388        }
9389        let Some(next) = target_kept_index(operands, label_kept) else {
9390            return current;
9391        };
9392        if next == current {
9393            return current;
9394        }
9395        current = next;
9396    }
9397    current
9398}
9399
9400/// Rewrite label operands from label ids to kept instruction indices.
9401fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
9402    operands
9403        .iter()
9404        .map(|operand| match operand {
9405            Op::Label(label) => {
9406                let target = label_kept
9407                    .get(label.0 as usize)
9408                    .copied()
9409                    .flatten()
9410                    .unwrap_or(kept_len);
9411                Op::Label(Label(target as u32))
9412            }
9413            other => other.clone(),
9414        })
9415        .collect()
9416}
9417
9418/// Encode the resolved instruction stream, choosing short forms where possible.
9419///
9420/// Compute the maximum value-stack depth by exploring the control-flow graph.
9421///
9422/// This is a breadth-first walk from the first instruction, tracking the stack
9423/// depth on entry to each instruction. Every instruction has at most two
9424/// successors (fall through, and a jump target), so a worklist over byte offsets
9425/// is enough. The reference does the same thing in `compute_stack_size`, which is
9426/// why the resulting numbers match exactly.
9427///
9428/// Instructions that pop a variable number of values (`call`, `array_from`, …)
9429/// encode that count in their operand, which is added to the static `n_pop`.
9430fn compute_stack_size(code: &[u8]) -> u32 {
9431    let mut depth_at = vec![u16::MAX; code.len()];
9432    // Each entry carries the enclosing `catch` levels, innermost last, because
9433    // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
9434    // offset and forgets that level.
9435    let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
9436    let mut max_depth = 0u32;
9437
9438    while let Some((pc, depth, catch_levels)) = worklist.pop() {
9439        if pc >= code.len() {
9440            continue;
9441        }
9442        if depth_at[pc] != u16::MAX {
9443            continue;
9444        }
9445        force_depth(&mut depth_at, pc, depth);
9446
9447        let Some(op) = Opcode::from_u8(code[pc]) else {
9448            break;
9449        };
9450        let info = op.info();
9451        let next = pc + info.size as usize;
9452        if next > code.len() {
9453            break;
9454        }
9455        let mut n_pop = info.n_pop as u32;
9456        let mut n_push = info.n_push as u32;
9457        // Variable-length forms carry their count in the operand.
9458        match info.format {
9459            crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
9460                n_pop += read_u16(code, pc + 1) as u32;
9461            }
9462            crate::opcode::OpFormat::Npopx => {
9463                n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
9464            }
9465            _ => {}
9466        }
9467        // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
9468        // are the `set_` variant; the table already records that, so nothing to
9469        // adjust here.
9470        let _ = &mut n_push;
9471
9472        // The depth before this instruction's own push, which is what a `catch`
9473        // records as its level.
9474        let depth_before = depth;
9475        let mut depth = depth.saturating_sub(n_pop) + n_push;
9476        let mut catch_levels = catch_levels;
9477        if op == Opcode::NipCatch {
9478            // Discard everything above the innermost catch offset, keeping the value
9479            // on top: the frame the code after this sees is the same shape it would
9480            // have had if the `try` were not there.
9481            if let Some(base) = catch_levels.pop() {
9482                depth = base + 1;
9483            }
9484        }
9485        max_depth = max_depth.max(depth);
9486
9487        // Successors.
9488        let target = jump_target_of(code, pc, op);
9489        match op {
9490            Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9491                if let Some(target) = target {
9492                    worklist.push((target, depth, catch_levels));
9493                }
9494            }
9495            Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
9496                if let Some(target) = target {
9497                    worklist.push((target, depth, catch_levels.clone()));
9498                }
9499                worklist.push((next, depth, catch_levels));
9500            }
9501            // A `catch` records an exception edge to the handler. The handler is
9502            // entered with the thrown value on top of the stack, in the slot the
9503            // catch offset occupies on the normal path — which is why the handler's
9504            // first instruction can `put_loc` the exception away, and why the depth
9505            // is the same on both paths.
9506            Opcode::Catch => {
9507                if let Some(target) = target {
9508                    // The handler is protected by the *enclosing* catch, not by this
9509                    // one: an error raised inside it is what the handler's own
9510                    // `catch` catches.
9511                    worklist.push((target, depth, catch_levels.clone()));
9512                }
9513                catch_levels.push(depth_before);
9514                worklist.push((next, depth, catch_levels));
9515            }
9516            // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
9517            // rewind past it too. Its level sits one slot higher than a `catch`'s:
9518            // the iterator and next-method slots occupy the offset's place.
9519            Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
9520                if let Some(target) = target {
9521                    worklist.push((target, depth, catch_levels.clone()));
9522                }
9523                catch_levels.push(depth_before + 1);
9524                worklist.push((next, depth, catch_levels));
9525            }
9526            // `gosub` calls a subroutine with the return address on top. The opcode
9527            // table records no push for it — `ret` is what pops the slot — so the
9528            // extra one is added here, where the depth of the subroutine's first
9529            // instruction is being computed.
9530            Opcode::Gosub => {
9531                if let Some(target) = target {
9532                    worklist.push((target, depth + 1, catch_levels.clone()));
9533                }
9534                worklist.push((next, depth, catch_levels));
9535            }
9536            // `ret` goes back to a `gosub`; nothing here follows it.
9537            Opcode::Ret
9538            | Opcode::Return
9539            | Opcode::ReturnUndef
9540            | Opcode::Throw
9541            | Opcode::ThrowError => {}
9542            _ => worklist.push((next, depth, catch_levels)),
9543        }
9544    }
9545    max_depth
9546}
9547
9548/// Record the stack depth on entry to `pc`, keeping the deeper value if the
9549/// instruction is reachable more than once.
9550fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
9551    let clamped = depth.min(u16::MAX as u32 - 1) as u16;
9552    if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
9553        depth_at[pc] = clamped;
9554    }
9555}
9556
9557fn read_u16(code: &[u8], at: usize) -> u16 {
9558    let mut value = 0u16;
9559    for i in 0..2 {
9560        value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
9561    }
9562    value
9563}
9564
9565/// The absolute target of a jump instruction, if it has one.
9566fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
9567    let info = op.info();
9568    let position = pc + 1;
9569    match info.format {
9570        crate::opcode::OpFormat::Label8 => {
9571            let offset = *code.get(position)? as i8 as i64;
9572            Some((position as i64 + offset) as usize)
9573        }
9574        crate::opcode::OpFormat::Label16 => {
9575            let offset = read_u16(code, position) as i16 as i64;
9576            Some((position as i64 + offset) as usize)
9577        }
9578        crate::opcode::OpFormat::Label => {
9579            let mut offset = 0i32;
9580            for i in 0..4 {
9581                offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
9582            }
9583            Some((position as i64 + offset as i64) as usize)
9584        }
9585        _ => None,
9586    }
9587}
9588
9589fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
9590    use Opcode::*;
9591    match (op, operands.first()) {
9592        (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
9593            op.short_form(*value as u32).unwrap_or(op)
9594        }
9595        (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
9596        (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
9597        (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
9598        | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
9599        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
9600        // A declared global is reached through its reference cell, so it shares
9601        // the `var_ref` encodings, short forms included.
9602        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
9603            op.short_form(*index).unwrap_or(op)
9604        }
9605        (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
9606            op.short_form(*count as u32).unwrap_or(op)
9607        }
9608        _ => op,
9609    }
9610}
9611
9612/// The byte offset each instruction will start at, plus the total code size.
9613fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
9614    let mut offsets = Vec::with_capacity(chosen.len() + 1);
9615    let mut offset = 0usize;
9616    for op in chosen {
9617        offsets.push(offset);
9618        offset += op.size() as usize;
9619    }
9620    offsets.push(offset);
9621    offsets
9622}
9623
9624/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
9625/// the offset actually fits.
9626///
9627/// The choice is circular: an instruction's size decides the offsets of everything after
9628/// it, and the offsets decide whether a jump may be short. So this starts with every jump
9629/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
9630/// Shrinking only ever *shortens* distances, so the loop converges.
9631///
9632/// Doing it in one pass instead — which is what this used to do — silently truncated any
9633/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
9634/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
9635/// with four closures in its body simply stopped, with no error and no output past the
9636/// first iteration.
9637fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
9638    let mut chosen: Vec<Opcode> = kept
9639        .iter()
9640        .map(|(op, operands)| choose_short_form(*op, operands))
9641        .collect();
9642    // A jump the compiler emitted in its widest form, and the forms it may shrink to.
9643    let candidates = |op: Opcode| match op {
9644        Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
9645        Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
9646        Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
9647        _ => None,
9648    };
9649    loop {
9650        let offsets = instruction_offsets(&chosen);
9651        let mut changed = false;
9652        for index in 0..kept.len() {
9653            let (op, operands) = &kept[index];
9654            let Some((short, medium, has_medium)) = candidates(*op) else {
9655                continue;
9656            };
9657            if chosen[index] == short {
9658                continue;
9659            }
9660            let Some(target) = target_kept_index(operands, label_kept) else {
9661                continue;
9662            };
9663            let Some(&target_offset) = offsets.get(target) else {
9664                continue;
9665            };
9666            // A jump is relative to the byte after its opcode, which is the convention
9667            // `jump_target_of` decodes with.
9668            let relative = target_offset as i64 - (offsets[index] as i64 + 1);
9669            if (-128..=127).contains(&relative) {
9670                chosen[index] = short;
9671                changed = true;
9672            } else if has_medium
9673                && chosen[index] == Opcode::Goto
9674                && (-32_768..=32_767).contains(&relative)
9675            {
9676                // Too far for 8 bits and close enough for 16. Only `goto` has a medium
9677                // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
9678                // the reference encodes them.
9679                chosen[index] = medium;
9680                changed = true;
9681            }
9682        }
9683        if !changed {
9684            return chosen;
9685        }
9686    }
9687}
9688
9689fn encode_operands(
9690    code: &mut Vec<u8>,
9691    op: Opcode,
9692    operands: &[Op],
9693    position: usize,
9694    offsets: &[usize],
9695) {
9696    use crate::opcode::OpFormat::*;
9697    let info = op.info();
9698    let write_slot = |code: &mut Vec<u8>, slot: Slot| {
9699        let index = match slot {
9700            Slot::Arg(i)
9701            | Slot::Loc(i)
9702            | Slot::VarRef(i)
9703            | Slot::Global(i)
9704            | Slot::GlobalDecl(i) => i,
9705        };
9706        code.extend_from_slice(&(index as u16).to_be_bytes());
9707    };
9708    match info.format {
9709        None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
9710        U8 | Const8 => {
9711            if let Some(value) = operands.first().and_then(operand_uint) {
9712                code.push(value as u8);
9713            }
9714        }
9715        // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
9716        // like their wide counterparts, only one byte wide.
9717        Loc8 => {
9718            if let Some(Op::Slot(slot)) = operands.first() {
9719                let index = match slot {
9720                    Slot::Arg(i)
9721                    | Slot::Loc(i)
9722                    | Slot::VarRef(i)
9723                    | Slot::Global(i)
9724                    | Slot::GlobalDecl(i) => *i,
9725                };
9726                code.push(index as u8);
9727            }
9728        }
9729        I8 => {
9730            if let Some(value) = operands.first().and_then(operand_int) {
9731                code.push(value as i8 as u8);
9732            }
9733        }
9734        U16 | Npop => {
9735            if let Some(value) = operands.first().and_then(operand_int) {
9736                code.extend_from_slice(&(value as u16).to_be_bytes());
9737            }
9738        }
9739        I16 => {
9740            if let Some(value) = operands.first().and_then(operand_int) {
9741                code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
9742            }
9743        }
9744        I32 => {
9745            if let Some(value) = operands.first().and_then(operand_int) {
9746                code.extend_from_slice(&value.to_be_bytes());
9747            }
9748        }
9749        U32 | Const => {
9750            if let Some(value) = operands.first().and_then(operand_uint) {
9751                code.extend_from_slice(&value.to_be_bytes());
9752            }
9753        }
9754        Loc | Arg | VarRef => {
9755            if let Some(Op::Slot(slot)) = operands.first() {
9756                write_slot(code, *slot);
9757            }
9758        }
9759        Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
9760            if let Some(Op::AtomId(index)) = operands.first() {
9761                code.extend_from_slice(&index.to_be_bytes());
9762            }
9763            // The trailing immediate means different things per format, and the
9764            // atom forms that carry a *label* have to resolve it like any other
9765            // jump, so they cannot share the `U8`/`U16` arms above.
9766            match info.format {
9767                AtomU8 | AtomLabelU8 => {
9768                    if let Some(value) = operands.get(1).and_then(operand_uint) {
9769                        code.push(value as u8);
9770                    }
9771                }
9772                AtomU16 | AtomLabelU16 => {
9773                    if let Some(value) = operands.get(1).and_then(operand_uint) {
9774                        code.extend_from_slice(&(value as u16).to_be_bytes());
9775                    }
9776                }
9777                _ => {}
9778            }
9779        }
9780        NpopU16 => {
9781            for operand in operands.iter().take(2) {
9782                if let Some(value) = operand_uint(operand) {
9783                    code.extend_from_slice(&(value as u16).to_be_bytes());
9784                }
9785            }
9786        }
9787        Label | Label8 | Label16 | LabelU16 => {
9788            if let Some(Op::Label(label)) = operands.first() {
9789                // Labels were already remapped to kept-instruction indices.
9790                let Some(&target) = offsets.get(label.0 as usize) else {
9791                    debug_assert!(false, "label {} is past the end", label.0);
9792                    return;
9793                };
9794                let relative = target as i64 - (position as i64 + 1);
9795                match info.format {
9796                    Label8 => code.push(relative as i8 as u8),
9797                    Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
9798                    // `label_u16` stores the target followed by an unrelated u16.
9799                    LabelU16 => {
9800                        code.extend_from_slice(&(relative as i32).to_be_bytes());
9801                        if let Some(value) = operands.get(1).and_then(operand_uint) {
9802                            code.extend_from_slice(&(value as u16).to_be_bytes());
9803                        }
9804                    }
9805                    _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
9806                }
9807            }
9808        }
9809    }
9810}
9811
9812fn operand_int(op: &Op) -> Option<i32> {
9813    match op {
9814        Op::Int(value) => Some(*value),
9815        _ => None,
9816    }
9817}
9818
9819fn operand_uint(op: &Op) -> Option<u32> {
9820    match op {
9821        Op::Const(value) | Op::AtomId(value) => Some(*value),
9822        Op::Int(value) => Some(*value as u32),
9823        _ => None,
9824    }
9825}
9826
9827/// Disassemble a compiled function.
9828pub fn disassemble(function: &CompiledFunction) -> String {
9829    disasm::disassemble_program(function)
9830}