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}
784
785/// How a use site of a private name compiles.
786///
787/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
788/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
789/// of a setter-only accessor pair.
790#[derive(Clone, Copy, PartialEq, Eq)]
791enum PrivateKind {
792    /// `#x = 1`: an own property keyed by the symbol in the binding.
793    Field,
794    /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
795    Method,
796    /// `get #a() {}`: the binding holds the getter, and a read calls it.
797    Getter,
798    /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
799    /// the same `TypeError` as reading an uninitialised `const`.
800    Setter,
801}
802
803/// What the compiler knows about one `#name` where it is used.
804#[derive(Clone)]
805struct PrivateUse {
806    kind: PrivateKind,
807    /// `#a<set>` when the class defines a setter for this name.
808    ///
809    /// A second binding, not a second field of the first: the reference stores the setter
810    /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
811    setter: Option<String>,
812}
813
814/// The class-scope bindings one class body needs, in declaration order.
815#[derive(Default)]
816struct ClassPlan {
817    /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
818    /// at class entry, in member order.
819    bindings: Vec<String>,
820    /// The private names, for the use sites inside the body.
821    uses: std::collections::HashMap<String, PrivateUse>,
822    /// Computed field keys, by element index, so the emission pass does not have to redo the
823    /// per-half counter that names them.
824    computed: std::collections::HashMap<usize, String>,
825    /// Whether the instance initialiser has to add the brand to `this`.
826    instance_brand: bool,
827    /// Whether the constructor itself has to carry the brand.
828    static_brand: bool,
829}
830
831impl ClassPlan {
832    /// Walk a class body once and decide every class-scope binding it needs.
833    ///
834    /// Order is the reference's: a member's binding is created when the member is parsed, so
835    /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
836    /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
837    /// the disassembly stops matching even when every instruction is right.
838    fn build(class: &Class) -> ClassPlan {
839        let mut plan = ClassPlan::default();
840        let mut instance_keys = 0usize;
841        let mut static_keys = 0usize;
842        for (index, element) in class.elements.iter().enumerate() {
843            match element {
844                ClassElement::Method {
845                    key: PropName::Private(ident),
846                    kind,
847                    is_static,
848                    ..
849                } => {
850                    let name = format!("#{}", ident.name);
851                    let first = !plan.uses.contains_key(&name);
852                    if first {
853                        plan.bindings.push(name.clone());
854                        plan.uses.insert(
855                            name.clone(),
856                            PrivateUse {
857                                kind: match kind {
858                                    MethodKind::Get => PrivateKind::Getter,
859                                    MethodKind::Set => PrivateKind::Setter,
860                                    _ => PrivateKind::Method,
861                                },
862                                setter: None,
863                            },
864                        );
865                    }
866                    match kind {
867                        MethodKind::Set => {
868                            let binding = format!("{name}<set>");
869                            plan.bindings.push(binding.clone());
870                            if let Some(use_) = plan.uses.get_mut(&name) {
871                                use_.setter = Some(binding);
872                            }
873                        }
874                        // A getter is what makes the name readable, so a pair that started
875                        // as a setter becomes readable once the getter arrives.
876                        MethodKind::Get => {
877                            if let Some(use_) = plan.uses.get_mut(&name) {
878                                use_.kind = PrivateKind::Getter;
879                            }
880                        }
881                        _ => {}
882                    }
883                    if *is_static {
884                        plan.static_brand = true;
885                    } else {
886                        plan.instance_brand = true;
887                    }
888                }
889                ClassElement::Method {
890                    key: PropName::Computed(_),
891                    ..
892                } => {}
893                ClassElement::Method { .. } => {}
894                ClassElement::Field {
895                    key: PropName::Private(ident),
896                    ..
897                } => {
898                    let name = format!("#{}", ident.name);
899                    if !plan.uses.contains_key(&name) {
900                        plan.bindings.push(name.clone());
901                        plan.uses.insert(
902                            name,
903                            PrivateUse {
904                                kind: PrivateKind::Field,
905                                setter: None,
906                            },
907                        );
908                    }
909                }
910                ClassElement::Field {
911                    key: PropName::Computed(_),
912                    is_static,
913                    ..
914                } => {
915                    let index_in_half = if *is_static {
916                        static_keys += 1;
917                        static_keys - 1
918                    } else {
919                        instance_keys += 1;
920                        instance_keys - 1
921                    };
922                    let binding = computed_field_binding(index_in_half, *is_static);
923                    plan.bindings.push(binding.clone());
924                    plan.computed.insert(index, binding);
925                }
926                ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
927            }
928        }
929        plan
930    }
931
932    /// How a private name used inside the body compiles, or `None` if no enclosing class
933    /// declares it.
934    fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
935        compiler
936            .private_scopes
937            .iter()
938            .rev()
939            .find_map(|scope| scope.get(name))
940    }
941}
942
943impl Compiler {
944    /// The exact source text of a function, for `Function.prototype.toString`.
945    ///
946    /// §20.2.3.5 requires the *original* text: a function must stringify back to what
947    /// was written, comments and odd spacing included. Slicing the recorded span out of
948    /// the whole source is the only way to get that — rebuilding it from the AST would
949    /// normalise the text, and answering `[native code]` for a script function (which is
950    /// what this engine used to do) makes the result useless for feature detection and
951    /// for libraries that read their own source.
952    ///
953    /// Top-level bodies have no single expression span, so their `source` stays `None`
954    /// and `toString` falls back to the calling convention the spec allows.
955    fn function_source(
956        &self,
957        span: Option<(usize, usize)>,
958        line: u32,
959        column: u32,
960    ) -> Option<String> {
961        let source = self.source.as_ref()?;
962        let span = span?;
963        let bytes = source.as_bytes();
964        let start = span.0;
965        let end = span.1;
966        if start >= bytes.len() || end > bytes.len() || start >= end {
967            let _ = (line, column);
968            return None;
969        }
970        Some(source.get(start..end)?.to_string())
971    }
972}
973
974/// Compile a script.
975pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
976    Compiler::new(false).compile(program)
977}
978
979/// Compile a script, keeping its text so `Function.prototype.toString` can answer with
980/// the original source.
981///
982/// The separate entry point rather than a parameter on [`compile_script`] because the
983/// tests and the disassembler compile from an AST they built themselves and have no
984/// source to give; they keep the `None` behaviour they already relied on.
985pub fn compile_script_with_source(
986    program: &Program,
987    source: &str,
988) -> Result<CompiledFunction, SyntaxError> {
989    let mut compiler = Compiler::new(false);
990    compiler.source = Some(source.to_string());
991    compiler.compile(program)
992}
993
994/// [`compile_script_with_source`] for a module.
995pub fn compile_module_with_source(
996    program: &Program,
997    source: &str,
998) -> Result<CompiledFunction, SyntaxError> {
999    let mut compiler = Compiler::new(true);
1000    compiler.source = Some(source.to_string());
1001    compiler.compile(program)
1002}
1003
1004/// Compile a script whose top level is the body of an `async` function.
1005///
1006/// The body is an ordinary script in every other way — it still reports a completion value
1007/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
1008/// it answers a promise instead of a value. The wrapper is what keeps that promise from
1009/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
1010/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
1011/// documents.
1012pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1013    Compiler::for_suspensible_script().compile(program)
1014}
1015
1016/// Compile a module.
1017pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1018    Compiler::new(true).compile(program)
1019}
1020
1021impl Compiler {
1022    /// Create a compiler.
1023    pub fn new(module: bool) -> Compiler {
1024        Compiler {
1025            source: None,
1026            module,
1027            async_body: false,
1028            stack: Vec::new(),
1029            private_scopes: Vec::new(),
1030        }
1031    }
1032
1033    /// Create a compiler for a script whose top level is an `async` function body.
1034    fn for_suspensible_script() -> Compiler {
1035        Compiler {
1036            source: None,
1037            module: false,
1038            async_body: true,
1039            stack: Vec::new(),
1040            private_scopes: Vec::new(),
1041        }
1042    }
1043
1044    /// Compile a whole program into its top-level function.
1045    pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
1046        let mut state = FnState::new("<eval>", FunctionKind::Normal);
1047        // A module body is *not* a script: it has no completion value, so no hidden
1048        // `<ret>` local and no `put_loc0` before each statement. What it shares with one
1049        // is having no `arguments` of its own and no receiver — see `is_module`.
1050        state.is_script = !self.module;
1051        state.is_module = self.module;
1052        if self.module {
1053            state.module = Some(ModuleMeta::default());
1054        }
1055        state.strict = program.strict || self.module;
1056        state.line = program.span.start.line;
1057        state.column = program.span.start.column;
1058        // Locals are numbered in declaration order; `<ret>` is always slot 0.
1059        //
1060        // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
1061        // slot that only appears in one of the two arrays shifts every later
1062        // binding's block and silently loses the temporal-dead-zone marking for
1063        // the script's own blocks. A function frame has no `<ret>`, which is why
1064        // the misalignment only showed up at the top level.
1065        if !self.module {
1066            state.vars.push(VarDef::var("<ret>"));
1067            state.var_block.push(FUNCTION_SCOPE);
1068        }
1069        self.stack.push(state);
1070        // The body is its own scope, keyed by the position of the program.
1071        // The script body needs a key no statement can produce. Statement keys are
1072        // source offsets, and the program's own start offset is `0` — which is also
1073        // the offset of the first statement, so a top-level `{ let x }` or
1074        // `for (let i …)` used to share the body's block and lose its scope.
1075        let body_key = SCRIPT_BODY;
1076        self.push_block(body_key, NO_PARENT);
1077        self.state().body_block = body_key;
1078        // A module body opens with a re-entry guard. The host evaluates a module exactly
1079        // once, so the guard never fires in practice — but the reference emits it, and a
1080        // module function called a second time (through `eval` of its own source, say)
1081        // must not run its body again.
1082        let module_guard = self.module.then(|| self.new_label());
1083        if let Some(body) = module_guard {
1084            // The guard wraps the *hoisting* too: a second evaluation of the same module
1085            // body must not even re-create its function declarations.
1086            self.emit(Opcode::PushThis, &[]);
1087            self.emit_jump(Opcode::IfFalse, body, &[]);
1088        }
1089        self.hoist(&program.body, body_key)?;
1090        // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
1091        // come before the guard's `return_undef`: the reference's jump target sits past
1092        // both, and a second evaluation therefore re-creates nothing.
1093        self.emit_scope_enter(body_key);
1094        if let Some(body) = module_guard {
1095            self.emit(Opcode::ReturnUndef, &[]);
1096            self.place_label(body);
1097        }
1098        // Through `stmts` rather than the loop, so a `using` region at the top level of an
1099        // eval'd body or a module gets its disposal epilogue like any other block.
1100        self.stmts(&program.body)?;
1101        if self.module {
1102            // A module has no completion value; its body simply ends.
1103            self.emit(Opcode::Undefined, &[]);
1104            self.emit(Opcode::ReturnAsync, &[]);
1105            // Top-level `await` makes the body an async function, so the host runs it as
1106            // a coroutine and waits. Without this the `await` opcode would suspend in a
1107            // body that nothing knows how to resume — which is what "a generator body ran
1108            // as an ordinary call" was reporting.
1109            if self.cur().has_await {
1110                self.state().kind = FunctionKind::Async;
1111            }
1112        } else if self.async_body {
1113            // An async body reports its completion value the same way, but through an
1114            // object: the function answers a promise, and resolving that promise *with*
1115            // the completion value would adopt a promise completion instead of reporting
1116            // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
1117            // resolve to `{value: <promise>}` rather than to `7`.
1118            //
1119            // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
1120            // value in an object so that promises can be safely returned").
1121            self.emit(Opcode::Object, &[]);
1122            self.emit(Opcode::Dup, &[]);
1123            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1124            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
1125            self.emit(Opcode::Return, &[]);
1126            self.state().kind = FunctionKind::Async;
1127        } else {
1128            // The program's value is whatever the last expression statement stored in
1129            // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
1130            // case into a single `set_loc0`.
1131            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1132            self.emit(Opcode::Return, &[]);
1133        }
1134        Ok(self.finish_current())
1135    }
1136
1137    // -- emitting ----------------------------------------------------------
1138
1139    fn state(&mut self) -> &mut FnState {
1140        self.stack.last_mut().expect("a function is being compiled")
1141    }
1142
1143    fn cur(&self) -> &FnState {
1144        self.stack.last().expect("a function is being compiled")
1145    }
1146
1147    fn emit(&mut self, op: Opcode, operands: &[Op]) {
1148        self.state().label_since_insn = false;
1149        let pos = self.cur().cur_pos;
1150        self.state().insns.push(Insn::Fixed {
1151            op,
1152            operands: operands.to_vec(),
1153        });
1154        self.state().insn_pos.push(pos);
1155    }
1156
1157    /// Reset the script's hidden return value to `undefined`.
1158    ///
1159    /// Called at the start of every statement that does not itself produce the
1160    /// program's value, which is how the reference keeps `if`/loop results from
1161    /// leaking into an eval result.
1162    fn reset_value(&mut self) {
1163        if !self.cur().is_script {
1164            return;
1165        }
1166        self.emit(Opcode::Undefined, &[]);
1167        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1168        self.state().leaves_value = false;
1169    }
1170
1171    /// Whether `name` is a local or argument slot rather than a global.
1172    fn is_slot(&self, name: &str) -> bool {
1173        self.cur().vars.iter().any(|v| v.name == name)
1174            || self.cur().args.iter().any(|a| a.name == name)
1175    }
1176
1177    /// `with (object) body`
1178    ///
1179    /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
1180    /// what makes the object reachable from a closure created inside the block, and it
1181    /// is also what lets an `eval` find it: the runtime collects the active `With`
1182    /// locals of every frame and resolves names against them before the realm.
1183    ///
1184    /// Inside the block every name reference is spelled as "look in the with objects
1185    /// first", innermost outwards, and falls through to the ordinary access. The test is
1186    /// `in`, which is `HasProperty` — the same question the spec's Object Environment
1187    /// Record asks.
1188    fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
1189        let name = self.next_with_name();
1190        // The object expression is evaluated *outside* the scope it introduces, so no
1191        // wrapper may be emitted for the names it mentions.
1192        let saved = std::mem::take(&mut self.state().with_names);
1193        self.expr(object)?;
1194        self.state().with_names = saved;
1195        self.emit(Opcode::ToObject, &[]);
1196        self.declare_hidden_local(&name, VarKind::With);
1197        // Pushed before the store so the store itself is not guarded by an *outer*
1198        // `with` — the object being stored is the new one, not something to look up.
1199        self.state().with_names.push(name.clone());
1200        self.emit_var(VarAction::Put, &name);
1201        let result = self.stmt(body);
1202        self.state().with_names.pop();
1203        result
1204    }
1205
1206    /// A hidden-local name for one `with` block, distinct from every enclosing one.
1207    fn next_with_name(&self) -> String {
1208        let depth = self.cur().with_names.len();
1209        if depth == 0 {
1210            "<with>".to_string()
1211        } else {
1212            format!("<with{depth}>")
1213        }
1214    }
1215
1216    /// Declare a hidden local that must stay a *local* even in a script.
1217    ///
1218    /// A script's `var` is a property of the global object, but the `with` object is not
1219    /// part of the source program's name space at all — it only exists for the compiler
1220    /// and the runtime — so it goes straight into the frame's slot list.
1221    fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
1222        let state = self.state();
1223        if state.vars.iter().any(|v| v.name == name) {
1224            return;
1225        }
1226        state.var_block.push(FUNCTION_SCOPE);
1227        state.vars.push(VarDef {
1228            kind,
1229            ..VarDef::var(name)
1230        });
1231    }
1232
1233    /// Emit a name access, guarded by every active `with` object.
1234    ///
1235    /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
1236    /// the read itself; the outer guards and the plain access are what the `if_false`
1237    /// jumps to, so the innermost object wins.
1238    fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
1239        let names = self.cur().with_names.clone();
1240        let done = self.new_label();
1241        let mut starts = Vec::new();
1242        // Innermost object first: the last `with` opened is the one that shadows the
1243        // others, so its guard has to be the first chance to satisfy the name.
1244        for with_name in names.iter().rev() {
1245            let next = self.new_label();
1246            // `in` takes the key then the object.
1247            self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1248            self.emit_var(VarAction::Get, with_name);
1249            self.emit(Opcode::In, &[]);
1250            self.emit_jump(Opcode::IfFalse, next, &[]);
1251            starts.push(next);
1252            match action {
1253                // A store keeps the value under the receiver, which is where
1254                // `put_field` expects it.
1255                VarAction::Put | VarAction::PutInit => {
1256                    self.emit_var(VarAction::Get, with_name);
1257                    self.emit(Opcode::Swap, &[]);
1258                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(name))]);
1259                }
1260                _ => {
1261                    self.emit_var(VarAction::Get, with_name);
1262                    self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1263                    self.emit(Opcode::GetArrayEl, &[]);
1264                }
1265            }
1266            self.emit_jump(Opcode::Goto, done, &[]);
1267            self.place_label(next);
1268        }
1269        self.emit_var(action, name);
1270        self.place_label(done);
1271    }
1272
1273    fn emit_var(&mut self, action: VarAction, name: &str) {
1274        // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
1275        // stores and keeps the value in one instruction. The reference does this
1276        // in a post-pass; folding it at emit time keeps instruction indices
1277        // stable, which matters because labels are recorded as indices.
1278        //
1279        // Only slots have a `set_` form: a global is stored with `put_var` and
1280        // read with `get_var`, and the reference does not fold those.
1281        //
1282        // A label between the two cancels the fold. `set_x v` leaves the value on
1283        // the stack, which is only equivalent when the read immediately follows the
1284        // store; when a jump target sits in between, the store must *consume* the
1285        // value and the read must fetch it afresh. A loop head is exactly that
1286        // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
1287        // condition re-reads it — and folding across the label would make the
1288        // condition compare whatever the previous iteration left on the stack.
1289        if action == VarAction::Get {
1290            let is_slot = self.is_slot(name);
1291            let at_label = std::mem::take(&mut self.state().label_since_insn);
1292            //
1293            // `arguments` is excluded because the reference treats it as a special
1294            // binding: it is initialised once and read many times, and folding its
1295            // initialisation into a `set_` would leave the object on the stack where
1296            // the reference leaves nothing.
1297            if is_slot
1298                && name != "arguments"
1299                && !at_label
1300                && let Some(Insn::Var {
1301                    action: previous,
1302                    name: previous_name,
1303                    ..
1304                }) = self.state().insns.last_mut()
1305                && *previous == VarAction::Put
1306                && previous_name == name
1307            {
1308                *previous = VarAction::Set;
1309                return;
1310            }
1311        }
1312        // Inside a `with`, every name lookup consults the with objects first. The
1313        // hidden `<with…>` locals themselves are exempt, or the guard would recurse.
1314        let guarded = !self.cur().with_names.is_empty()
1315            && !self.cur().with_names.iter().any(|hidden| hidden == name)
1316            && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1317            && !self.state().emitting_with_guard;
1318        if guarded {
1319            self.state().emitting_with_guard = true;
1320            self.emit_with_guarded(action, name);
1321            self.state().emitting_with_guard = false;
1322            return;
1323        }
1324        let block = self.cur().current_block;
1325        self.state().label_since_insn = false;
1326        let pos = self.cur().cur_pos;
1327        let in_params = self.cur().in_params;
1328        self.state().insns.push(Insn::Var {
1329            action,
1330            name: name.to_string(),
1331            block,
1332            in_params,
1333        });
1334        self.state().insn_pos.push(pos);
1335    }
1336
1337    fn new_label(&mut self) -> Label {
1338        let state = self.state();
1339        state.labels.push(None);
1340        Label(state.labels.len() as u32 - 1)
1341    }
1342
1343    fn place_label(&mut self, label: Label) {
1344        let index = self.cur().insns.len();
1345        self.state().label_since_insn = true;
1346        self.state().labels[label.0 as usize] = Some(index);
1347    }
1348
1349    fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1350        let mut operands = vec![Op::Label(label)];
1351        operands.extend_from_slice(extra);
1352        self.emit(op, &operands);
1353    }
1354
1355    // -- scopes ------------------------------------------------------------
1356
1357    /// Start a new lexical scope inside `parent`.
1358    fn push_block(&mut self, key: u64, parent: u64) {
1359        let state = self.state();
1360        if !state.blocks.iter().any(|b| b.key == key) {
1361            state.blocks.push(Block { key, parent });
1362        }
1363        state.current_block = key;
1364    }
1365
1366    /// Emit the code that runs when a lexical scope is entered.
1367    ///
1368    /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1369    /// so entering its block marks it uninitialised. Hoisted function
1370    /// declarations are created here instead, which is why a call before the
1371    /// declaration still works.
1372    ///
1373    /// The order is not obvious: bindings are emitted in *reverse* declaration
1374    /// order, because the reference walks its scope chain, which is built by
1375    /// prepending.
1376    fn emit_scope_enter(&mut self, block: u64) {
1377        // Only *this* scope's hoisted declarations are consumed here; the rest stay in the
1378        // list for the scope that owns them. `std::mem::take` used to empty the whole list,
1379        // so entering an outer scope threw away every nested block's function
1380        // declarations: `function h(){ { function k(){} } return k; }` answered
1381        // `undefined`, and `{ function g(){} }` was `undefined` even *inside* the block.
1382        // That is one Annex B rule the engine otherwise implements (a sloppy-mode function
1383        // in a block is also a `var` of the enclosing function), and it is what makes the
1384        // `for (const ctor of ctors) { function f(){} … }` shape in test262 work.
1385        let mut hoisted = std::mem::take(&mut self.state().hoisted);
1386        let mut rest = Vec::with_capacity(hoisted.len());
1387        let mut mine: Vec<(HoistTarget, u32)> = Vec::new();
1388        for (owner, target, pool_index) in hoisted.drain(..) {
1389            if owner == block {
1390                mine.push((target, pool_index));
1391            } else {
1392                rest.push((owner, target, pool_index));
1393            }
1394        }
1395        self.state().hoisted = rest;
1396        mine.sort_by_key(|(target, _)| match target {
1397            HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1398            HoistTarget::Global(_) => u32::MAX,
1399        });
1400        for (target, pool_index) in mine {
1401            self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1402            match target {
1403                HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1404                HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1405                HoistTarget::Global(name) => {
1406                    // A global binding lives in a reference cell, so the store
1407                    // goes through `put_var_ref` while reads use `get_var`.
1408                    let block = self.cur().current_block;
1409                    let pos = self.cur().cur_pos;
1410                    let in_params = self.cur().in_params;
1411                    self.state().insns.push(Insn::Var {
1412                        action: VarAction::PutRef,
1413                        name,
1414                        block,
1415                        in_params,
1416                    });
1417                    self.state().insn_pos.push(pos);
1418                }
1419            }
1420        }
1421        for index in self.block_vars_reversed(block) {
1422            self.emit(
1423                Opcode::SetLocUninitialized,
1424                &[Op::Slot(Slot::Loc(index as u32))],
1425            );
1426        }
1427    }
1428
1429    /// Emit the code that runs when a lexical scope is exited.
1430    ///
1431    /// A captured binding has to be closed: detaching its reference cell freezes
1432    /// the value the binding had when the block ended, which is what a closure
1433    /// created inside the block must keep seeing.
1434    fn emit_scope_leave(&mut self, block: u64) {
1435        for index in self.block_vars_reversed(block) {
1436            if self.cur().vars[index].is_captured {
1437                self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1438            }
1439        }
1440    }
1441
1442    /// Locals declared in `block`, in reverse declaration order.
1443    fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1444        let state = self.cur();
1445        let mut out: Vec<usize> = (0..state.vars.len())
1446            .filter(|index| {
1447                state.var_block.get(*index).copied() == Some(block)
1448                    && state.vars[*index].is_lexical
1449                    // A derived constructor's `this` is lexical but is not initialised by
1450                    // entering the scope: `check_ctor` proves it, so its dead-zone marker
1451                    // was emitted with the constructor's own prologue.
1452                    && state.vars[*index].name != "this"
1453            })
1454            .collect();
1455        out.reverse();
1456        out
1457    }
1458
1459    /// Declare a local, even at the top level of a script.
1460    ///
1461    /// A `catch` parameter is always a local: the reference puts it in the
1462    /// function's own variable list (`1: catch e`), never in the global object,
1463    /// because it only exists while the handler runs.
1464    fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1465        let state = self.state();
1466        let index = state.vars.len() as u32;
1467        // A `catch` parameter belongs to a scope even though it is not lexical: the
1468        // runtime instantiates it per handler entry, but it never sits in the
1469        // temporal dead zone.
1470        let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1471            state.current_block
1472        } else {
1473            0
1474        };
1475        state.var_block.push(block);
1476        state.vars.push(def);
1477        index
1478    }
1479
1480    fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1481        if self.cur().is_module
1482            && self.cur().current_block == self.cur().body_block
1483            && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1484        {
1485            // Only the body's own block: a `let` inside a module-level `{}` is still an
1486            // ordinary local of that block, not a module variable.
1487            //
1488            // A `using` binding is excluded on purpose, and the reference excludes it in
1489            // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1490            // "'using' variables are currently not exported in modules"): a module-level
1491            // `using` is an ordinary *local* of the module body function, not a module
1492            // cell. Two things follow, and both are what the reference does — `export {a}`
1493            // of a `using` binding is "exported variable 'a' does not exist", and
1494            // disposal works, because the disposal epilogue addresses locals by slot.
1495            //
1496            // The hidden dispose-method variable is excluded for a stronger reason: it is
1497            // *always* a local (`add_scope_var` in the reference), and it must sit
1498            // immediately after its value so `using_dispose` can find it at `slot + 1`.
1499            return self.declare_module(name, &def);
1500        }
1501        if self.cur().declares_globally(&def) {
1502            self.declare_global(name, &def);
1503            return 0;
1504        }
1505        let state = self.state();
1506        let index = state.vars.len() as u32;
1507        let block = if def.is_lexical {
1508            state.current_block
1509        } else {
1510            0
1511        };
1512        state.var_block.push(block);
1513        state.vars.push(def);
1514        index
1515    }
1516
1517    /// Declare a `using` binding and its cached dispose method, returning both slots.
1518    ///
1519    /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1520    /// `(value, value + 1)` — the reference does the same and documents the constraint.
1521    fn declare_using(&mut self, name: &str) -> (u32, u32) {
1522        let mut def = VarDef::lexical(name);
1523        def.kind = VarKind::Using;
1524        let value = self.declare(name, def);
1525        let mut method = VarDef::lexical(using_method_name(name));
1526        method.kind = VarKind::UsingMethod;
1527        let method_slot = self.declare(&using_method_name(name), method);
1528        (value, method_slot)
1529    }
1530
1531    /// The slot a `using` binding's dispose method lives in.
1532    fn using_method_slot(&self, name: &str) -> Option<u32> {
1533        let hidden = using_method_name(name);
1534        self.cur()
1535            .vars
1536            .iter()
1537            .position(|var| var.name == hidden)
1538            .map(|index| index as u32)
1539    }
1540
1541    // -- statements --------------------------------------------------------
1542
1543    fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1544        self.stmt_labelled(stmt, &[])
1545    }
1546
1547    /// Compile a statement that a chain of labels names.
1548    ///
1549    /// Only a loop consumes `labels`; every other statement ignores them (the
1550    /// parser has already rejected a label on a statement that cannot use it).
1551    fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1552        // Only a *top-level* expression statement supplies the program's value.
1553        let saved = self.cur().leaves_value;
1554        self.state().leaves_value =
1555            matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1556        self.state().stmt_depth += 1;
1557        let result = self.stmt_inner(stmt, labels);
1558        self.state().stmt_depth -= 1;
1559        // A nested statement never contributes the program's value, so the flag
1560        // the wrapper set above is what survives.
1561        let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1562        self.state().leaves_value = produced;
1563        let _ = saved;
1564        result
1565    }
1566
1567    fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1568        match &stmt.kind {
1569            StmtKind::Empty | StmtKind::Debugger => {}
1570            StmtKind::Expr(expr) => {
1571                // The statement's first token is a position the reference records: an
1572                // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1573                // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1574                // is why an error from a construct with no position of its own (`[...it]`
1575                // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1576                let saved = self.cur().cur_pos;
1577                self.state().cur_pos = Some(expr.span.start);
1578                // An expression statement's value is thrown away — except in a
1579                // script, where it becomes the program's result. `assign` reads this
1580                // and clears it, so a nested assignment still produces a value.
1581                self.state().discard_value = !self.cur().is_script;
1582                let result = self.expr(expr);
1583                self.state().discard_value = false;
1584                result?;
1585                if std::mem::take(&mut self.state().no_value) {
1586                    // A store whose value was discarded left nothing to drop.
1587                } else if self.cur().is_script {
1588                    // The program's value lands in the hidden `<ret>` local.
1589                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1590                } else {
1591                    self.emit(Opcode::Drop, &[]);
1592                }
1593                // Restored last: the trailing `drop` is part of the statement, and in the
1594                // reference it simply inherits whatever the expression last recorded.
1595                self.state().cur_pos = saved;
1596            }
1597            StmtKind::Block(body) => {
1598                // The block's declarations were hoisted with its enclosing
1599                // statement list, so there is nothing left to declare here.
1600                let key = stmt.span.start.offset as u64;
1601                let parent = self.cur().current_block;
1602                self.push_block(key, parent);
1603                self.emit_scope_enter(key);
1604                // A block is where a `using` region lives, so its statements have to go
1605                // through `stmts`: that is what emits the disposal epilogue.
1606                self.stmts(body)?;
1607                self.emit_scope_leave(key);
1608                self.state().current_block = parent;
1609            }
1610            StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1611            // A function declaration was already instantiated when its scope was
1612            // entered, so the statement itself emits nothing.
1613            StmtKind::FuncDecl(_) => {}
1614            StmtKind::If { test, cons, alt } => {
1615                self.reset_value();
1616                let else_label = self.new_label();
1617                let end_label = self.new_label();
1618                self.expr(test)?;
1619                self.emit_jump(Opcode::IfFalse, else_label, &[]);
1620                self.stmt(cons)?;
1621                if alt.is_some() {
1622                    self.emit_jump(Opcode::Goto, end_label, &[]);
1623                }
1624                self.place_label(else_label);
1625                if let Some(alt) = alt {
1626                    self.stmt(alt)?;
1627                    self.place_label(end_label);
1628                }
1629            }
1630            StmtKind::While { test, body } => {
1631                self.reset_value();
1632                let top = self.new_label();
1633                let end = self.new_label();
1634                self.place_label(top);
1635                self.expr(test)?;
1636                // The condition's false branch and `break` share one target,
1637                // which is why a `while` loop needs only one end label.
1638                self.emit_jump(Opcode::IfFalse, end, &[]);
1639                self.loop_body(body, labels, top, end)?;
1640                self.emit_jump(Opcode::Goto, top, &[]);
1641                self.place_label(end);
1642            }
1643            StmtKind::DoWhile { body, test } => {
1644                self.reset_value();
1645                let top = self.new_label();
1646                let cont = self.new_label();
1647                let end = self.new_label();
1648                self.place_label(top);
1649                // `continue` in a `do…while` runs the test, so it lands on `cont`
1650                // rather than on the loop head.
1651                self.loop_body(body, labels, cont, end)?;
1652                self.place_label(cont);
1653                self.expr(test)?;
1654                self.emit_jump(Opcode::IfTrue, top, &[]);
1655                self.place_label(end);
1656            }
1657            StmtKind::For {
1658                init,
1659                test,
1660                update,
1661                body,
1662            } => {
1663                self.reset_value();
1664                let for_key = stmt.span.start.offset as u64;
1665                let for_parent = self.cur().current_block;
1666                self.push_block(for_key, for_parent);
1667                self.emit_scope_enter(for_key);
1668                if let Some(init) = init {
1669                    match init {
1670                        ForInit::VarDecl(decl) => {
1671                            self.var_decl(decl)?;
1672                        }
1673                        ForInit::Expr(expr) => {
1674                            // The head's value is discarded. Saying so lets an
1675                            // assignment store with `put` instead of `dup`+`put`, which
1676                            // is what the reference emits — and the difference matters:
1677                            // a `dup`/`drop` pair around the store gives the peephole a
1678                            // chance to fold the store into the *condition's* read.
1679                            self.state().discard_value = true;
1680                            let result = self.expr(expr);
1681                            self.state().discard_value = false;
1682                            result?;
1683                            if !std::mem::take(&mut self.state().no_value) {
1684                                self.emit(Opcode::Drop, &[]);
1685                            }
1686                        }
1687                    }
1688                }
1689                // A `let`/`const` in the head gets a *fresh binding per iteration*,
1690                // so a closure made in the body captures that iteration's value
1691                // instead of sharing one. The reference expresses this with
1692                // `close_loc`, which swaps in a new reference cell holding the
1693                // current value; the three points below are the ones it uses — after
1694                // the initialiser, before the update, and after the loop.
1695                let loop_bindings = match init {
1696                    Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
1697                        let mut names: Vec<String> = Vec::new();
1698                        for declarator in &decl.declarators {
1699                            let mut idents = Vec::new();
1700                            declarator.target.bound_names(&mut idents);
1701                            names.extend(idents.into_iter().map(|ident| ident.name));
1702                        }
1703                        names
1704                    }
1705                    _ => Vec::new(),
1706                };
1707                // The reference also closes right after the initialiser, so the first
1708                // iteration's closures get their own cell rather than sharing the one
1709                // the initialiser wrote into.
1710                for name in &loop_bindings {
1711                    let pos = self.cur().cur_pos;
1712                    self.state().insns.push(Insn::CloseCaptured {
1713                        name: name.clone(),
1714                        block: for_key,
1715                    });
1716                    self.state().insn_pos.push(pos);
1717                }
1718                let top = self.new_label();
1719                let cont = self.new_label();
1720                let end = self.new_label();
1721                self.place_label(top);
1722                if let Some(test) = test {
1723                    self.expr(test)?;
1724                    self.emit_jump(Opcode::IfFalse, end, &[]);
1725                }
1726                // `continue` runs the update expression first, so it lands on
1727                // `cont`, which sits just before the update.
1728                self.loop_body(body, labels, cont, end)?;
1729                self.place_label(cont);
1730                // Each iteration ends with a fresh cell, so the closures the body just
1731                // created keep the cell they captured and the update writes to a new
1732                // one. Without this every closure in the loop shares one binding.
1733                let binding_block = for_key;
1734                for name in &loop_bindings {
1735                    let pos = self.cur().cur_pos;
1736                    self.state().insns.push(Insn::CloseCaptured {
1737                        name: name.clone(),
1738                        block: binding_block,
1739                    });
1740                    self.state().insn_pos.push(pos);
1741                }
1742                if let Some(update) = update {
1743                    self.state().discard_value = true;
1744                    let result = self.expr(update);
1745                    self.state().discard_value = false;
1746                    result?;
1747                    if !std::mem::take(&mut self.state().no_value) {
1748                        self.emit(Opcode::Drop, &[]);
1749                    }
1750                }
1751                self.emit_jump(Opcode::Goto, top, &[]);
1752                self.place_label(end);
1753                self.emit_scope_leave(for_key);
1754                self.state().current_block = for_parent;
1755            }
1756            StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1757            StmtKind::Throw(expr) => {
1758                self.expr(expr)?;
1759                self.emit(Opcode::Throw, &[]);
1760            }
1761            StmtKind::Break(_) | StmtKind::Continue(_) => {
1762                // Labels and loops are wired up in a later milestone; a bare
1763                // break/continue jumps to the innermost enclosing target, which
1764                // the loop helpers register.
1765                self.control_transfer(stmt)?;
1766            }
1767            StmtKind::Labeled { label, body } => {
1768                self.labeled(label, body, stmt)?;
1769            }
1770            StmtKind::Switch {
1771                discriminant,
1772                cases,
1773            } => {
1774                self.switch(discriminant, cases, stmt)?;
1775            }
1776            StmtKind::Try {
1777                block,
1778                handler,
1779                finalizer,
1780            } => {
1781                self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
1782            }
1783            StmtKind::ForIn { left, right, body } => {
1784                self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
1785            }
1786            StmtKind::ForOf {
1787                left,
1788                right,
1789                body,
1790                is_await,
1791            } => {
1792                let kind = if *is_await {
1793                    ForLoopKind::AwaitOf
1794                } else {
1795                    ForLoopKind::Of
1796                };
1797                self.for_in_of(stmt, left, right, body, kind, labels)?;
1798            }
1799            StmtKind::With { object, body } => self.with_stmt(object, body)?,
1800            StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
1801            // `import` emits nothing: hoisting already bound its names, and the host
1802            // fills their cells before the body runs.
1803            StmtKind::Import(_) => {}
1804            StmtKind::Export(decl) => self.export_stmt(decl)?,
1805        }
1806        Ok(())
1807    }
1808
1809    /// Compile `return`, running every enclosing finalizer on the way out.
1810    ///
1811    /// `nip_catch` is what makes this possible: it discards everything on the stack
1812    /// down to and including the `catch` offset while keeping the return value on
1813    /// top, so the frame the finalizer sees has the same shape as on the normal
1814    /// path.
1815    fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
1816        let mut has_value = value.is_some();
1817        if let Some(expr) = value {
1818            // `return f(x)` is a tail call *only* when nothing has to happen to the
1819            // value afterwards. A `finally` or an open iterator in scope forces the
1820            // normal path, because the cleanup has to run after the call returns —
1821            // which is exactly what a tail call refuses to do.
1822            let plain = self
1823                .cur()
1824                .jump_targets
1825                .iter()
1826                .all(|target| target.finally_label.is_none() && !target.has_iterator);
1827            if plain && self.expr_if_tail_call(expr)? {
1828                return Ok(());
1829            }
1830            self.expr(expr)?;
1831        }
1832        // `return v` in an *async generator* awaits `v` before anything else happens —
1833        // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
1834        // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
1835        // exactly that reason ("the await must be done before handling the finally in case
1836        // it raises an exception").
1837        if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
1838            self.emit(Opcode::Await, &[]);
1839            self.state().has_await = true;
1840        }
1841        has_value = self.emit_unwind_for_return(has_value);
1842        // A generator or async function does not return to its caller: it either
1843        // finishes, and the value becomes `{value, done: true}`, or it suspends.
1844        // `return_async` is the "finished" half, and it reads the value off the stack
1845        // rather than carrying it, which is what the resume machinery expects.
1846        if self.cur().is_suspending() {
1847            if !has_value {
1848                self.emit(Opcode::Undefined, &[]);
1849            }
1850            self.emit(Opcode::ReturnAsync, &[]);
1851            return Ok(());
1852        }
1853        if has_value {
1854            self.emit(Opcode::Return, &[]);
1855        } else {
1856            self.emit(Opcode::ReturnUndef, &[]);
1857        }
1858        Ok(())
1859    }
1860
1861    /// Close an iterator: the reference's `emit_iterator_close`.
1862    ///
1863    /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
1864    /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
1865    /// sequence, and three details in it are load-bearing:
1866    ///
1867    /// * the iterator object is compared against `undefined` first, because a loop that
1868    ///   ran to completion clears that slot rather than closing an exhausted iterator;
1869    /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
1870    /// * `preserve_completion` keeps whatever was underneath (the return value of the
1871    ///   function being left), which is why one branch ends on `nip` and the other on `drop`.
1872    fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
1873        if !is_async {
1874            if preserve_completion {
1875                self.emit(Opcode::Rot3r, &[]);
1876                self.emit(Opcode::Undefined, &[]);
1877            }
1878            self.emit(Opcode::IteratorClose, &[]);
1879            return;
1880        }
1881        if preserve_completion {
1882            // `iter next completion -> completion iter`
1883            self.emit(Opcode::Nip, &[]);
1884            self.emit(Opcode::Swap, &[]);
1885        } else {
1886            // `iter next catch_offset -> iter`
1887            self.emit(Opcode::Drop, &[]);
1888            self.emit(Opcode::Drop, &[]);
1889        }
1890        let done = self.new_label();
1891        let no_return = self.new_label();
1892        self.emit(Opcode::Dup, &[]);
1893        self.emit(Opcode::IsUndefined, &[]);
1894        self.emit_jump(Opcode::IfTrue, done, &[]);
1895        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
1896        self.emit(Opcode::Dup, &[]);
1897        self.emit(Opcode::IsUndefinedOrNull, &[]);
1898        self.emit_jump(Opcode::IfTrue, no_return, &[]);
1899        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
1900        self.emit(Opcode::Await, &[]);
1901        self.state().has_await = true;
1902        self.emit_jump(Opcode::Goto, done, &[]);
1903        self.place_label(no_return);
1904        self.emit(Opcode::Drop, &[]);
1905        self.place_label(done);
1906        self.emit(Opcode::Drop, &[]);
1907    }
1908
1909    /// Emit the finalizer/iterator cleanup for leaving the current position with a
1910    /// return, and report whether a value is now on the stack for it to carry.
1911    ///
1912    /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
1913    /// enclosing `finally` at once, and the two used to be separate — the `yield` path
1914    /// simply emitted `return_async`, so `it.return()` ended the generator without ever
1915    /// running `finally` blocks the body was sitting inside.
1916    fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
1917        let targets = self.cur().jump_targets.clone();
1918        for target in targets.iter().rev() {
1919            if target.finally_label.is_none() && !target.has_iterator {
1920                continue;
1921            }
1922            if !has_value {
1923                // The cleanup expects a value to pass through; with nothing to
1924                // return, `undefined` stands in.
1925                self.emit(Opcode::Undefined, &[]);
1926                has_value = true;
1927            }
1928            self.emit(Opcode::NipCatch, &[]);
1929            if target.has_iterator {
1930                // Rewind to the loop's own slots and hand the close a dummy catch offset:
1931                // the loop is being abandoned, so there is nothing left to catch.
1932                self.emit_iterator_close(target.is_async_iterator, true);
1933            } else if let Some(finally) = target.finally_label {
1934                self.emit_jump(Opcode::Gosub, finally, &[]);
1935            }
1936        }
1937        has_value
1938    }
1939
1940    /// Compile a statement list, stopping at the first statement that cannot
1941    /// fall through.
1942    fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
1943        for (index, stmt) in body.iter().enumerate() {
1944            // A `using` declaration is not just a binding: everything after it, to the end
1945            // of the list, runs inside its disposal region. Compiling the rest of the list
1946            // recursively is what gives nested regions their innermost-first order.
1947            if Self::using_declaration(stmt).is_some() {
1948                return self.using_region(stmt, &body[index + 1..]);
1949            }
1950            self.stmt(stmt)?;
1951            if Self::terminates(stmt) {
1952                break;
1953            }
1954        }
1955        Ok(())
1956    }
1957
1958    /// The declaration a `using` statement carries, if it is one.
1959    fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
1960        match &stmt.kind {
1961            StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
1962            _ => None,
1963        }
1964    }
1965
1966    /// Compile `decl` and then the rest of its block, disposing when the block ends.
1967    ///
1968    /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
1969    /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
1970    /// exception — and this engine already funnels all of those through `catch` plus
1971    /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
1972    /// `return` and `break` dispose without knowing anything about `using`.
1973    ///
1974    /// ```text
1975    ///   <declaration>              value -> x, method -> x+1
1976    ///   catch CATCH                <- an exception in the rest lands here
1977    /// REST:
1978    ///   <the rest of the block>
1979    ///   drop                       <- the catch offset, on the fall-through path
1980    ///   undefined; gosub DISPOSE; drop
1981    ///   goto END
1982    /// CATCH:
1983    ///   using_dispose x            <- merges the failure into the pending exception
1984    ///   throw
1985    /// DISPOSE:
1986    ///   using_dispose_init
1987    ///   using_dispose x
1988    ///   using_dispose_end          <- rethrows if a dispose failed
1989    ///   ret
1990    /// END:
1991    /// ```
1992    fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
1993        let Some(decl) = Self::using_declaration(stmt) else {
1994            unreachable!("using_region is only called for a using declaration");
1995        };
1996        // `using` binds exactly one name and has no pattern form, which the parser
1997        // enforces; the region still has to know *which* slot to dispose.
1998        let name = decl
1999            .declarators
2000            .first()
2001            .and_then(|declarator| match &declarator.target.kind {
2002                PatternKind::Ident(ident) => Some(ident.name.clone()),
2003                _ => None,
2004            });
2005        self.stmt(stmt)?;
2006        let Some(name) = name else {
2007            // Unreachable for a well-formed `using`, but a bare `using` with no declarator
2008            // must not make the compiler panic.
2009            return self.stmts(rest);
2010        };
2011        let Some(value_slot) = self.using_value_slot(&name) else {
2012            // Declared globally, which the parser rules out for a script; a module's
2013            // top level is a scope, and there the disposal stays a known gap.
2014            return self.stmts(rest);
2015        };
2016        // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
2017        // exit path already disposed.
2018        let live = !rest.last().is_some_and(Self::terminates);
2019        self.using_region_around(value_slot, live, |compiler| compiler.stmts(rest))
2020    }
2021
2022    /// The slot a `using` binding's value lives in.
2023    fn using_value_slot(&self, name: &str) -> Option<u32> {
2024        self.cur()
2025            .vars
2026            .iter()
2027            .position(|var| var.name == name && var.kind == VarKind::Using)
2028            .map(|index| index as u32)
2029    }
2030
2031    /// Wrap `inside` in a disposal region for the resource in `value_slot`.
2032    ///
2033    /// Shared between a `using` statement — which owns the rest of its block — and a
2034    /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
2035    /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
2036    /// the end, `return`, `break`, `continue`, and an exception — and this engine already
2037    /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
2038    /// target with a `finally_label` is what makes `return` and `break` dispose without
2039    /// knowing anything about `using`.
2040    ///
2041    /// ```text
2042    ///   catch CATCH                <- an exception inside lands here
2043    ///   <inside>
2044    ///   drop                       <- the catch offset, on the fall-through path
2045    ///   undefined; gosub DISPOSE; drop
2046    ///   goto END
2047    /// CATCH:
2048    ///   using_dispose slot         <- merges the failure into the pending exception
2049    ///   throw
2050    /// DISPOSE:
2051    ///   using_dispose_init
2052    ///   using_dispose slot
2053    ///   using_dispose_end          <- rethrows if a dispose failed
2054    ///   ret
2055    /// END:
2056    /// ```
2057    fn using_region_around(
2058        &mut self,
2059        value_slot: u32,
2060        live: bool,
2061        inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
2062    ) -> Result<(), SyntaxError> {
2063        let catch_label = self.new_label();
2064        let end_label = self.new_label();
2065        let dispose_label = self.new_label();
2066
2067        self.emit_jump(Opcode::Catch, catch_label, &[]);
2068        self.push_jump_target(JumpTarget {
2069            names: Vec::new(),
2070            break_label: None,
2071            continue_label: None,
2072            // The catch offset is the one thing on the stack that leaving has to remove.
2073            drop_count: 1,
2074            finally_label: Some(dispose_label),
2075            is_regular_stmt: false,
2076            has_iterator: false,
2077            is_async_iterator: false,
2078        });
2079        inside(self)?;
2080        self.pop_jump_target();
2081
2082        if live {
2083            self.emit(Opcode::Drop, &[]);
2084            self.emit(Opcode::Undefined, &[]);
2085            self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2086            self.emit(Opcode::Drop, &[]);
2087            self.emit_jump(Opcode::Goto, end_label, &[]);
2088        }
2089
2090        // An exception unwinds to here with the thrown value on the stack, which is exactly
2091        // the shape `using_dispose` expects as its error state.
2092        self.place_label(catch_label);
2093        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2094        self.emit(Opcode::Throw, &[]);
2095
2096        self.place_label(dispose_label);
2097        // Inside the subroutine the return value and the `gosub` return address are both
2098        // live, and neither an outer finalizer nor another region may run before this one
2099        // has finished.
2100        self.push_jump_target(JumpTarget {
2101            names: Vec::new(),
2102            break_label: None,
2103            continue_label: None,
2104            drop_count: 2,
2105            finally_label: None,
2106            is_regular_stmt: false,
2107            has_iterator: false,
2108            is_async_iterator: false,
2109        });
2110        self.emit(Opcode::UsingDisposeInit, &[]);
2111        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2112        self.emit(Opcode::UsingDisposeEnd, &[]);
2113        self.pop_jump_target();
2114        self.emit(Opcode::Ret, &[]);
2115        self.place_label(end_label);
2116        Ok(())
2117    }
2118
2119    /// Declare every name a statement list introduces, before compiling any of
2120    /// it, so a reference that appears textually before a declaration still
2121    /// resolves.
2122    ///
2123    /// Declarations are walked in source order because that is the order the
2124    /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2125    /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2126    /// declarations hoist out to the function scope; lexical names belong to the
2127    /// block they were written in, which `block` records.
2128    fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2129        let saved = self.cur().current_block;
2130        self.state().current_block = block;
2131        let result = self.hoist_list(body);
2132        // Only now is every binding of this scope known, so the deferred function
2133        // bodies can be compiled against the finished list. Compiled at its own
2134        // declaration instead, a body that names a `var` written further down would
2135        // have resolved that name as a global.
2136        if result.is_ok() {
2137            let deferred = std::mem::take(&mut self.state().deferred_funcs);
2138            let mut outcome = Ok(());
2139            for (owner, func) in deferred {
2140                let previous = self.cur().current_block;
2141                self.state().current_block = owner;
2142                outcome = self.func_decl(&func);
2143                self.state().current_block = previous;
2144                if outcome.is_err() {
2145                    break;
2146                }
2147            }
2148            self.state().current_block = saved;
2149            return outcome;
2150        }
2151        // `current_block` is restored by the caller for a block statement, since
2152        // it needs it set while compiling; only clean up on the hoist path.
2153        self.state().current_block = saved;
2154        result
2155    }
2156
2157    fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2158        for stmt in body {
2159            self.hoist_stmt(stmt)?;
2160        }
2161        Ok(())
2162    }
2163
2164    /// Whether a statement always transfers control away, making everything after
2165    /// it in the same list unreachable.
2166    ///
2167    /// The reference drops such statements in `skip_dead_code`, so `return 1;
2168    /// let x = 2;` compiles to the same bytecode as `return 1;`.
2169    fn terminates(stmt: &Stmt) -> bool {
2170        matches!(
2171            stmt.kind,
2172            StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2173        )
2174    }
2175
2176    fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2177        match &stmt.kind {
2178            StmtKind::VarDecl(decl) => {
2179                for declarator in &decl.declarators {
2180                    let mut names = Vec::new();
2181                    declarator.target.bound_names(&mut names);
2182                    for name in names {
2183                        let text = name.name.clone();
2184                        if decl.kind == VarDeclKind::Var {
2185                            let def = VarDef::var(text.clone());
2186                            self.declare_var(&text, def);
2187                        } else if decl.kind.is_using() {
2188                            // Two adjacent slots: the resource, then the dispose method
2189                            // snapshotted at declaration. `using_dispose` reads them as a
2190                            // pair `(slot, slot + 1)`, so nothing may be declared between
2191                            // them — which is why both are declared here, in one step,
2192                            // rather than the method being added at emission time.
2193                            self.declare_using(&text);
2194                        } else {
2195                            let def = if decl.kind == VarDeclKind::Const {
2196                                VarDef::constant(text.clone())
2197                            } else {
2198                                VarDef::lexical(text.clone())
2199                            };
2200                            self.declare(&text, def);
2201                        }
2202                    }
2203                }
2204            }
2205            StmtKind::FuncDecl(func) => {
2206                if let Some(name) = &func.name {
2207                    // A function declaration is a `var` binding that happens to
2208                    // hold a function, not a lexical one.
2209                    let def = VarDef::var(name.name.clone());
2210                    self.declare_var(&name.name.clone(), def);
2211                }
2212                // The function object is created when the scope is entered, so it
2213                // exists before the declaration is reached. Its body is compiled
2214                // *after* this scope's hoisting finishes, so a name it uses resolves
2215                // even when the `var` that declares it comes later in the source.
2216                let owner = self.cur().current_block;
2217                self.state().deferred_funcs.push((owner, func.clone()));
2218            }
2219            StmtKind::ClassDecl(class) => {
2220                if let Some(name) = &class.name {
2221                    self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2222                }
2223            }
2224            // A module's imports are bound before any of its code runs, and its exports
2225            // declare the very bindings they export — so both hoist the declarations
2226            // their `StmtKind` arm will later emit code for.
2227            StmtKind::Import(decl) => self.hoist_import(decl)?,
2228            StmtKind::Export(decl) => self.hoist_export(decl)?,
2229            StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2230            StmtKind::If { cons, alt, .. } => {
2231                self.hoist_stmt(cons)?;
2232                if let Some(alt) = alt {
2233                    self.hoist_stmt(alt)?;
2234                }
2235            }
2236            StmtKind::While { body, .. }
2237            | StmtKind::DoWhile { body, .. }
2238            | StmtKind::Labeled { body, .. }
2239            | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2240            StmtKind::For { init, body, .. } => {
2241                // A `for` head gets its own scope even when it declares nothing,
2242                // because `let` in the head is scoped to the loop.
2243                let key = stmt.span.start.offset as u64;
2244                let parent = self.cur().current_block;
2245                self.push_block(key, parent);
2246                if let Some(init) = init
2247                    && let ForInit::VarDecl(decl) = init
2248                {
2249                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2250                }
2251                self.hoist_stmt(body)?;
2252                self.state().current_block = parent;
2253            }
2254            StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
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 ForHead::VarDecl(decl) = left {
2259                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2260                }
2261                self.hoist_stmt(body)?;
2262                self.state().current_block = parent;
2263            }
2264            StmtKind::Try {
2265                block,
2266                handler,
2267                finalizer,
2268            } => {
2269                self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2270                let try_parent = self.cur().current_block;
2271                if let Some(handler) = handler {
2272                    // The catch parameter belongs to the function scope, not to a
2273                    // block: it is a `catch` binding rather than a `let`, so it is
2274                    // never in the temporal dead zone and `emit_scope_enter` must
2275                    // not mark it uninitialised. It still has to be declared before
2276                    // the handler body is hoisted, so it takes the slot the
2277                    // reference gives it (bindings are numbered in source order).
2278                    if let Some(pattern) = &handler.param {
2279                        // The parameter gets its own scope, so entering the handler
2280                        // does not have to re-declare it. It is not lexical, so it
2281                        // is never marked uninitialised.
2282                        let key = Self::try_block_key(stmt, TryPart::Param);
2283                        let parent = self.cur().current_block;
2284                        self.push_block(key, parent);
2285                        // A destructuring parameter binds several names, one slot each,
2286                        // in the order they are written. The reference declares those as
2287                        // `let`s rather than as one `catch` binding — its dump prints
2288                        // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2289                        // so the kind follows the shape of the parameter.
2290                        //
2291                        // Neither form is in the dead zone: the stores run as the handler
2292                        // is entered, so both use the unchecked `put_loc`.
2293                        let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2294                        let mut names = Vec::new();
2295                        pattern.bound_names(&mut names);
2296                        for name in names {
2297                            let def = VarDef {
2298                                name: name.name.clone(),
2299                                is_const: false,
2300                                is_lexical: destructures,
2301                                kind: if destructures {
2302                                    crate::bytecode::VarKind::LexicalCatch
2303                                } else {
2304                                    crate::bytecode::VarKind::Catch
2305                                },
2306                                is_captured: false,
2307                                scope_level: 0,
2308                                scope_next: None,
2309                            };
2310                            self.declare_local(&name.name.clone(), def);
2311                        }
2312                        // The handler body nests inside the parameter's scope, so the
2313                        // body's bindings chain on to the parameter (the reference
2314                        // prints `let y [next:1]`, pointing at `e`).
2315                        self.state().current_block = key;
2316                    }
2317                    self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2318                    // Back to the block the `try` itself lives in, so the finalizer
2319                    // is a sibling of the handler rather than nested in it.
2320                    self.state().current_block = try_parent;
2321                }
2322                if let Some(finalizer) = finalizer {
2323                    self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2324                }
2325            }
2326            StmtKind::Switch { cases, .. } => {
2327                let key = stmt.span.start.offset as u64;
2328                let parent = self.cur().current_block;
2329                self.push_block(key, parent);
2330                for case in cases {
2331                    self.hoist_list(&case.body)?;
2332                }
2333                self.state().current_block = parent;
2334            }
2335            _ => {}
2336        }
2337        Ok(())
2338    }
2339
2340    /// Hoist a nested statement list, which is its own lexical scope.
2341    fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2342        let parent = self.cur().current_block;
2343        self.push_block(key, parent);
2344        self.hoist_list(body)?;
2345        self.state().current_block = parent;
2346        Ok(())
2347    }
2348
2349    /// A block key for one part of a `try` statement.
2350    ///
2351    /// The three parts are three separate scopes, so they cannot share the key a
2352    /// statement's own offset would give them: the try block, the handler body and
2353    /// the finalizer would then look like one scope, and their `let` bindings would
2354    /// be marked uninitialised only on entering the first of them.
2355    fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2356        (stmt.span.start.offset as u64) * 4 + part as u64
2357    }
2358
2359    /// Declare a `var`: it lives in the function's own scope, not the block's.
2360    fn declare_var(&mut self, name: &str, def: VarDef) {
2361        if self.cur().is_module {
2362            self.declare_module(name, &def);
2363            return;
2364        }
2365        if self.cur().declares_globally(&def) {
2366            self.declare_global(name, &def);
2367            return;
2368        }
2369        let state = self.state();
2370        // A binding of the *parameter* scope does not count: the body's `var` of the
2371        // same name is a different binding and needs a slot of its own.
2372        if state.vars.iter().enumerate().any(|(index, v)| {
2373            v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
2374        }) {
2375            return;
2376        }
2377        // A `var` belongs to the function scope, never to the enclosing block.
2378        state.var_block.push(FUNCTION_SCOPE);
2379        state.vars.push(def);
2380    }
2381
2382    /// Declare `name` as a binding of the parameter scope, returning its slot.
2383    fn declare_param_var(&mut self, name: &str) -> u32 {
2384        declare_param_var_at(self.state(), name)
2385    }
2386
2387    /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2388    ///
2389    /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2390    /// so each points at the one declared before it and the oldest ends the chain with
2391    /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2392    /// runtime walks when it instantiates them.
2393    fn declare_param_binding(&mut self, name: &str) -> u32 {
2394        let state = self.state();
2395        let previous = state
2396            .vars
2397            .iter()
2398            .enumerate()
2399            .rev()
2400            .find(|(index, var)| {
2401                state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2402            })
2403            .map(|(index, _)| index as i32);
2404        let index = state.vars.len() as u32;
2405        state.var_block.push(PARAM_SCOPE);
2406        let mut def = VarDef::lexical(name);
2407        // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2408        // the function's, and its bindings are initialised one by one rather than all at
2409        // once — which is exactly what the dead zone needs.
2410        def.scope_level = 1;
2411        def.scope_next = Some(previous.unwrap_or(-2));
2412        state.vars.push(def);
2413        index
2414    }
2415
2416    /// The slot of a parameter-list binding, if the list has one by that name.
2417    fn param_binding_slot(&self, name: &str) -> Option<u32> {
2418        let state = self.cur();
2419        state
2420            .vars
2421            .iter()
2422            .enumerate()
2423            .position(|(index, var)| {
2424                var.name == name
2425                    && var.is_lexical
2426                    && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2427            })
2428            .map(|index| index as u32)
2429    }
2430
2431    /// Every parameter-list binding, in declaration order.
2432    fn param_binding_names(&self) -> Vec<String> {
2433        let state = self.cur();
2434        state
2435            .vars
2436            .iter()
2437            .enumerate()
2438            .filter(|(index, var)| {
2439                var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2440            })
2441            .map(|(_, var)| var.name.clone())
2442            .collect()
2443    }
2444
2445    /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2446    fn body_var_slot(&self, name: &str) -> Option<u32> {
2447        let state = self.cur();
2448        state
2449            .vars
2450            .iter()
2451            .enumerate()
2452            .find(|(index, var)| {
2453                var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2454            })
2455            .map(|(index, _)| index as u32)
2456    }
2457
2458    /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2459    /// one.
2460    ///
2461    /// With parameter expressions the reference creates two: an unmapped one in the
2462    /// argument scope, for the defaults and anything they close over, and the body's own.
2463    /// They are separate bindings, which is what makes
2464    /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2465    /// report 1 from `p` and 2 from the body.
2466    fn provide_param_arguments(&mut self) {
2467        if !self.cur().has_parameter_expressions {
2468            return;
2469        }
2470        let mentioned = self.cur().needs_param_arguments
2471            || self
2472                .cur()
2473                .insns
2474                .iter()
2475                .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2476        if !mentioned {
2477            return;
2478        }
2479        let slot = self.declare_param_var("arguments");
2480        let magic = if self.cur().strict || !self.cur().simple_parameter_list {
2481            0
2482        } else {
2483            1
2484        };
2485        self.prepend_initialiser_to(
2486            slot,
2487            Insn::Fixed {
2488                op: Opcode::SpecialObject,
2489                operands: vec![Op::Int(magic)],
2490            },
2491        );
2492    }
2493
2494    /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2495    fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2496        let current = self.stack.len() - 1;
2497        let init = [
2498            producer,
2499            Insn::Fixed {
2500                op: Opcode::PutLoc,
2501                operands: vec![Op::Slot(Slot::Loc(slot))],
2502            },
2503        ];
2504        let inserted = init.len();
2505        for (index, instruction) in init.into_iter().enumerate() {
2506            self.stack[current].insns.insert(index, instruction);
2507        }
2508        for placed in self.stack[current].labels.iter_mut().flatten() {
2509            *placed += inserted;
2510        }
2511        self.state().label_since_insn = false;
2512    }
2513
2514    /// Give the function an `arguments` binding if its body mentions one.
2515    ///
2516    /// The check runs on the *instruction* stream rather than the AST: by this point
2517    /// every reference has become an `Insn::Var`, so scanning is exact and needs no
2518    /// AST walker. Declaring lazily matters for more than tidiness — always declaring
2519    /// would renumber every later local slot and stop the bytecode matching the
2520    /// reference, which only adds the binding when the body uses it.
2521    ///
2522    /// `arguments` is a local, initialised at the top of the body by
2523    /// `special_object`; that is the reference's shape, so the disassembly agrees.
2524    fn provide_arguments(&mut self) {
2525        let current = self.stack.len() - 1;
2526        if self.stack[current].is_script || self.stack[current].is_module {
2527            // A module has no `arguments` binding; referring to it is a ReferenceError,
2528            // which is exactly what an unbound name produces.
2529            return;
2530        }
2531        // An arrow has no `arguments` of its own: the binding belongs to the enclosing
2532        // function, which is why `() => arguments` sees the caller's arguments.
2533        if self.stack[current].is_arrow {
2534            if self.mentions("arguments") {
2535                self.ensure_enclosing_arguments();
2536            }
2537            return;
2538        }
2539        // Only a *body* mention needs the body's binding: the parameter list has one of
2540        // its own (see [`Compiler::provide_param_arguments`]).
2541        //
2542        // `delete arguments` counts too: it compiles to `DeleteVar`, which is not a
2543        // `Var`, so without this the body got no binding at all — the name resolved to
2544        // the global object and `delete` answered `true` for a binding that cannot be
2545        // deleted. The reference answers `false`.
2546        let mentioned = self.cur().insns.iter().any(|insn| match insn {
2547            Insn::Var {
2548                name, in_params, ..
2549            } => name == "arguments" && !*in_params,
2550            Insn::DeleteVar { name } => name == "arguments",
2551            _ => false,
2552        });
2553        if !mentioned && !self.cur().needs_arguments_local {
2554            return;
2555        }
2556        // The request may have come only from a parameter-list arrow, in which case the
2557        // parameter scope's binding already answers for it and the body needs none.
2558        if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
2559            return;
2560        }
2561        // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`.
2562        //
2563        // With parameter expressions the list and the body are separate environments, so
2564        // an assignment to a parameter cannot be reflected into `arguments` at all — the
2565        // arguments object is unmapped whatever the mode, which is why the reference emits
2566        // `special_object 0` here even in sloppy code.
2567        // A non-simple parameter list (`[a]`, `...rest`, `a = 1`) makes the arguments
2568        // object unmapped whatever the mode — §10.4.4 keys the decision on
2569        // `IsSimpleParameterList`, not on strictness alone.
2570        let magic = if self.stack[current].strict || !self.stack[current].simple_parameter_list {
2571            0
2572        } else {
2573            1
2574        };
2575        // A mapped `arguments` shares storage with the parameters: `arguments[0] = 2`
2576        // has to be visible as `a`, and assigning `a` has to be visible as `arguments[0]`.
2577        // The only storage both sides can see is a reference cell, so every parameter the
2578        // object maps gets one — even a parameter no closure captured. Without this the
2579        // slot holds a plain copy and the mapping has nothing to write through.
2580        if magic == 1 {
2581            for arg in &mut self.stack[current].args {
2582                arg.is_captured = true;
2583            }
2584        }
2585        self.prepend_binding("arguments", magic);
2586    }
2587
2588    /// Whether a *body* instruction refers to `arguments`.
2589    fn body_mentions_arguments(&self) -> bool {
2590        self.cur()
2591            .insns
2592            .iter()
2593            .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
2594    }
2595
2596    /// Whether the function body's instruction stream refers to `name`.
2597    fn mentions(&self, name: &str) -> bool {
2598        let current = self.stack.len() - 1;
2599        // A binding of the parameter scope does not answer for the body: the body's own
2600        // `arguments` (or self-name) still has to be provided for it.
2601        if self.stack[current]
2602            .vars
2603            .iter()
2604            .enumerate()
2605            .any(|(index, v)| {
2606                v.name == name
2607                    && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
2608            })
2609        {
2610            return false;
2611        }
2612        self.stack[current]
2613            .insns
2614            .iter()
2615            .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
2616    }
2617
2618    /// Bind the name a named function expression uses to refer to itself.
2619    ///
2620    /// The value is `special_object 2`, the function currently running, so the binding
2621    /// is the closure itself and not a copy. It is a local of this function, which is
2622    /// what keeps `g` out of the enclosing scope.
2623    /// Give the function a local `this`, for an arrow inside it to capture.
2624    fn provide_this_local(&mut self) {
2625        let current = self.stack.len() - 1;
2626        if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
2627            return;
2628        }
2629        if !self.stack[current]
2630            .vars
2631            .iter()
2632            .any(|var| var.name == "this")
2633        {
2634            self.declare_hidden_local("this", VarKind::Normal);
2635        }
2636        self.prepend_initialiser(
2637            "this",
2638            Insn::Fixed {
2639                op: Opcode::PushThis,
2640                operands: vec![],
2641            },
2642        );
2643    }
2644
2645    /// Give the function a local `<home_object>`, for an arrow or a static block inside it
2646    /// to read through `super`.
2647    fn provide_home_object_local(&mut self) {
2648        let current = self.stack.len() - 1;
2649        if !self.stack[current].needs_home_object_local {
2650            return;
2651        }
2652        if !self.stack[current]
2653            .vars
2654            .iter()
2655            .any(|var| var.name == HOME_OBJECT)
2656        {
2657            self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
2658        }
2659        self.prepend_initialiser(
2660            HOME_OBJECT,
2661            Insn::Fixed {
2662                op: Opcode::SpecialObject,
2663                operands: vec![Op::Int(4)],
2664            },
2665        );
2666    }
2667
2668    fn provide_self_name(&mut self) {
2669        let current = self.stack.len() - 1;
2670        let Some(name) = self.stack[current].self_name.clone() else {
2671            return;
2672        };
2673        if self.stack[current].self_name_initialized {
2674            return;
2675        }
2676        // Either the body refers to the name, or a nested function already forced the
2677        // binding into existence while being resolved. A direct `eval` can name it
2678        // without mentioning it, so its presence is a third reason: in strict mode
2679        // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
2680        // that only happens if the binding exists.
2681        let declared = self.stack[current].vars.iter().any(|v| v.name == name);
2682        if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
2683            return;
2684        }
2685        self.stack[current].self_name_initialized = true;
2686        self.prepend_binding_with(&name, 2, VarKind::FunctionName);
2687    }
2688
2689    /// Insert `special_object magic` plus the store to `name` at the top of the body.
2690    ///
2691    /// Prepending shifts every label that has been placed, so they are all moved by
2692    /// the number of instructions inserted.
2693    fn prepend_binding(&mut self, name: &str, magic: i32) {
2694        self.prepend_binding_with(name, magic, VarKind::Normal);
2695    }
2696
2697    /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
2698    fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
2699        let current = self.stack.len() - 1;
2700        // A function-expression's own name is immutable in strict mode, which is what
2701        // makes `f = 1` inside a strict body throw instead of being dropped.
2702        let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
2703        self.declare_var(
2704            name,
2705            VarDef {
2706                kind,
2707                is_const,
2708                ..VarDef::var(name)
2709            },
2710        );
2711        let init = [
2712            Insn::Fixed {
2713                op: Opcode::SpecialObject,
2714                operands: vec![Op::Int(magic)],
2715            },
2716            Insn::Var {
2717                // An initialisation, not an assignment: sloppy mode drops stores to a
2718                // function-expression's own name, and the prologue is what puts the
2719                // value there in the first place.
2720                action: if kind == VarKind::FunctionName {
2721                    VarAction::PutInit
2722                } else {
2723                    VarAction::Put
2724                },
2725                name: name.to_string(),
2726                block: 0,
2727                in_params: false,
2728            },
2729        ];
2730        let inserted = init.len();
2731        for (index, instruction) in init.into_iter().enumerate() {
2732            self.stack[current].insns.insert(index, instruction);
2733        }
2734        for placed in self.stack[current].labels.iter_mut().flatten() {
2735            *placed += inserted;
2736        }
2737        // A store sits at the insertion point now, so the `put`/`get` fold must not
2738        // reach across it.
2739        self.stack[current].label_since_insn = true;
2740    }
2741
2742    /// Record a top-level script declaration as a global.
2743    ///
2744    /// A script's top-level `var`/`let`/`function` create properties of the
2745    /// global object, not slots in the script's frame, so they show up as closure
2746    /// variables instead.
2747    fn declare_global(&mut self, name: &str, def: &VarDef) {
2748        let state = self.state();
2749        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2750            // The name was already referenced, from a function compiled before this
2751            // declaration was reached — `function a(){ b() } function b(){}` resolves
2752            // `b` while `b` is still unknown, and that guess has to be corrected here.
2753            // Leaving it as a plain global meant the declaration was never registered,
2754            // so the binding did not exist at run time and `a()` threw
2755            // `b is not defined`.
2756            if matches!(existing.closure_type, ClosureType::Global) {
2757                existing.closure_type = ClosureType::GlobalDecl;
2758                existing.is_const = def.is_const;
2759                existing.is_lexical = def.is_lexical;
2760            }
2761            return;
2762        }
2763        state.closure_vars.push(ClosureVar {
2764            name: name.to_string(),
2765            is_const: def.is_const,
2766            is_lexical: def.is_lexical,
2767            closure_type: ClosureType::GlobalDecl,
2768            var_idx: 0,
2769        });
2770    }
2771
2772    /// Record a module-level declaration as a module variable.
2773    ///
2774    /// The binding is a closure variable of the module body, so reads and writes are
2775    /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
2776    /// *who fills the cell*: the module record does, before the body runs, and an import
2777    /// points its cell at the exporting module's, which is what makes bindings live and
2778    /// cycles work.
2779    fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
2780        let state = self.state();
2781        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2782            // The name may have been referenced before this declaration was hoisted,
2783            // which resolved it as a plain global. Correct that here, the way
2784            // `declare_global` does.
2785            if matches!(existing.closure_type, ClosureType::Global) {
2786                existing.closure_type = ClosureType::ModuleDecl;
2787                existing.is_const = def.is_const;
2788                existing.is_lexical = def.is_lexical;
2789            }
2790            return 0;
2791        }
2792        state.closure_vars.push(ClosureVar {
2793            name: name.to_string(),
2794            is_const: def.is_const,
2795            is_lexical: def.is_lexical,
2796            closure_type: ClosureType::ModuleDecl,
2797            var_idx: 0,
2798        });
2799        0
2800    }
2801
2802    /// Declare a module variable and answer its closure-variable index.
2803    ///
2804    /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
2805    /// module variable is not one. The import table needs the real index instead, because
2806    /// that is the position the host writes the cell into.
2807    fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
2808        self.declare_module(name, def);
2809        self.cur()
2810            .closure_vars
2811            .iter()
2812            .position(|c| c.name == name)
2813            .map(|index| index as u32)
2814            .unwrap_or(0)
2815    }
2816
2817    /// Declare one imported binding as a module variable.
2818    ///
2819    /// Returns the closure-variable index, which is what the import table records: the
2820    /// host writes the exporter's cell into that slot before the body runs.
2821    fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
2822        let state = self.state();
2823        if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
2824            // Keep the slot, fix the kind: the name may already have been referenced.
2825            state.closure_vars[index].closure_type = ClosureType::ModuleImport;
2826            state.closure_vars[index].is_const = is_const;
2827            return index as u32;
2828        }
2829        state.closure_vars.push(ClosureVar {
2830            name: name.to_string(),
2831            // An imported binding cannot be assigned: `x = 1` on an import is a
2832            // `TypeError` at run time, which the const flag is what produces.
2833            is_const: true,
2834            // Lexical, so reads go through `get_var_ref_check`: before linking has filled
2835            // the cell an import is in its dead zone, and reading it there must say so
2836            // rather than answer `undefined`.
2837            is_lexical: true,
2838            closure_type: ClosureType::ModuleImport,
2839            var_idx: 0,
2840        });
2841        state.closure_vars.len() as u32 - 1
2842    }
2843
2844    /// Emit the code an `export` needs.
2845    ///
2846    /// Only `export default <expr>` has any: everything else is a table entry whose
2847    /// binding is declared elsewhere. The expression is stored into the hidden
2848    /// `*default*` variable rather than returned, because the module body has no value
2849    /// to speak of.
2850    fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2851        match &decl.kind {
2852            ExportKind::Declaration(stmt) => self.stmt(stmt),
2853            ExportKind::Default(expr) => {
2854                // A named default function/class is already a module binding; the export
2855                // points at it and there is nothing to evaluate.
2856                if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some())
2857                    || matches!(&expr.kind, ExprKind::Class(class) if class.name.is_some())
2858                {
2859                    return Ok(());
2860                }
2861                self.expr(expr)?;
2862                let index = self.declare_export_default();
2863                self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
2864                Ok(())
2865            }
2866            ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
2867        }
2868    }
2869
2870    /// A module name as the string it denotes.
2871    fn module_name_text(name: &ModuleName) -> &str {
2872        match name {
2873            ModuleName::Ident(ident) => &ident.name,
2874            ModuleName::Str(text) => text,
2875        }
2876    }
2877
2878    /// Bind `import`'s local names and record where each one comes from.
2879    ///
2880    /// Nothing is emitted: an import is not an instruction, it is a promise that the
2881    /// binding's cell will be filled before the body runs. The cell lands in the module's
2882    /// environment at a fixed index, and the host fills it from the exporter's cell —
2883    /// which is why a cyclic import can bind before the other module has evaluated.
2884    fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
2885        let request = self.module_request(&decl.source, &decl.attributes);
2886        for specifier in &decl.specifiers {
2887            let (local, name, is_star) = match specifier {
2888                ImportSpecifier::Default(ident) => {
2889                    (ident.name.clone(), "default".to_string(), false)
2890                }
2891                ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
2892                ImportSpecifier::Named { imported, local } => (
2893                    local.name.clone(),
2894                    Self::module_name_text(imported).to_string(),
2895                    false,
2896                ),
2897            };
2898            // `import * as ns` is *not* a live binding of another module's variable —
2899            // it is a value of its own, which is why the reference declares it like a
2900            // module variable and the host stores the namespace object in that cell.
2901            let var_idx = if is_star {
2902                // `const`: a namespace object is a value, and the binding is immutable.
2903                self.declare_module_var(&local, &VarDef::constant(local.clone()))
2904            } else {
2905                self.declare_import(&local, true)
2906            };
2907            self.module_meta().imports.push(ImportEntry {
2908                module: request,
2909                name,
2910                var_idx,
2911                is_star,
2912            });
2913        }
2914        Ok(())
2915    }
2916
2917    /// Record what an `export` offers, declaring the binding it exports.
2918    ///
2919    /// `export var x = 1` is a declaration like any other; only the table entry is extra.
2920    fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2921        match &decl.kind {
2922            ExportKind::Declaration(stmt) => {
2923                // The inner declaration keeps its own hoisting, then every name it binds
2924                // becomes an export of the same name.
2925                self.hoist_stmt(stmt)?;
2926                let mut names = Vec::new();
2927                Self::declared_names(stmt, &mut names);
2928                for name in names {
2929                    let var_idx = self.module_binding_index(&name);
2930                    self.exports_local(&name, var_idx);
2931                }
2932            }
2933            ExportKind::Default(expr) => {
2934                // The reference puts a default export in a hidden `*default*` variable,
2935                // so `export default function f(){}` can export a *value* while `f` stays
2936                // a binding of the module.
2937                if let ExprKind::Function(func) = &expr.kind
2938                    && let Some(name) = &func.name
2939                {
2940                    let text = name.name.clone();
2941                    self.hoist_stmt(&Stmt {
2942                        kind: StmtKind::FuncDecl(func.clone()),
2943                        span: expr.span,
2944                    })?;
2945                    let var_idx = self.module_binding_index(&text);
2946                    self.module_meta().exports.push(ExportEntry::Local {
2947                        export_name: "default".to_string(),
2948                        var_idx,
2949                    });
2950                    return Ok(());
2951                }
2952                if let ExprKind::Class(class) = &expr.kind
2953                    && let Some(name) = &class.name
2954                {
2955                    let text = name.name.clone();
2956                    self.hoist_stmt(&Stmt {
2957                        kind: StmtKind::ClassDecl(class.clone()),
2958                        span: expr.span,
2959                    })?;
2960                    let var_idx = self.module_binding_index(&text);
2961                    let _ = var_idx;
2962                }
2963                let var_idx = self.declare_export_default();
2964                self.module_meta().exports.push(ExportEntry::Local {
2965                    export_name: "default".to_string(),
2966                    var_idx,
2967                });
2968            }
2969            ExportKind::Named {
2970                specifiers,
2971                source,
2972                attributes,
2973            } => match source {
2974                Some(source) => {
2975                    let request = self.module_request(source, attributes);
2976                    for specifier in specifiers {
2977                        self.module_meta().exports.push(ExportEntry::Indirect {
2978                            export_name: Self::module_name_text(&specifier.exported).to_string(),
2979                            module: request,
2980                            import_name: Self::module_name_text(&specifier.local).to_string(),
2981                        });
2982                    }
2983                }
2984                None => {
2985                    for specifier in specifiers {
2986                        let local = Self::module_name_text(&specifier.local).to_string();
2987                        let var_idx = self.module_binding_index(&local);
2988                        let export_name = Self::module_name_text(&specifier.exported).to_string();
2989                        self.module_meta().exports.push(ExportEntry::Local {
2990                            export_name,
2991                            var_idx,
2992                        });
2993                    }
2994                }
2995            },
2996            ExportKind::All {
2997                source,
2998                exported,
2999                attributes,
3000            } => {
3001                let request = self.module_request(source, attributes);
3002                match exported {
3003                    Some(name) => {
3004                        self.module_meta().exports.push(ExportEntry::StarAs {
3005                            export_name: Self::module_name_text(name).to_string(),
3006                            module: request,
3007                        });
3008                    }
3009                    None => {
3010                        self.module_meta()
3011                            .exports
3012                            .push(ExportEntry::Star { module: request });
3013                    }
3014                }
3015            }
3016        }
3017        Ok(())
3018    }
3019
3020    /// The names a declaration binds, which is what `export <decl>` exports.
3021    fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
3022        match &stmt.kind {
3023            StmtKind::VarDecl(decl) => {
3024                for declarator in &decl.declarators {
3025                    let mut names = Vec::new();
3026                    declarator.target.bound_names(&mut names);
3027                    out.extend(names.into_iter().map(|name| name.name));
3028                }
3029            }
3030            StmtKind::FuncDecl(func) => {
3031                if let Some(name) = &func.name {
3032                    out.push(name.name.clone());
3033                }
3034            }
3035            StmtKind::ClassDecl(class) => {
3036                if let Some(name) = &class.name {
3037                    out.push(name.name.clone());
3038                }
3039            }
3040            _ => {}
3041        }
3042    }
3043
3044    /// The closure-variable index of a module binding, declaring it if the name was
3045    /// exported without being declared here.
3046    ///
3047    /// `export { x }` where `x` is not declared in the module is a link-time
3048    /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
3049    fn module_binding_index(&mut self, name: &str) -> u32 {
3050        if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
3051            return index as u32;
3052        }
3053        self.declare_module_var(name, &VarDef::lexical(name.to_string()))
3054    }
3055
3056    fn exports_local(&mut self, export_name: &str, var_idx: u32) {
3057        self.module_meta().exports.push(ExportEntry::Local {
3058            export_name: export_name.to_string(),
3059            var_idx,
3060        });
3061    }
3062
3063    /// The hidden `*default*` binding `export default <expr>` stores into.
3064    fn declare_export_default(&mut self) -> u32 {
3065        const DEFAULT: &str = "*default*";
3066        if let Some(index) = self
3067            .cur()
3068            .closure_vars
3069            .iter()
3070            .position(|c| c.name == DEFAULT)
3071        {
3072            return index as u32;
3073        }
3074        self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
3075    }
3076
3077    /// The module tables, which only the top-level state has.
3078    fn module_meta(&mut self) -> &mut ModuleMeta {
3079        self.state()
3080            .module
3081            .as_mut()
3082            .expect("module tables are only touched while compiling a module")
3083    }
3084
3085    /// The index of `specifier`'s request, adding it if it is new.
3086    ///
3087    /// Deduplicated on the specifier *and* its attributes: the same file imported once as
3088    /// JSON and once as text is two modules with two different contents, which is exactly
3089    /// what `hello_module.js` does.
3090    fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
3091        let attributes: Vec<(String, String)> = attributes
3092            .iter()
3093            .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
3094            .collect();
3095        let meta = self.module_meta();
3096        if let Some(index) = meta
3097            .requests
3098            .iter()
3099            .position(|request| request.specifier == specifier && request.attributes == attributes)
3100        {
3101            return index as u32;
3102        }
3103        meta.requests.push(ModuleRequest {
3104            specifier: specifier.to_string(),
3105            attributes,
3106        });
3107        meta.requests.len() as u32 - 1
3108    }
3109
3110    /// Compile a loop body with a `break`/`continue` target pushed for it.
3111    fn loop_body(
3112        &mut self,
3113        body: &Stmt,
3114        labels: &[String],
3115        continue_label: Label,
3116        break_label: Label,
3117    ) -> Result<(), SyntaxError> {
3118        self.push_jump_target(JumpTarget {
3119            names: labels.to_vec(),
3120            break_label: Some(break_label),
3121            continue_label: Some(continue_label),
3122            // A loop leaves nothing of its own on the value stack.
3123            drop_count: 0,
3124            finally_label: None,
3125            is_regular_stmt: false,
3126            has_iterator: false,
3127            is_async_iterator: false,
3128        });
3129        let result = self.stmt(body);
3130        self.pop_jump_target();
3131        result
3132    }
3133
3134    fn push_jump_target(&mut self, target: JumpTarget) {
3135        self.state().jump_targets.push(target);
3136    }
3137
3138    fn pop_jump_target(&mut self) {
3139        self.state().jump_targets.pop();
3140    }
3141
3142    fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3143        let (label, is_break) = match &stmt.kind {
3144            StmtKind::Break(label) => (label.as_ref(), true),
3145            StmtKind::Continue(label) => (label.as_ref(), false),
3146            _ => unreachable!("control_transfer is only called for break and continue"),
3147        };
3148
3149        // Walk outward from the innermost construct. Everything considered before
3150        // the match is a construct control is leaving, and leaving it has a cost:
3151        // its stack slots go, and its finalizer runs.
3152        let targets = self.cur().jump_targets.clone();
3153        for target in targets.iter().rev() {
3154            let destination = match (label, is_break) {
3155                // An unlabelled `break` skips a labelled non-loop statement: `break`
3156                // may name one, but the bare form only means "leave the loop".
3157                (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3158                (None, false) => target.continue_label,
3159                (Some(name), true) => target
3160                    .break_label
3161                    .filter(|_| target.names.contains(&name.name)),
3162                (Some(name), false) => target
3163                    .continue_label
3164                    .filter(|_| target.names.contains(&name.name)),
3165            };
3166
3167            if let Some(destination) = destination {
3168                self.emit_jump(Opcode::Goto, destination, &[]);
3169                return Ok(());
3170            }
3171
3172            // Closing the iterator consumes the three slots the loop keeps on the
3173            // stack (iterator, next method, catch offset), so those are not dropped
3174            // again below.
3175            let mut remaining = target.drop_count;
3176            if target.has_iterator {
3177                self.emit_iterator_close(target.is_async_iterator, false);
3178                remaining = remaining.saturating_sub(3);
3179            }
3180            for _ in 0..remaining {
3181                self.emit(Opcode::Drop, &[]);
3182            }
3183            if let Some(finally) = target.finally_label {
3184                // The finalizer runs as a subroutine and is handed a dummy return
3185                // value, which is dropped afterwards to keep the stack the depth it
3186                // had before.
3187                self.emit(Opcode::Undefined, &[]);
3188                self.emit_jump(Opcode::Gosub, finally, &[]);
3189                self.emit(Opcode::Drop, &[]);
3190            }
3191        }
3192
3193        // The parser rejects a break/continue with no target, so reaching here
3194        // means the compiler's own bookkeeping is wrong.
3195        Err(SyntaxError::new(
3196            if is_break {
3197                "break has no enclosing loop or switch"
3198            } else {
3199                "continue has no enclosing loop"
3200            },
3201            stmt.span,
3202        ))
3203    }
3204
3205    /// Compile a labelled statement.
3206    ///
3207    /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3208    /// that loop's targets, so the chain is collected and handed to the loop. A
3209    /// label on a non-loop statement only provides a `break` target, because
3210    /// `continue` may not target it.
3211    fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3212        let mut names = vec![label.name.clone()];
3213        let mut inner = body;
3214        while let StmtKind::Labeled {
3215            label: next,
3216            body: deeper,
3217        } = &inner.kind
3218        {
3219            names.push(next.name.clone());
3220            inner = deeper;
3221        }
3222        if Self::is_loop(inner) {
3223            return self.stmt_labelled(inner, &names);
3224        }
3225        let end = self.new_label();
3226        self.push_jump_target(JumpTarget {
3227            names,
3228            break_label: Some(end),
3229            continue_label: None,
3230            drop_count: 0,
3231            finally_label: None,
3232            is_regular_stmt: true,
3233            has_iterator: false,
3234            is_async_iterator: false,
3235        });
3236        let result = self.stmt(inner);
3237        self.pop_jump_target();
3238        result?;
3239        self.place_label(end);
3240        let _ = stmt;
3241        Ok(())
3242    }
3243
3244    /// Whether a statement is a loop, i.e. a valid target for `continue`.
3245    fn is_loop(stmt: &Stmt) -> bool {
3246        matches!(
3247            stmt.kind,
3248            StmtKind::While { .. }
3249                | StmtKind::DoWhile { .. }
3250                | StmtKind::For { .. }
3251                | StmtKind::ForIn { .. }
3252                | StmtKind::ForOf { .. }
3253        )
3254    }
3255
3256    /// Compile `switch`.
3257    ///
3258    /// The discriminant is evaluated once and stays on the value stack while the
3259    /// clauses compare against copies of it, so it is dropped at the end — which is
3260    /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3261    /// clause's body jumps over the *next* clause's tests straight into its body.
3262    ///
3263    /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3264    /// the next run's tests. Only the last run's miss reaches the `default` body, or
3265    /// the end of the switch when there is no `default`. That failure path can point
3266    /// backwards (`default` written first), so the runs and their labels are worked
3267    /// out before any code is emitted.
3268    fn switch(
3269        &mut self,
3270        discriminant: &Expr,
3271        cases: &[SwitchCase],
3272        stmt: &Stmt,
3273    ) -> Result<(), SyntaxError> {
3274        self.reset_value();
3275        // The discriminant is evaluated outside the switch's block scope, before
3276        // any `case` clause exists.
3277        self.expr(discriminant)?;
3278
3279        let switch_key = stmt.span.start.offset as u64;
3280        let switch_parent = self.cur().current_block;
3281        self.push_block(switch_key, switch_parent);
3282        self.emit_scope_enter(switch_key);
3283
3284        let break_label = self.new_label();
3285        self.push_jump_target(JumpTarget {
3286            names: Vec::new(),
3287            break_label: Some(break_label),
3288            // `switch` is a valid `break` target but not a `continue` target.
3289            continue_label: None,
3290            // The discriminant stays on the value stack for the whole statement, so
3291            // a `break` aimed further out has to discard it.
3292            drop_count: 1,
3293            finally_label: None,
3294            is_regular_stmt: false,
3295            has_iterator: false,
3296            is_async_iterator: false,
3297        });
3298
3299        // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3300        // its label to the clause after it, so both tests reach the same body.
3301        let mut runs: Vec<(usize, usize)> = Vec::new();
3302        let mut scan = 0;
3303        while scan < cases.len() {
3304            if cases[scan].test.is_some() {
3305                let mut last = scan;
3306                while last + 1 < cases.len()
3307                    && cases[last].test.is_some()
3308                    && cases[last].body.is_empty()
3309                    && cases[last + 1].test.is_some()
3310                {
3311                    last += 1;
3312                }
3313                runs.push((scan, last));
3314                scan = last + 1;
3315            } else {
3316                scan += 1;
3317            }
3318        }
3319
3320        let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3321        let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3322        let default_at = cases.iter().position(|case| case.test.is_none());
3323        // Where the last run sends control when nothing matched.
3324        let miss_target = match default_at {
3325            Some(index) => body_labels[index],
3326            None => break_label,
3327        };
3328
3329        // When `default` comes first, control has to jump over it to reach the
3330        // tests. It only needs to when some clause actually has a test; otherwise
3331        // the default body is the entry point.
3332        let mut entry = None;
3333        if default_at == Some(0) && !runs.is_empty() {
3334            self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3335            entry = Some(run_labels[0]);
3336        }
3337
3338        let mut index = 0;
3339        let mut run = 0;
3340        let result = (|| -> Result<(), SyntaxError> {
3341            while index < cases.len() {
3342                if cases[index].test.is_some() {
3343                    let (first, last) = runs[run];
3344                    // Reaching these tests from the preceding body is a
3345                    // fallthrough, which continues inside the body and skips them.
3346                    if index > 0 {
3347                        self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3348                    }
3349                    if let Some(label) = entry.take() {
3350                        self.place_label(label);
3351                    }
3352                    self.place_label(run_labels[run]);
3353
3354                    for (offset, case) in cases[first..=last].iter().enumerate() {
3355                        let test = case.test.as_ref().unwrap();
3356                        self.emit(Opcode::Dup, &[]);
3357                        self.expr(test)?;
3358                        self.emit(Opcode::StrictEq, &[]);
3359                        if first + offset < last {
3360                            self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3361                        } else {
3362                            // Hand over to the next run's tests, or give up.
3363                            let next = match runs.get(run + 1) {
3364                                Some(_) => run_labels[run + 1],
3365                                None => miss_target,
3366                            };
3367                            self.emit_jump(Opcode::IfFalse, next, &[]);
3368                        }
3369                    }
3370
3371                    self.place_label(body_labels[index]);
3372                    for case in &cases[first..=last] {
3373                        self.stmts(&case.body)?;
3374                    }
3375                    index = last + 1;
3376                    run += 1;
3377                } else {
3378                    // `default`: control arrives here either by falling through or
3379                    // because every test missed.
3380                    self.place_label(body_labels[index]);
3381                    self.stmts(&cases[index].body)?;
3382                    index += 1;
3383                }
3384            }
3385            Ok(())
3386        })();
3387
3388        if result.is_ok() {
3389            self.place_label(break_label);
3390            // Discard the discriminant now that no test needs it.
3391            self.emit(Opcode::Drop, &[]);
3392        }
3393
3394        self.pop_jump_target();
3395        self.emit_scope_leave(switch_key);
3396        self.state().current_block = switch_parent;
3397        result
3398    }
3399
3400    /// Compile `try`/`catch`/`finally`.
3401    ///
3402    /// The shape is an exception table built out of `catch` instructions, each of
3403    /// which records where control goes if the instructions that follow raise:
3404    ///
3405    /// ```text
3406    /// catch HANDLER            <- if the guarded block throws, jump to HANDLER
3407    ///   <guarded block>
3408    ///   drop                   <- discard the catch offset
3409    ///   undefined; gosub FINALLY; drop
3410    ///   goto END
3411    /// HANDLER:
3412    ///   <bind the catch parameter>
3413    ///   catch CATCH2           <- if the handler itself throws, go to CATCH2
3414    ///   <handler body>
3415    ///   drop; undefined; gosub FINALLY; drop; goto END
3416    /// CATCH2:
3417    ///   gosub FINALLY; throw   <- run the finalizer, then let the error out
3418    /// FINALLY:
3419    ///   <finalizer>
3420    ///   ret                    <- return to the `gosub`
3421    /// END:
3422    /// ```
3423    ///
3424    /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
3425    /// of the finalizer serves the normal path, the handler path and the
3426    /// propagating-exception path.
3427    ///
3428    /// The `undefined` before each `gosub` is a dummy return value: the finalizer
3429    /// runs with `ret_value` on the stack, and the normal path has no value to
3430    /// keep, so it pushes one to keep the stack depth identical on every path.
3431    fn try_stmt(
3432        &mut self,
3433        stmt: &Stmt,
3434        block: &[Stmt],
3435        handler: &Option<CatchClause>,
3436        finalizer: Option<&[Stmt]>,
3437    ) -> Result<(), SyntaxError> {
3438        self.reset_value();
3439
3440        let catch_label = self.new_label();
3441        let catch2_label = self.new_label();
3442        let finally_label = self.new_label();
3443        let end_label = self.new_label();
3444
3445        self.emit_jump(Opcode::Catch, catch_label, &[]);
3446
3447        // The guarded block. `break` may not target it, so its entry exists purely
3448        // to unwind: a jump out has to discard the catch offset and run the
3449        // finalizer.
3450        self.push_jump_target(JumpTarget {
3451            names: Vec::new(),
3452            break_label: None,
3453            continue_label: None,
3454            drop_count: 1,
3455            finally_label: Some(finally_label),
3456            is_regular_stmt: false,
3457            has_iterator: false,
3458            is_async_iterator: false,
3459        });
3460
3461        let block_key = Self::try_block_key(stmt, TryPart::Block);
3462        let block_parent = self.cur().current_block;
3463        self.push_block(block_key, block_parent);
3464        self.emit_scope_enter(block_key);
3465        self.stmts(block)?;
3466        self.emit_scope_leave(block_key);
3467        self.state().current_block = block_parent;
3468        // A guarded block that ends in a `return`/`throw` never reaches the
3469        // epilogue, so the reference does not emit one.
3470        self.pop_jump_target();
3471        let block_live = !block.last().is_some_and(Self::terminates);
3472
3473        if block_live {
3474            self.emit(Opcode::Drop, &[]);
3475            self.emit(Opcode::Undefined, &[]);
3476            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3477            self.emit(Opcode::Drop, &[]);
3478            self.emit_jump(Opcode::Goto, end_label, &[]);
3479        }
3480
3481        if let Some(handler) = handler {
3482            self.place_label(catch_label);
3483            // The thrown value is on top of the stack: bind it, or discard it for
3484            // `catch { }`.
3485            match &handler.param {
3486                Some(pattern) => {
3487                    // The stores resolve the names, so they have to run inside the
3488                    // parameter's own scope; otherwise a same-named `catch` further out
3489                    // could win. A `catch` binding is never in the dead zone, so the store
3490                    // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
3491                    let param_key = Self::try_block_key(stmt, TryPart::Param);
3492                    let param_parent = self.cur().current_block;
3493                    self.push_block(param_key, param_parent);
3494                    self.destructure(pattern, Some(VarDeclKind::Var))?;
3495                    self.state().current_block = param_parent;
3496                }
3497                None => self.emit(Opcode::Drop, &[]),
3498            }
3499            self.emit_jump(Opcode::Catch, catch2_label, &[]);
3500
3501            self.push_jump_target(JumpTarget {
3502                names: Vec::new(),
3503                break_label: None,
3504                continue_label: None,
3505                drop_count: 1,
3506                finally_label: Some(finally_label),
3507                is_regular_stmt: false,
3508                has_iterator: false,
3509                is_async_iterator: false,
3510            });
3511            let catch_key = Self::try_block_key(stmt, TryPart::Catch);
3512            let catch_parent = self.cur().current_block;
3513            self.push_block(catch_key, catch_parent);
3514            self.emit_scope_enter(catch_key);
3515            self.stmts(&handler.body)?;
3516            self.emit_scope_leave(catch_key);
3517            self.state().current_block = catch_parent;
3518            self.pop_jump_target();
3519            let handler_live = !handler.body.last().is_some_and(Self::terminates);
3520
3521            if handler_live {
3522                self.emit(Opcode::Drop, &[]);
3523                self.emit(Opcode::Undefined, &[]);
3524                self.emit_jump(Opcode::Gosub, finally_label, &[]);
3525                self.emit(Opcode::Drop, &[]);
3526                self.emit_jump(Opcode::Goto, end_label, &[]);
3527            }
3528
3529            // An error raised inside the handler still has to run the finalizer.
3530            self.place_label(catch2_label);
3531            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3532            self.emit(Opcode::Throw, &[]);
3533        } else {
3534            // `try`/`finally` with no handler: the finalizer runs, then the error
3535            // keeps propagating.
3536            self.place_label(catch_label);
3537            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3538            self.emit(Opcode::Throw, &[]);
3539        }
3540
3541        self.place_label(finally_label);
3542        // Inside the finalizer, leaving has a different cost: the return value and
3543        // the `gosub` return address are both on the stack, and neither finalizer nor
3544        // any outer one may run before the block has finished.
3545        self.push_jump_target(JumpTarget {
3546            names: Vec::new(),
3547            break_label: None,
3548            continue_label: None,
3549            drop_count: 2,
3550            finally_label: None,
3551            is_regular_stmt: false,
3552            has_iterator: false,
3553            is_async_iterator: false,
3554        });
3555        if let Some(finalizer) = finalizer {
3556            let finally_key = Self::try_block_key(stmt, TryPart::Finally);
3557            let finally_parent = self.cur().current_block;
3558            self.push_block(finally_key, finally_parent);
3559            self.emit_scope_enter(finally_key);
3560            self.stmts(finalizer)?;
3561            self.emit_scope_leave(finally_key);
3562            self.state().current_block = finally_parent;
3563        }
3564        self.pop_jump_target();
3565        self.emit(Opcode::Ret, &[]);
3566        self.place_label(end_label);
3567        Ok(())
3568    }
3569
3570    /// Compile `for`/`in` and `for`/`of`.
3571    ///
3572    /// Both keep an enumeration record on the value stack for the whole loop, which
3573    /// is what makes leaving early expensive: the record has to be dropped, or the
3574    /// iterator closed. The layout is
3575    ///
3576    /// ```text
3577    ///   <iterated expression>
3578    ///   for_in_start | for_of_start      <- pushes the record
3579    ///   goto TEST
3580    /// NEXT:
3581    ///   <bind the loop variable>
3582    ///   <body>
3583    /// TEST:
3584    ///   for_in_next | for_of_next 0
3585    ///   if_false NEXT                    <- not finished: next iteration
3586    ///   drop                             <- finished: discard the leftover value
3587    /// BREAK:
3588    ///   drop | iterator_close            <- the one cleanup `break` also uses
3589    /// ```
3590    ///
3591    /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
3592    /// normal exit share one copy — which is why `break` inside the loop emits nothing
3593    /// of its own, and only a jump that passes *through* the loop pays for its record.
3594    fn for_in_of(
3595        &mut self,
3596        stmt: &Stmt,
3597        left: &ForHead,
3598        right: &Expr,
3599        body: &Stmt,
3600        kind: ForLoopKind,
3601        labels: &[String],
3602    ) -> Result<(), SyntaxError> {
3603        self.reset_value();
3604
3605        let loop_key = stmt.span.start.offset as u64;
3606        let loop_parent = self.cur().current_block;
3607        self.push_block(loop_key, loop_parent);
3608        self.emit_scope_enter(loop_key);
3609
3610        // The iterated expression is evaluated inside the loop's scope, after the
3611        // bindings exist in the temporal dead zone.
3612        self.expr(right)?;
3613
3614        let next = self.new_label();
3615        let test = self.new_label();
3616        let break_target = self.new_label();
3617
3618        let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
3619        match kind {
3620            ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
3621            ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
3622            ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
3623        }
3624        self.emit_jump(Opcode::Goto, test, &[]);
3625
3626        self.push_jump_target(JumpTarget {
3627            // `outer: for (x of xs) … break outer` needs the name here. Without it the
3628            // loop had no label to break to, and the compiler reported "break has no
3629            // enclosing loop" for a loop that was plainly enclosing it.
3630            names: labels.to_vec(),
3631            break_label: Some(break_target),
3632            continue_label: Some(test),
3633            // Passing through the loop has to dispose of its record. A `for`/`of`
3634            // record is three slots, and closing the iterator consumes all of them.
3635            drop_count: if has_iterator { 3 } else { 1 },
3636            finally_label: None,
3637            is_regular_stmt: false,
3638            has_iterator,
3639            is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
3640        });
3641
3642        self.place_label(next);
3643        self.bind_loop_variable(left)?;
3644
3645        // The reference marks the body with its own label here. Nothing jumps to it
3646        // once the loop is laid out, but it is not decoration: a label between the
3647        // store and the body is why `put_loc v; get_loc v` does *not* fold into
3648        // `set_loc v` when the body starts by reading the loop variable.
3649        let body_label = self.new_label();
3650        self.place_label(body_label);
3651        // `for (using x of …)` disposes once per iteration, so the body is a disposal
3652        // region rather than the whole loop: the resource is the element that this
3653        // iteration produced.
3654        let using_slot = match left {
3655            ForHead::VarDecl(decl) if decl.kind.is_using() => {
3656                decl.declarators
3657                    .first()
3658                    .and_then(|declarator| match &declarator.target.kind {
3659                        PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
3660                        _ => None,
3661                    })
3662            }
3663            _ => None,
3664        };
3665        match using_slot {
3666            Some(slot) => {
3667                let live = !Self::terminates(body);
3668                self.using_region_around(slot, live, |compiler| compiler.stmt(body))?;
3669            }
3670            None => self.stmt(body)?,
3671        }
3672
3673        // §14.7.5.6 `ForIn/OfBodyEvaluation` step 6: a `let`/`const` head gets a **fresh
3674        // binding each iteration**, so a closure the body creates keeps that iteration's
3675        // value. `CloseCaptured` is the same instruction the C-style `for` uses: it swaps in
3676        // a new reference cell holding the current value.
3677        //
3678        // The position is the *end* of the body, not the start: closing before the body
3679        // would leave the closures pointing at the cell the next `put_loc` overwrites, and
3680        // `for (const x of [1,2,3]) fs.push(() => x)` answered `2,3,3` instead of `1,2,3`.
3681        for name in Self::loop_binding_names(left) {
3682            let pos = self.cur().cur_pos;
3683            self.state().insns.push(Insn::CloseCaptured {
3684                name,
3685                block: loop_key,
3686            });
3687            self.state().insn_pos.push(pos);
3688        }
3689        self.place_label(test);
3690        match kind {
3691            ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
3692            ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
3693            ForLoopKind::AwaitOf => {
3694                // The reference's shape: step, `await` the result, then unpack it.
3695                self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
3696                self.emit(Opcode::Await, &[]);
3697                self.state().has_await = true;
3698                self.emit(Opcode::IteratorGetValueDone, &[]);
3699            }
3700        }
3701        self.emit_jump(Opcode::IfFalse, next, &[]);
3702        // The loop is finished; `for_xx_next` left an `undefined` behind.
3703        self.emit(Opcode::Drop, &[]);
3704
3705        self.pop_jump_target();
3706        self.place_label(break_target);
3707        if has_iterator {
3708            // A loop that ran to completion finds its iterator slot already cleared (see
3709            // `iterator_get_value_done`), so this closes only an iterator abandoned by a
3710            // `break` that jumped here.
3711            self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
3712        } else {
3713            self.emit(Opcode::Drop, &[]);
3714        }
3715
3716        self.emit_scope_leave(loop_key);
3717        self.state().current_block = loop_parent;
3718        Ok(())
3719    }
3720
3721    /// The names a `for (let … of/in …)` head declares, which need a fresh cell per
3722    /// iteration. An assignment head (`for (x of …)`) declares nothing, so it is empty.
3723    fn loop_binding_names(left: &ForHead) -> Vec<String> {
3724        let ForHead::VarDecl(decl) = left else {
3725            return Vec::new();
3726        };
3727        if decl.kind == VarDeclKind::Var {
3728            return Vec::new();
3729        }
3730        let mut names = Vec::new();
3731        for declarator in &decl.declarators {
3732            let mut idents = Vec::new();
3733            declarator.target.bound_names(&mut idents);
3734            names.extend(idents.into_iter().map(|ident| ident.name));
3735        }
3736        names
3737    }
3738
3739    /// Store the value `for_xx_next` left on the stack into the loop variable.
3740    fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
3741        // A declaration *initialises* the binding, which is what takes a `let` out of
3742        // the temporal dead zone, so the store is the unchecked form. Assigning to a
3743        // binding declared elsewhere is an ordinary write and keeps its check.
3744        let (pattern, action) = match left {
3745            ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
3746            ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
3747        };
3748        match &pattern.kind {
3749            PatternKind::Ident(name) => {
3750                // `for (using x of …)` validates and snapshots each iteration's value
3751                // before the body runs, which is what makes a non-disposable element fail
3752                // on the iteration that produced it rather than at the end of the loop.
3753                if let ForHead::VarDecl(decl) = left
3754                    && decl.kind.is_using()
3755                {
3756                    let method_slot = self
3757                        .using_method_slot(&name.name)
3758                        .expect("a using binding was declared during hoisting");
3759                    self.emit(
3760                        Opcode::UsingCheck,
3761                        &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3762                    );
3763                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3764                }
3765                self.emit_var(action, &name.name);
3766                Ok(())
3767            }
3768            // Every other target stores through the same path an assignment pattern
3769            // uses, which is what makes `for (a[0] in obj)` write each key into the
3770            // property instead of refusing the loop outright.
3771            _ => self.destructure(
3772                pattern,
3773                match left {
3774                    ForHead::VarDecl(decl) => Some(decl.kind),
3775                    ForHead::Assign(_) => None,
3776                },
3777            ),
3778        }
3779    }
3780
3781    fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
3782        for declarator in &decl.declarators {
3783            let Some(init) = &declarator.init else {
3784                // `var x;` stays `undefined`. A lexical binding is different: it
3785                // has to be *initialised* to leave the temporal dead zone, so the
3786                // compiler supplies an explicit `undefined`.
3787                if decl.kind.is_lexical() {
3788                    // A lexical binding has to be *initialised* to leave the temporal
3789                    // dead zone, and a destructuring one is no different — `let {a}`
3790                    // with no initialiser is a syntax error, but `let [a] = []` still
3791                    // needs `a` to be initialised from an empty source, which the
3792                    // pattern does on its own.
3793                    self.emit(Opcode::Undefined, &[]);
3794                    self.destructure(&declarator.target, Some(decl.kind))?;
3795                }
3796                continue;
3797            };
3798            match &declarator.target.kind {
3799                PatternKind::Ident(name) => {
3800                    self.expr(init)?;
3801                    self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
3802                    if decl.kind.is_using() {
3803                        // `using_check` validates the value and snapshots its dispose
3804                        // method: `value -> value, method`. The snapshot is what makes a
3805                        // later change to `Symbol.dispose` irrelevant, and validating here
3806                        // is what keeps the body from running at all when the value is not
3807                        // disposable.
3808                        let method_slot = self
3809                            .using_method_slot(&name.name)
3810                            .expect("a using binding was declared during hoisting");
3811                        self.emit(
3812                            Opcode::UsingCheck,
3813                            &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3814                        );
3815                        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3816                        self.emit_var(VarAction::PutInit, &name.name);
3817                        continue;
3818                    }
3819                    // A declaration statement produces no value, so nothing is
3820                    // duplicated onto the stack.
3821                    match decl.kind {
3822                        VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
3823                        _ => self.emit_var(VarAction::PutInit, &name.name),
3824                    }
3825                }
3826                _ => {
3827                    // A destructuring declaration keeps nothing on the stack: the
3828                    // pattern consumes the initialiser.
3829                    self.expr(init)?;
3830                    self.destructure(&declarator.target, Some(decl.kind))?;
3831                }
3832            }
3833        }
3834        Ok(())
3835    }
3836
3837    /// Bind a destructuring pattern from the value on top of the stack.
3838    ///
3839    /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
3840    /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
3841    /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
3842    /// *assignment*, where a member expression is a legal target and the store is an
3843    /// ordinary property write.
3844    ///
3845    /// The value is consumed. An assignment expression's own result is the right-hand
3846    /// side, which the caller keeps separately — the spec does not make the pattern's
3847    /// last store produce it.
3848    fn destructure(
3849        &mut self,
3850        pattern: &Pattern,
3851        decl: Option<VarDeclKind>,
3852    ) -> Result<(), SyntaxError> {
3853        match &pattern.kind {
3854            PatternKind::Ident(name) => {
3855                match decl {
3856                    Some(VarDeclKind::Var) | None => {
3857                        self.emit_var(VarAction::Put, &name.name);
3858                    }
3859                    Some(_) => self.emit_var(VarAction::PutInit, &name.name),
3860                }
3861                Ok(())
3862            }
3863            PatternKind::Assign { target, default } => {
3864                // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
3865                // keeps `null`.
3866                //
3867                // The shape is the reference's: test for `undefined`, and when the value is
3868                // present fall **through** to a single store both paths share. The
3869                // alternatives — branching to the store on each side — need a second store
3870                // and a jump between them, which is what the dump used to show.
3871                let has_value = self.new_label();
3872                self.emit(Opcode::Dup, &[]);
3873                self.emit(Opcode::IsUndefined, &[]);
3874                self.emit_jump(Opcode::IfFalse, has_value, &[]);
3875                self.emit(Opcode::Drop, &[]);
3876                self.expr(default)?;
3877                // `var {f = function(){}} = {}` names the function `f`, like a plain
3878                // `var f = function(){}` does. Both pattern forms do it:
3879                // `BindingInitialization` names the value for a *binding* target, and since
3880                // ES2018 `DestructuringAssignmentEvaluation` does the same, so
3881                // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
3882                // no name to give, which is why only an identifier qualifies.
3883                if let PatternKind::Ident(name) = &target.kind {
3884                    self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
3885                }
3886                self.place_label(has_value);
3887                self.destructure(target, decl)
3888            }
3889            PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
3890            PatternKind::Object { properties, rest } => {
3891                self.destructure_object(properties, rest, decl, pattern)
3892            }
3893            PatternKind::Member(member) if decl.is_none() => {
3894                // An assignment pattern may store into a property. The value is on the
3895                // stack, so the receiver and the key go above it and `rot3l`/`swap2`
3896                // put the three in the order `put_array_el`/`put_field` expect.
3897                self.expr(&member.object)?;
3898                match &member.property {
3899                    MemberProp::Ident(name) => {
3900                        // `value obj` -> `obj value`, the order `put_field` takes.
3901                        // Nothing needs to be left behind: a pattern element's value is
3902                        // consumed by its own store.
3903                        self.emit(Opcode::Swap, &[]);
3904                        self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
3905                    }
3906                    MemberProp::Computed(index) => {
3907                        self.expr(index)?;
3908                        // `value obj key` -> `obj key value`.
3909                        self.emit(Opcode::Rot3l, &[]);
3910                        self.emit(Opcode::PutArrayEl, &[]);
3911                    }
3912                    MemberProp::Private(name) => {
3913                        // `value obj` -> `obj value`, and the store half of the assignment is
3914                        // the same one `obj.#x = value` uses — only without `insert2`,
3915                        // because a pattern element's value is not wanted back.
3916                        let binding = format!("#{}", name.name);
3917                        let (kind, setter) = self.private_use(&binding, member.span)?;
3918                        self.emit(Opcode::Swap, &[]);
3919                        self.private_store(&binding, kind, setter.as_deref())?;
3920                    }
3921                }
3922                Ok(())
3923            }
3924            PatternKind::Rest(inner) => self.destructure(inner, decl),
3925            PatternKind::Invalid(expr) => {
3926                Err(SyntaxError::new("invalid assignment target", expr.span))
3927            }
3928            _ => Err(SyntaxError::new(
3929                "this destructuring target is not supported by the compiler yet",
3930                pattern.span,
3931            )),
3932        }
3933    }
3934
3935    /// `[…]` on the left: drain an iterator, binding one target per element.
3936    fn destructure_array(
3937        &mut self,
3938        elements: &[Option<PatternElement>],
3939        rest: &Option<Box<RestElement>>,
3940        decl: Option<VarDeclKind>,
3941    ) -> Result<(), SyntaxError> {
3942        // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
3943        // pattern accepts any iterable and closes the iterator when the pattern ends
3944        // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
3945        // first because it is on top.
3946        self.emit(Opcode::ForOfStart, &[]);
3947        for element in elements {
3948            self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
3949            self.emit(Opcode::Drop, &[]);
3950            match element {
3951                Some(PatternElement::Pattern(pattern)) => self.destructure(pattern, decl)?,
3952                Some(PatternElement::Property { span, .. }) => {
3953                    return Err(SyntaxError::new(
3954                        "a property pattern is not a valid array element",
3955                        *span,
3956                    ));
3957                }
3958                // An elision skips the value, which is already on the stack.
3959                None => self.emit(Opcode::Drop, &[]),
3960            }
3961        }
3962        if let Some(rest) = rest {
3963            // The remaining values go into a fresh array. The target and its running
3964            // index stay on the stack above the iterator, which is what the operand of
3965            // `for_of_next` accounts for: two values sit above the iterator triple.
3966            self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
3967            self.emit(Opcode::Push0, &[]);
3968            let top = self.new_label();
3969            self.place_label(top);
3970            self.emit(Opcode::ForOfNext, &[Op::Int(2)]);
3971            let done = self.new_label();
3972            self.emit_jump(Opcode::IfTrue, done, &[]);
3973            self.emit(Opcode::DefineArrayEl, &[]);
3974            self.emit(Opcode::Inc, &[]);
3975            self.emit_jump(Opcode::Goto, top, &[]);
3976            self.place_label(done);
3977            self.emit(Opcode::Drop, &[]);
3978            self.emit(Opcode::Drop, &[]);
3979            self.destructure_rest(rest, decl)?;
3980        }
3981        self.emit(Opcode::IteratorClose, &[]);
3982        Ok(())
3983    }
3984
3985    /// `{…}` on the left: read properties off one boxed source object.
3986    fn destructure_object(
3987        &mut self,
3988        properties: &[Option<PatternElement>],
3989        rest: &Option<Box<RestElement>>,
3990        decl: Option<VarDeclKind>,
3991        pattern: &Pattern,
3992    ) -> Result<(), SyntaxError> {
3993        // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
3994        // aside for the rest element below.
3995        self.emit(Opcode::ToObject, &[]);
3996        let mut taken: Vec<Wtf8> = Vec::new();
3997        // Whether any key was computed, which a rest element cannot exclude.
3998        let mut computed = false;
3999        for property in properties {
4000            let Some(PatternElement::Property {
4001                key, value, span, ..
4002            }) = property
4003            else {
4004                return Err(SyntaxError::new(
4005                    "a bare pattern is not a valid object property",
4006                    properties
4007                        .iter()
4008                        .flatten()
4009                        .map(|element| match element {
4010                            PatternElement::Pattern(pattern) => pattern.span,
4011                            PatternElement::Property { span, .. } => *span,
4012                        })
4013                        .next()
4014                        .unwrap_or(pattern.span),
4015                ));
4016            };
4017            // Every read needs the source twice: to read from, and to keep for the next
4018            // property. `get_field2` is that duplicate-and-read in one instruction, but it
4019            // leaves the copy *under* the value, so it is only usable when whatever
4020            // consumes the value tolerates that. See [`reads_with_get_field2`].
4021            let nested = reads_with_get_field2(decl, value);
4022            if !nested {
4023                self.emit(Opcode::Dup, &[]);
4024            }
4025            match key {
4026                PropName::Literal(literal) => {
4027                    let name = self.property_key_text(literal, *span)?;
4028                    taken.push(name.clone());
4029                    self.emit(
4030                        if nested {
4031                            Opcode::GetField2
4032                        } else {
4033                            Opcode::GetField
4034                        },
4035                        &[Op::Atom(Atom::from_wtf8(&name))],
4036                    );
4037                }
4038                PropName::Computed(index) => {
4039                    // A computed key has no name to exclude ahead of time, so a rest
4040                    // element that has to skip it is refused below rather than silently
4041                    // copying the property into the rest object.
4042                    computed = true;
4043                    self.expr(index)?;
4044                    self.emit(Opcode::GetArrayEl, &[]);
4045                }
4046                PropName::Private(_) => {
4047                    return Err(SyntaxError::new(
4048                        "private fields are not supported by the compiler yet",
4049                        value.span,
4050                    ));
4051                }
4052            }
4053            self.destructure(value, decl)?;
4054        }
4055        match rest {
4056            Some(rest) => {
4057                if computed {
4058                    return Err(SyntaxError::new(
4059                        "a computed key with a rest element is not supported by the compiler yet",
4060                        Self::rest_span(rest),
4061                    ));
4062                }
4063                // `target src exclude`: the exclusion list is an array of the keys the
4064                // literal part already took, so the rest object gets only the others.
4065                self.emit(Opcode::Object, &[]);
4066                self.emit(Opcode::Swap, &[]);
4067                for name in &taken {
4068                    self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
4069                }
4070                self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
4071                self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4072                self.emit(Opcode::Drop, &[]);
4073                self.emit(Opcode::Drop, &[]);
4074                self.destructure_rest(rest, decl)?;
4075            }
4076            // The source was only kept for a rest element.
4077            None => self.emit(Opcode::Drop, &[]),
4078        }
4079        Ok(())
4080    }
4081
4082    /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
4083    fn destructure_rest(
4084        &mut self,
4085        rest: &RestElement,
4086        decl: Option<VarDeclKind>,
4087    ) -> Result<(), SyntaxError> {
4088        match rest {
4089            RestElement::Pattern(pattern) => self.destructure(pattern, decl),
4090            // `[...a.b] = c` stores into a property.
4091            RestElement::Member(member) => {
4092                let pattern = Pattern {
4093                    kind: PatternKind::Member(member.clone()),
4094                    span: member.span,
4095                };
4096                self.destructure(&pattern, decl)
4097            }
4098        }
4099    }
4100
4101    /// The source range of a rest element, for error messages.
4102    fn rest_span(rest: &RestElement) -> Span {
4103        match rest {
4104            RestElement::Pattern(pattern) => pattern.span,
4105            RestElement::Member(member) => member.span,
4106        }
4107    }
4108
4109    /// Compile a function declaration and queue it for instantiation at scope
4110    /// entry.
4111    ///
4112    /// A declaration is visible before the statement that declares it, so the
4113    /// code that creates the function object belongs at the top of the enclosing
4114    /// scope, not at the declaration.
4115    fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
4116        let name = func.name.as_ref().expect("a declaration has a name");
4117        let function = self.compile_function(func)?;
4118        let pool_index = self.push_constant(Constant::Function(Box::new(function)));
4119        let target = self.hoist_target(&name.name);
4120        let block = self.cur().current_block;
4121        self.state().hoisted.push((block, target, pool_index));
4122        Ok(())
4123    }
4124
4125    /// Where a name lives, for a hoisted declaration.
4126    fn hoist_target(&self, name: &str) -> HoistTarget {
4127        let state = self.cur();
4128        if let Some(index) = state.args.iter().position(|a| a.name == name) {
4129            return HoistTarget::Arg(index as u32);
4130        }
4131        if let Some(index) = state.vars.iter().position(|v| v.name == name) {
4132            return HoistTarget::Loc(index as u32);
4133        }
4134        // A global function declaration is not a slot at all.
4135        HoistTarget::Global(name.to_string())
4136    }
4137
4138    // -- expressions -------------------------------------------------------
4139
4140    /// Compile one expression, recording where its instructions sit.
4141    ///
4142    /// The position is the node's operator when it has one and its first token
4143    /// otherwise, and it is restored on the way out so a parent's own instructions —
4144    /// which are emitted *after* its children — are blamed on the parent. Without the
4145    /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4146    fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4147        let saved = self.cur().cur_pos;
4148        // Only the node kinds the reference calls `emit_source_pos` for record a position:
4149        // the operator a node exists for, and a variable *read*, which the reference
4150        // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4151        // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4152        // start, a parenthesised group, an anonymous function expression — leaves the
4153        // previous position in place, because a table entry the reference never writes is
4154        // one we must not write either: the instruction that inherits a position (the
4155        // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4156        // report a more recent token than the reference does.
4157        let pos = expr.op_pos.or(match &expr.kind {
4158            ExprKind::Ident(ident) => Some(ident.span.start),
4159            _ => None,
4160        });
4161        match pos {
4162            Some(pos) => self.state().cur_pos = Some(pos),
4163            // A node the reference records nothing for: its own instructions stay
4164            // unpositioned, so they inherit whatever was written last — which is what an
4165            // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4166            // enclosing position instead would blame them on a token the reference has not
4167            // reached yet: a spread's `iterator_open` reports the expression it follows, and
4168            // a template's `to_propkey` the interpolation.
4169            None => self.state().cur_pos = None,
4170        }
4171        // Note a direct `eval` call before compiling it, because the *whole* function
4172        // is affected: an eval can name any binding the function declares, so every one
4173        // of them has to live in a cell for a closure it creates to capture it.
4174        if Self::is_direct_eval(expr) {
4175            // Every enclosing function is affected too: the eval sees the whole scope
4176            // chain, and a closure it creates can capture a binding of any of them.
4177            // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a
4178            // cell, because the closure the eval builds outlives the loop iteration.
4179            for state in &mut self.stack {
4180                state.has_direct_eval = true;
4181            }
4182            let block = self.cur().current_block;
4183            let in_params = self.cur().in_params;
4184            self.state()
4185                .pending_eval_sites
4186                .push((expr.span, block, in_params));
4187        }
4188        let result = self.expr_inner(expr);
4189        self.state().cur_pos = saved;
4190        result
4191    }
4192
4193    /// Record which bindings are in scope at a direct `eval` call.
4194    ///
4195    /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
4196    /// resolves names from a string at run time, so the only chance to pin down *which*
4197    /// slot a name means is here. Visibility is the lexical rule: a binding counts when
4198    /// its block is the current block, an enclosing one, or the function scope.
4199    fn materialize_eval_sites(&mut self) {
4200        let pending = std::mem::take(&mut self.state().pending_eval_sites);
4201        for (span, site_block, in_params) in pending {
4202            self.resolve_eval_site(span, site_block, in_params);
4203        }
4204    }
4205
4206    /// Resolve the bindings visible at one `eval` call.
4207    fn resolve_eval_site(&mut self, span: Span, site_block: u64, site_in_params: bool) {
4208        /// How near a binding is: function distance first, then block depth, then the
4209        /// later declaration (which shadows the earlier one in the same block).
4210        type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
4211
4212        // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
4213        // walked, innermost function first: a direct `eval` sees every enclosing
4214        // function's bindings, and none of them can be resolved at run time because the
4215        // runtime only has names to go on.
4216        let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
4217        let deepest = self.stack.len() - 1;
4218        for (level, state) in self.stack.iter().enumerate().rev() {
4219            let owner = (deepest - level) as u32;
4220            // The innermost function's block is the one the call sat in, which is not
4221            // the block the compiler is in now; the enclosing functions are still at
4222            // the point where this one was created.
4223            let here = if level == deepest {
4224                site_block
4225            } else {
4226                state.current_block
4227            };
4228            // The chain of live blocks, innermost first, with a depth for each. The walk
4229            // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
4230            // block can start at source offset zero.
4231            let mut live: Vec<(u64, usize)> = vec![(here, 0)];
4232            let mut block = here;
4233            while let Some(parent) = state
4234                .blocks
4235                .iter()
4236                .find(|candidate| candidate.key == block)
4237                .map(|candidate| candidate.parent)
4238                .filter(|parent| *parent != NO_PARENT)
4239                .filter(|parent| parent != &block)
4240            {
4241                live.push((parent, live.len()));
4242                block = parent;
4243            }
4244            let depth_of = |key: u64| {
4245                live.iter()
4246                    .find(|(candidate, _)| *candidate == key)
4247                    .map(|(_, depth)| *depth)
4248                    // The function scope is the outermost depth there is. A binding of a
4249                    // block this site is not inside lands here too, which pushes it
4250                    // behind every live one — the right answer: it is out of scope.
4251                    .unwrap_or(live.len())
4252            };
4253            for (index, arg) in state.args.iter().enumerate() {
4254                bindings.push((
4255                    (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
4256                    EvalVisible {
4257                        name: arg.name.clone(),
4258                        is_arg: true,
4259                        index: index as u32,
4260                        owner,
4261                    },
4262                ));
4263            }
4264            // A parameter list cannot see the body, so a body `var` is not a binding the
4265            // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
4266            // not let that eval write the body's `c`.
4267            let hides_body = if level == deepest {
4268                site_in_params
4269            } else {
4270                state.created_in_params
4271            };
4272            for (index, var) in state.vars.iter().enumerate() {
4273                let block = state
4274                    .var_block
4275                    .get(index)
4276                    .copied()
4277                    .unwrap_or(FUNCTION_SCOPE);
4278                if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
4279                    continue;
4280                }
4281                bindings.push((
4282                    (
4283                        owner as usize,
4284                        depth_of(block),
4285                        std::cmp::Reverse(index as u32),
4286                    ),
4287                    EvalVisible {
4288                        name: var.name.clone(),
4289                        is_arg: false,
4290                        index: index as u32,
4291                        owner,
4292                    },
4293                ));
4294            }
4295        }
4296        // Innermost function first, then innermost block, then the later declaration
4297        // (which shadows the earlier one within a block).
4298        bindings.sort_by_key(|(priority, _)| *priority);
4299        let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
4300        self.state().eval_sites.push(EvalSite {
4301            line: span.start.line,
4302            column: span.start.column,
4303            bindings,
4304        });
4305    }
4306
4307    /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
4308    ///
4309    /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
4310    /// a bare identifier callee counts.
4311    fn is_direct_eval(expr: &Expr) -> bool {
4312        matches!(
4313            &expr.kind,
4314            ExprKind::Call { callee, .. }
4315                if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
4316        )
4317    }
4318
4319    fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4320        match &expr.kind {
4321            ExprKind::Number(value) => self.push_number(*value),
4322            ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
4323            ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
4324            ExprKind::Null => self.emit(Opcode::Null, &[]),
4325            ExprKind::String(text) => self.push_string(text),
4326            ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
4327            ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
4328            ExprKind::This => self.this_expression(),
4329            ExprKind::NewTarget => self.new_target_expression(),
4330            ExprKind::Paren(inner) => self.expr(inner)?,
4331            ExprKind::Binary { op, left, right } => {
4332                self.expr(left)?;
4333                self.expr(right)?;
4334                self.emit(binary_opcode(*op), &[]);
4335            }
4336            ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
4337            ExprKind::Unary {
4338                op: UnaryOp::Minus,
4339                argument,
4340            } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
4341                let ExprKind::Number(value) = argument.unparen().kind else {
4342                    unreachable!("matched above")
4343                };
4344                // The reference folds a negative literal only when the negation is
4345                // exact in the integer range: `-1` becomes `push_minus1` and
4346                // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
4347                // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
4348                // `-Infinity`, not `Infinity` — and folding a fraction would change
4349                // which instruction the reference emits.
4350                let negated = -value;
4351                // `-2147483648` is deliberately excluded: its magnitude is one past
4352                // `i32::MAX`, so the reference sends it through the constant pool and
4353                // negates at run time instead.
4354                if value > 0.0
4355                    && negated == negated.trunc()
4356                    && negated >= -(i32::MAX as f64)
4357                    && negated < 0.0
4358                {
4359                    self.push_number(negated);
4360                } else {
4361                    self.push_number(value);
4362                    self.emit(Opcode::Neg, &[]);
4363                }
4364            }
4365            ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
4366            ExprKind::Conditional { test, cons, alt } => {
4367                let else_label = self.new_label();
4368                let end_label = self.new_label();
4369                self.expr(test)?;
4370                self.emit_jump(Opcode::IfFalse, else_label, &[]);
4371                self.expr(cons)?;
4372                self.emit_jump(Opcode::Goto, end_label, &[]);
4373                self.place_label(else_label);
4374                self.expr(alt)?;
4375                self.place_label(end_label);
4376            }
4377            ExprKind::Assign { op, target, value } => self.assign(*op, target, value)?,
4378            ExprKind::Update {
4379                op,
4380                argument,
4381                prefix,
4382            } => self.update(*op, argument, *prefix)?,
4383            ExprKind::Sequence(items) => {
4384                for (index, item) in items.iter().enumerate() {
4385                    self.expr(item)?;
4386                    if index + 1 != items.len() {
4387                        self.emit(Opcode::Drop, &[]);
4388                    }
4389                }
4390            }
4391            ExprKind::Call { .. } => self.chain_link_top(expr)?,
4392            ExprKind::Member { .. } => self.chain_link_top(expr)?,
4393            ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
4394            ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
4395            ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
4396            ExprKind::Template(template) => self.template_literal(template)?,
4397            ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
4398            ExprKind::New { callee, arguments } => {
4399                // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
4400                // The `dup` is not redundant: `call_constructor` takes the
4401                // constructor twice, once as the target and once as `new.target`,
4402                // which is what makes `new.target === C` inside the body.
4403                self.expr(callee)?;
4404                self.emit(Opcode::Dup, &[]);
4405                let args = arguments.as_deref().unwrap_or(&[]);
4406                if Self::has_spread(args) {
4407                    // `C C array`: the duplicated callee is already both the target
4408                    // and `new.target`, so no reordering is needed before `apply 1`.
4409                    self.argument_array(args)?;
4410                    self.emit(Opcode::Apply, &[Op::Int(1)]);
4411                    return Ok(());
4412                }
4413                for argument in args {
4414                    self.expr(argument)?;
4415                }
4416                self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
4417            }
4418            ExprKind::Class(class) => self.class_definition(class, true)?,
4419            ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
4420            ExprKind::Yield { argument, delegate } => {
4421                self.yield_expression(argument.as_deref(), *delegate)?
4422            }
4423            ExprKind::Await(argument) => self.await_expression(argument)?,
4424            ExprKind::RegExp { pattern, flags } => {
4425                // A literal is compiled *here*, at parse time, not when the line runs. The
4426                // spec is explicit that an invalid pattern is an early error (§12.9.4:
4427                // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
4428                // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
4429                // also validates `\p{…}` names: 163 conformance cases are patterns that have
4430                // to be rejected before any code runs.
4431                //
4432                // This is the whole reason the engine lives in its own crate rather than
4433                // inside `quickjs-pure`: the compiler could not depend on the interpreter
4434                // (`pure` depends on `compile`), but both need this.
4435                // The lexer already rejected an unknown or repeated flag, so an unparsable
4436                // flag string here would be a bug in the lexer rather than in the script;
4437                // fall back to the default flags instead of inventing a second message.
4438                let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
4439                let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
4440                    SyntaxError::new(
4441                        format!("invalid regular expression: {}", error.message),
4442                        expr.span,
4443                    )
4444                })?;
4445                // The tree is thrown away and rebuilt when the literal first runs: keeping it
4446                // would mean serialising the syntax tree into the function's constant pool,
4447                // and a literal is created once per evaluation of its expression anyway.
4448                let _ = parsed;
4449                // The pattern and its flags travel as two string constants; `regexp` builds
4450                // the object. A dedicated opcode (rather than a call to the constructor) is
4451                // what the reference does too, so that a literal never goes through the
4452                // public `RegExp` function and its string-coercion rules.
4453                self.push_string(&Wtf8::new(pattern));
4454                self.push_string(&Wtf8::new(flags));
4455                self.emit(Opcode::Regexp, &[]);
4456            }
4457            ExprKind::Arrow(func) => {
4458                let function = self.compile_function(func)?;
4459                let index = self.push_constant(Constant::Function(Box::new(function)));
4460                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4461            }
4462            ExprKind::Function(func) => {
4463                let function = self.compile_function_with_name(func, true)?;
4464                let index = self.push_constant(Constant::Function(Box::new(function)));
4465                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4466            }
4467            // `import.meta`: the host fills a per-module object at link time.
4468            ExprKind::ImportMeta => {
4469                self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
4470            }
4471            // `import("x")` compiles to a two-slot push followed by one opcode: the
4472            // specifier, then the options object (`undefined` here, since this compiler
4473            // does not accept the second argument yet).
4474            ExprKind::ImportCall(specifier) => {
4475                self.expr(specifier)?;
4476                self.emit(Opcode::Undefined, &[]);
4477                self.emit(Opcode::Import, &[]);
4478            }
4479            ExprKind::PrivateIn { name, object } => {
4480                // `#x in o`: the object, then the binding, then one opcode which decides what
4481                // to do with the second operand. A field's binding holds a symbol and the
4482                // answer is an own-property test; a method's holds a function and the answer
4483                // is a brand check — both live in `private_in`, so the compiler emits the
4484                // same instruction for either.
4485                self.expr(object)?;
4486                self.emit_var(VarAction::Get, &format!("#{}", name.name));
4487                self.emit(Opcode::PrivateIn, &[]);
4488            }
4489            _ => {
4490                return Err(SyntaxError::new(
4491                    "this expression form is not supported by the compiler yet",
4492                    expr.span,
4493                ));
4494            }
4495        }
4496        Ok(())
4497    }
4498
4499    /// Build one array holding the evaluated call arguments, which is how a call
4500    /// containing a spread is compiled: the reference does the same, building the
4501    /// list on the stack and handing it to `apply`.
4502    fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
4503        let elements: Vec<Option<ArrayElement>> = arguments
4504            .iter()
4505            .map(|argument| match &argument.unparen().kind {
4506                ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
4507                _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
4508            })
4509            .collect();
4510        self.array_literal(&elements, Span::default())
4511    }
4512
4513    /// Whether any argument is a spread, which is what selects the `apply` form.
4514    fn has_spread(arguments: &[Expr]) -> bool {
4515        arguments
4516            .iter()
4517            .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
4518    }
4519
4520    /// Compile `a${x}b`.
4521    ///
4522    /// A template is a `+` chain built left to right: the leading chunk (or an empty
4523    /// string when the template starts with a substitution), then for each
4524    /// substitution its value, `to_propkey` and `add`, then the following chunk when
4525    /// it is not empty. `to_propkey` is what makes a number or object substitute the
4526    /// way `ToString` would while leaving the result a string for `add` to
4527    /// concatenate.
4528    ///
4529    /// The chunk is an atom rather than a constant-pool string, because a non-empty
4530    /// chunk always lands where a value is pushed and `push_atom_value` is the
4531    /// instruction the reference uses for it; the empty first chunk has its own
4532    /// zero-byte form.
4533    fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
4534        let first = template.quasis.first();
4535        match first.and_then(|quasi| quasi.cooked.clone()) {
4536            Some(text) if !text.is_empty() => {
4537                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4538            }
4539            // Either the template begins with a substitution, or the chunk is
4540            // empty — in both cases the chain needs a string to start from.
4541            _ => self.emit(Opcode::PushEmptyString, &[]),
4542        }
4543        for (index, expression) in template.expressions.iter().enumerate() {
4544            self.expr(expression)?;
4545            self.emit(Opcode::ToPropkey, &[]);
4546            self.emit(Opcode::Add, &[]);
4547            if let Some(text) = template
4548                .quasis
4549                .get(index + 1)
4550                .and_then(|quasi| quasi.cooked.clone())
4551                && !text.is_empty()
4552            {
4553                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4554                self.emit(Opcode::Add, &[]);
4555            }
4556        }
4557        Ok(())
4558    }
4559
4560    /// Compile an object literal.
4561    ///
4562    /// The object is built in place: `object` pushes it, and each property leaves it
4563    /// on the stack with one field more, so no temporary is needed and later
4564    /// properties can overwrite earlier ones.
4565    ///
4566    /// The instruction depends on *how* the property was written, not on what kind
4567    /// of value it holds:
4568    ///
4569    /// | source | instruction |
4570    /// |---|---|
4571    /// | `{ a: v }` | `define_field a` |
4572    /// | `{ __proto__: v }` | `set_proto` |
4573    /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
4574    /// | `{ m() {} }` | `define_method m,4` |
4575    /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
4576    /// | `{ [k]() {} }` | `define_method_computed 4` |
4577    /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
4578    ///
4579    /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
4580    /// key itself, which is why the trailing `drop` is absent there too.
4581    /// `tag`…``: a call whose first argument is the call site's template object.
4582    ///
4583    /// The template object is a frozen array of the cooked chunks with a frozen `raw`
4584    /// array beside it, so `String.raw` can read the source text back. It is a constant
4585    /// because its contents never change; the reference builds one per call site and
4586    /// reuses it, while this builds one per evaluation, which only `tag` code that
4587    /// compares template objects across calls could tell apart.
4588    fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
4589        let cooked = quasi
4590            .quasis
4591            .iter()
4592            .map(|chunk| chunk.cooked.clone())
4593            .collect();
4594        let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
4595        let index = self.push_constant(Constant::Template { cooked, raw });
4596        let count = quasi.expressions.len() + 1;
4597        // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
4598        if let ExprKind::Member {
4599            object, property, ..
4600        } = &tag.unparen().kind
4601        {
4602            self.expr(object)?;
4603            match property {
4604                MemberProp::Ident(name) => {
4605                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
4606                }
4607                MemberProp::Computed(key) => {
4608                    self.expr(key)?;
4609                    self.emit(Opcode::GetArrayEl2, &[]);
4610                }
4611                MemberProp::Private(name) => {
4612                    let binding = format!("#{}", name.name);
4613                    let (kind, _) = self.private_use(&binding, tag.span)?;
4614                    self.private_callee(&binding, kind)?;
4615                }
4616            }
4617            self.emit(Opcode::PushConst, &[Op::Const(index)]);
4618            for expression in &quasi.expressions {
4619                self.expr(expression)?;
4620            }
4621            self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
4622            return Ok(());
4623        }
4624        self.expr(tag)?;
4625        self.emit(Opcode::PushConst, &[Op::Const(index)]);
4626        for expression in &quasi.expressions {
4627            self.expr(expression)?;
4628        }
4629        self.emit(Opcode::Call, &[Op::Int(count as i32)]);
4630        Ok(())
4631    }
4632
4633    fn object_literal(
4634        &mut self,
4635        properties: &[ObjectProperty],
4636        span: Span,
4637    ) -> Result<(), SyntaxError> {
4638        self.emit(Opcode::Object, &[]);
4639        for property in properties {
4640            match property {
4641                ObjectProperty::Spread(value) => {
4642                    // `copy_data_properties` takes the target, the source and an
4643                    // exclusion list; a literal `null` means "exclude nothing".
4644                    // Flag bit 1 copies symbols, bits 2/5 pick the source and the
4645                    // exclusion list by stack offset.
4646                    self.expr(spread_argument(value))?;
4647                    self.emit(Opcode::Null, &[]);
4648                    self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4649                    self.emit(Opcode::Drop, &[]);
4650                    self.emit(Opcode::Drop, &[]);
4651                }
4652                ObjectProperty::Property {
4653                    key,
4654                    value,
4655                    kind,
4656                    shorthand,
4657                    span: property_span,
4658                } => match key {
4659                    PropName::Computed(key_expr) => {
4660                        self.expr(key_expr)?;
4661                        match kind {
4662                            PropertyKind::Value => {
4663                                self.emit(Opcode::ToPropkey, &[]);
4664                                self.expr(value)?;
4665                                self.set_name_if_anonymous_computed(value);
4666                                self.emit(Opcode::DefineArrayEl, &[]);
4667                                // `define_array_el` leaves the object and the key;
4668                                // the key is no longer needed.
4669                                self.emit(Opcode::Drop, &[]);
4670                            }
4671                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4672                                self.emit_method_function(value)?;
4673                                self.emit(
4674                                    Opcode::DefineMethodComputed,
4675                                    &[Op::Int(define_method_flags(*kind))],
4676                                );
4677                            }
4678                        }
4679                    }
4680                    PropName::Literal(key) => {
4681                        let name = self.property_key_text(key, *property_span)?;
4682                        match kind {
4683                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4684                                self.emit_method_function(value)?;
4685                                self.emit(
4686                                    Opcode::DefineMethod,
4687                                    &[
4688                                        Op::Atom(Atom::from_wtf8(&name)),
4689                                        Op::Int(define_method_flags(*kind)),
4690                                    ],
4691                                );
4692                            }
4693                            PropertyKind::Value => {
4694                                self.expr(value)?;
4695                                // `{__proto__: x}` sets the prototype instead of
4696                                // creating a property; the shorthand `{__proto__}`
4697                                // is an ordinary property and does not.
4698                                if name == "__proto__" && !shorthand {
4699                                    self.emit(Opcode::SetProto, &[]);
4700                                } else {
4701                                    self.set_name_if_anonymous(value, &name);
4702                                    self.emit(
4703                                        Opcode::DefineField,
4704                                        &[Op::Atom(Atom::from_wtf8(&name))],
4705                                    );
4706                                }
4707                            }
4708                        }
4709                    }
4710                    PropName::Private(_) => {
4711                        return Err(SyntaxError::new(
4712                            "private names are not valid in object literals",
4713                            *property_span,
4714                        ));
4715                    }
4716                },
4717            }
4718        }
4719        let _ = span;
4720        Ok(())
4721    }
4722
4723    /// Emit the function a method/accessor property defines.
4724    fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
4725        self.expr(value)
4726    }
4727
4728    /// The name a literal property key contributes.
4729    ///
4730    /// String keys are used as written. A numeric key is converted the way
4731    /// `ToString` would convert it, because the atom is made from that spelling:
4732    /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
4733    fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
4734        match key {
4735            PropKey::Str(text) => Ok(text.clone()),
4736            PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
4737        }
4738    }
4739
4740    /// Compile an optional chain.
4741    ///
4742    /// `?.` short-circuits the *whole remaining spine*, not just its own link:
4743    /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
4744    /// `undefined`. So the chain is compiled with one end label and every guard
4745    /// jumps to it. The parser hands us the extent of that spine as an
4746    /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
4747    /// exactly the scope the label has to cover.
4748    fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
4749        let end = self.new_label();
4750        self.chain_link(inner, end)?;
4751        self.place_label(end);
4752        Ok(())
4753    }
4754
4755    /// A member access or call reached from outside any optional chain.
4756    ///
4757    /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
4758    /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
4759    /// still created because [`Self::chain_link`] takes it, and placing it at the
4760    /// end is a no-op that keeps a single code path.
4761    fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4762        let end = self.new_label();
4763        self.chain_link(expr, end)?;
4764        self.place_label(end);
4765        Ok(())
4766    }
4767
4768    /// One link of a chain, where `end` is the label a `?.` guard jumps to.
4769    fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
4770        match &expr.kind {
4771            ExprKind::Member {
4772                object,
4773                property,
4774                optional,
4775            } => {
4776                // `super.x` is not a lookup on a value: it starts at the home object's
4777                // prototype and keeps `this` as the receiver, so it cannot go through
4778                // `chain_link` and the ordinary field read.
4779                if matches!(object.unparen().kind, ExprKind::SuperProp) {
4780                    self.super_base();
4781                    match property {
4782                        MemberProp::Ident(name) => self.emit(
4783                            Opcode::PushAtomValue,
4784                            &[Op::Atom(Atom::from_text(&name.name))],
4785                        ),
4786                        MemberProp::Computed(index) => self.expr(index)?,
4787                        MemberProp::Private(_) => {
4788                            return Err(SyntaxError::new(
4789                                "private fields are not supported by the compiler yet",
4790                                expr.span,
4791                            ));
4792                        }
4793                    }
4794                    self.emit(Opcode::GetSuperValue, &[]);
4795                    return Ok(());
4796                }
4797                self.chain_link(object, end)?;
4798                if *optional {
4799                    self.optional_guard(end);
4800                }
4801                match property {
4802                    // `.length` has its own opcode. The reference emits it for every
4803                    // object, not just arrays, so a name-based rule is right and
4804                    // cheaper than the generic field read.
4805                    MemberProp::Ident(name) if name.name == "length" => {
4806                        self.emit(Opcode::GetLength, &[]);
4807                    }
4808                    MemberProp::Ident(name) => {
4809                        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
4810                    }
4811                    MemberProp::Computed(index) => {
4812                        self.expr(index)?;
4813                        self.emit(Opcode::GetArrayEl, &[]);
4814                    }
4815                    MemberProp::Private(name) => {
4816                        // The binding comes from the class scope, so a read from outside the
4817                        // class cannot name it at all. `?.` checks the object, not the field:
4818                        // `o?.#x` guards on `o` being nullish.
4819                        let binding = format!("#{}", name.name);
4820                        let (kind, _) = self.private_use(&binding, expr.span)?;
4821                        self.private_load(&binding, kind, expr.span)?;
4822                    }
4823                }
4824                Ok(())
4825            }
4826            ExprKind::Call {
4827                callee,
4828                arguments,
4829                optional,
4830            } => {
4831                // `o.m(args)` has to pass `o` as `this`, which a plain `call`
4832                // cannot: it reads the function and then calls it with no
4833                // receiver at all. The reference's answer is to keep the object
4834                // under the function value — `get_field2` reads a field and leaves
4835                // its base in place — and to use `call_method`, which takes the
4836                // receiver from the stack. Missing this does not just cost an
4837                // instruction, it loses the `this` binding.
4838                if let ExprKind::Member {
4839                    object,
4840                    property,
4841                    optional: member_optional,
4842                } = &callee.unparen().kind
4843                {
4844                    // `super.m()` reads the method off the home object's prototype but
4845                    // calls it with `this`, so the receiver goes under the read instead of
4846                    // being replaced by it.
4847                    if matches!(object.unparen().kind, ExprKind::SuperProp) {
4848                        self.super_base();
4849                        match property {
4850                            MemberProp::Ident(name) => self.emit(
4851                                Opcode::PushAtomValue,
4852                                &[Op::Atom(Atom::from_text(&name.name))],
4853                            ),
4854                            MemberProp::Computed(index) => self.expr(index)?,
4855                            MemberProp::Private(_) => {
4856                                return Err(SyntaxError::new(
4857                                    "private fields are not supported by the compiler yet",
4858                                    expr.span,
4859                                ));
4860                            }
4861                        }
4862                        // The two-output form would drop the receiver; this one replaces
4863                        // the prototype and the key, leaving `this` underneath.
4864                        self.emit(Opcode::GetArrayEl, &[]);
4865                        if Self::has_spread(arguments) {
4866                            self.argument_array(arguments)?;
4867                            self.emit(Opcode::Perm3, &[]);
4868                            self.emit(Opcode::Apply, &[Op::Int(0)]);
4869                            return Ok(());
4870                        }
4871                        for argument in arguments {
4872                            self.expr(argument)?;
4873                        }
4874                        self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4875                        return Ok(());
4876                    }
4877                    self.chain_link(object, end)?;
4878                    if *member_optional {
4879                        self.optional_guard(end);
4880                    }
4881                    match property {
4882                        MemberProp::Ident(name) => {
4883                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4884                        }
4885                        MemberProp::Computed(index) => {
4886                            self.expr(index)?;
4887                            // The key is not needed after the read, so this is the
4888                            // two-output form: object, value.
4889                            self.emit(Opcode::GetArrayEl2, &[]);
4890                        }
4891                        MemberProp::Private(name) => {
4892                            // The receiver is already under the callee, which is exactly the
4893                            // shape `call_method` and `apply` want — so nothing is dropped.
4894                            let binding = format!("#{}", name.name);
4895                            let (kind, _) = self.private_use(&binding, expr.span)?;
4896                            self.private_callee(&binding, kind)?;
4897                        }
4898                    }
4899                    if Self::has_spread(arguments) {
4900                        // Stack is `obj func`; the array goes on top, then `perm3`
4901                        // reorders to the `func this array` that `apply` wants.
4902                        self.argument_array(arguments)?;
4903                        self.emit(Opcode::Perm3, &[]);
4904                        self.emit(Opcode::Apply, &[Op::Int(0)]);
4905                        return Ok(());
4906                    }
4907                    for argument in arguments {
4908                        self.expr(argument)?;
4909                    }
4910                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4911                    return Ok(());
4912                }
4913                // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
4914                // with `get_field2` so the base stays under it, and on the short-circuit
4915                // path pushes an extra `undefined` as a placeholder receiver — the call
4916                // then throws, which is what calling a missing optional chain should do.
4917                if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
4918                    && let ExprKind::Member {
4919                        object,
4920                        property,
4921                        optional: member_optional,
4922                    } = &inner.unparen().kind
4923                {
4924                    let call = self.new_label();
4925                    // A guard target of its own: the outer `end` skips the whole
4926                    // expression, and a short-circuited receiver still has to reach the
4927                    // call so that calling it throws.
4928                    let short = self.new_label();
4929                    self.chain_link(object, end)?;
4930                    if *member_optional {
4931                        self.optional_guard(short);
4932                    }
4933                    match property {
4934                        MemberProp::Ident(name) => {
4935                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4936                        }
4937                        MemberProp::Computed(index) => {
4938                            self.expr(index)?;
4939                            self.emit(Opcode::GetArrayEl2, &[]);
4940                        }
4941                        MemberProp::Private(name) => {
4942                            let binding = format!("#{}", name.name);
4943                            let (kind, _) = self.private_use(&binding, expr.span)?;
4944                            self.private_callee(&binding, kind)?;
4945                        }
4946                    }
4947                    self.emit_jump(Opcode::Goto, call, &[]);
4948                    self.place_label(short);
4949                    self.emit(Opcode::Undefined, &[]);
4950                    self.place_label(call);
4951                    if Self::has_spread(arguments) {
4952                        self.argument_array(arguments)?;
4953                        self.emit(Opcode::Perm3, &[]);
4954                        self.emit(Opcode::Apply, &[Op::Int(0)]);
4955                        return Ok(());
4956                    }
4957                    for argument in arguments {
4958                        self.expr(argument)?;
4959                    }
4960                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4961                    return Ok(());
4962                }
4963                self.chain_link(callee, end)?;
4964                if *optional {
4965                    self.optional_guard(end);
4966                }
4967                if Self::has_spread(arguments) {
4968                    // `func array -> func undefined array`, which is the plain-call
4969                    // form of `apply`: the receiver is `undefined`.
4970                    self.argument_array(arguments)?;
4971                    self.emit(Opcode::Undefined, &[]);
4972                    self.emit(Opcode::Swap, &[]);
4973                    self.emit(Opcode::Apply, &[Op::Int(0)]);
4974                    return Ok(());
4975                }
4976                for argument in arguments {
4977                    self.expr(argument)?;
4978                }
4979                self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
4980                Ok(())
4981            }
4982            _ => self.expr(expr),
4983        }
4984    }
4985
4986    /// Compile `expr` as a tail call when it is one, reporting whether it was.
4987    ///
4988    /// `tail_call` reuses the current frame instead of pushing a new one, so a
4989    /// tail-recursive function runs in constant stack space. It also has to be the
4990    /// *last* thing the function does, which is why only a `return` reaches here.
4991    fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
4992        let ExprKind::Call {
4993            callee,
4994            arguments,
4995            optional: false,
4996        } = &expr.unparen().kind
4997        else {
4998            return Ok(false);
4999        };
5000        // A spread call has no tail form: `tail_call` takes its arguments one at a time off
5001        // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
5002        // as an ordinary call costs the one frame the optimisation was saving and keeps the
5003        // semantics — the alternative was reaching the spread expression below and failing
5004        // with "this expression form is not supported", which is how `return super.m(...a)`
5005        // stopped compiling. Checked before anything is emitted, because the decision cannot
5006        // be taken back once `super_base` or a `get_field2` is on the stack.
5007        if Self::has_spread(arguments) {
5008            return Ok(false);
5009        }
5010        let end = self.new_label();
5011        if let ExprKind::Member {
5012            object,
5013            property,
5014            optional: false,
5015        } = &callee.unparen().kind
5016        {
5017            // `super.m()` in tail position is still an ordinary method call with `this`
5018            // as the receiver; only the read of the method differs.
5019            if matches!(object.unparen().kind, ExprKind::SuperProp) {
5020                self.super_base();
5021                match property {
5022                    MemberProp::Ident(name) => self.emit(
5023                        Opcode::PushAtomValue,
5024                        &[Op::Atom(Atom::from_text(&name.name))],
5025                    ),
5026                    MemberProp::Computed(index) => self.expr(index)?,
5027                    MemberProp::Private(_) => return Ok(false),
5028                }
5029                self.emit(Opcode::GetArrayEl, &[]);
5030                for argument in arguments {
5031                    self.expr(argument)?;
5032                }
5033                self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5034                self.place_label(end);
5035                return Ok(true);
5036            }
5037            self.chain_link(object, end)?;
5038            match property {
5039                MemberProp::Ident(name) => {
5040                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5041                }
5042                MemberProp::Computed(index) => {
5043                    self.expr(index)?;
5044                    self.emit(Opcode::GetArrayEl2, &[]);
5045                }
5046                MemberProp::Private(_) => return Ok(false),
5047            }
5048            for argument in arguments {
5049                self.expr(argument)?;
5050            }
5051            self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5052            self.place_label(end);
5053            return Ok(true);
5054        }
5055        self.chain_link(callee, end)?;
5056        for argument in arguments {
5057            self.expr(argument)?;
5058        }
5059        self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
5060        self.place_label(end);
5061        Ok(true)
5062    }
5063
5064    /// The `?.` guard: keep the value if it is neither null nor undefined,
5065    /// otherwise replace it with `undefined` and leave the whole chain.
5066    fn optional_guard(&mut self, end: Label) {
5067        let cont = self.new_label();
5068        self.emit(Opcode::Dup, &[]);
5069        self.emit(Opcode::IsUndefinedOrNull, &[]);
5070        self.emit_jump(Opcode::IfFalse, cont, &[]);
5071        self.emit(Opcode::Drop, &[]);
5072        self.emit(Opcode::Undefined, &[]);
5073        self.emit_jump(Opcode::Goto, end, &[]);
5074        self.place_label(cont);
5075    }
5076
5077    fn push_number(&mut self, value: f64) {
5078        // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
5079        // goes into the constant pool.
5080        if value == value.trunc() && value.abs() <= i32::MAX as f64 {
5081            let int = value as i32;
5082            if (-1..=7).contains(&int) {
5083                self.emit(Opcode::PushI32, &[Op::Int(int)]);
5084                return;
5085            }
5086            if (-128..=127).contains(&int) {
5087                self.emit(Opcode::PushI8, &[Op::Int(int)]);
5088                return;
5089            }
5090            if (-32768..=32767).contains(&int) {
5091                self.emit(Opcode::PushI16, &[Op::Int(int)]);
5092                return;
5093            }
5094            self.emit(Opcode::PushI32, &[Op::Int(int)]);
5095            return;
5096        }
5097        let index = self.push_constant(Constant::Number(value));
5098        self.emit(Opcode::PushConst, &[Op::Const(index)]);
5099    }
5100
5101    /// Push a `BigInt` literal.
5102    ///
5103    /// A value that fits an `i32` uses the immediate form, which is what the reference
5104    /// emits too; anything larger goes into the constant pool, because the operand of
5105    /// `push_bigint` is only four bytes wide.
5106    fn push_bigint(&mut self, digits: &str, radix: u32) {
5107        if radix == 10
5108            && let Ok(value) = digits.parse::<i64>()
5109            && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
5110        {
5111            self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
5112            return;
5113        }
5114        let index = self.push_constant(Constant::BigInt {
5115            digits: digits.to_string(),
5116            radix,
5117        });
5118        self.emit(Opcode::PushConst, &[Op::Const(index)]);
5119    }
5120
5121    fn push_string(&mut self, text: &Wtf8) {
5122        if text.is_empty() {
5123            self.emit(Opcode::PushEmptyString, &[]);
5124            return;
5125        }
5126        self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
5127    }
5128
5129    /// Name an anonymous function from the binding it is assigned to.
5130    ///
5131    /// `var f = function(){}` produces a function whose `name` is `f`, which the
5132    /// runtime cannot know without being told: the function object is created
5133    /// before the store. `set_name` carries the name across.
5134    fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
5135        if value.is_anonymous_function_definition() {
5136            self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
5137        }
5138    }
5139
5140    /// The same, for a computed key: the name comes from the value on the stack
5141    /// rather than from an atom, so a different instruction carries it.
5142    fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
5143        if value.is_anonymous_function_definition() {
5144            self.emit(Opcode::SetNameComputed, &[]);
5145        }
5146    }
5147
5148    /// Compile a function body that exists only in the compiler's head — a class's
5149    /// implicit constructor or its field initialiser.
5150    ///
5151    /// Everything structural is the same as a written function: a fresh `FnState`, its
5152    /// own body block, and resolution while the frame is still on the stack. Only the
5153    /// statements differ.
5154    fn compile_synthetic_function(
5155        &mut self,
5156        name: &str,
5157        strict: bool,
5158        span: Span,
5159        body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
5160    ) -> Result<CompiledFunction, SyntaxError> {
5161        let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
5162        state.span = Some((span.start.offset as usize, span.end.offset as usize));
5163        state.strict = strict;
5164        state.created_in_block = self.cur().current_block;
5165        state.with_names = self.cur().with_names.clone();
5166        state.line = span.start.line;
5167        state.column = span.start.column;
5168        let depth = self.stack.len();
5169        self.stack.push(state);
5170        let body_key = span.start.offset as u64;
5171        self.push_block(body_key, NO_PARENT);
5172        self.state().body_block = body_key;
5173        let result = (|| {
5174            self.emit_scope_enter(body_key);
5175            body(self)?;
5176            if self.end_is_reachable() {
5177                self.emit(Opcode::ReturnUndef, &[]);
5178            }
5179            Ok(())
5180        })();
5181        if result.is_err() {
5182            self.stack.truncate(depth);
5183            return result.map(|()| unreachable!());
5184        }
5185        Ok(self.finish_current())
5186    }
5187
5188    /// The implicit return of a class constructor.
5189    ///
5190    /// A constructor that falls off the end initialises its instance fields first, and a
5191    /// derived one returns `this` — which is what makes `new D()` the object `super()`
5192    /// built rather than `undefined`.
5193    fn emit_class_constructor_tail(&mut self) {
5194        match self.cur().ctor_kind {
5195            CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
5196            // Nothing to install: a base constructor did it in its prologue and a derived
5197            // one at each `super()` site, which is where `this` first exists.
5198            CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
5199            CtorKind::Derived => {
5200                // `get_loc_check` rather than `get_loc`: reaching the end without ever
5201                // running `super()` is a ReferenceError, not `undefined`.
5202                self.emit_var(VarAction::Get, "this");
5203                self.emit(Opcode::Return, &[]);
5204            }
5205        }
5206    }
5207
5208    /// `yield expr` / `yield* expr`.
5209    ///
5210    /// The suspension itself is one instruction: the value is on the stack, `yield` hands
5211    /// it to the caller and parks the frame. On resume the stack holds the value the
5212    /// caller passed *and* a "magic" number saying which method resumed it — `next`
5213    /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
5214    /// `if_false <continue>` asks whether this was an ordinary `next`:
5215    ///
5216    /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
5217    /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
5218    ///   and uses the value sitting under the magic number.
5219    ///
5220    /// A `throw` never reaches here: the interpreter unwinds instead (see
5221    /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
5222    fn yield_expression(
5223        &mut self,
5224        argument: Option<&Expr>,
5225        delegate: bool,
5226    ) -> Result<(), SyntaxError> {
5227        if delegate {
5228            return self.yield_star(argument);
5229        }
5230        // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
5231        // does the same for the `return(v)` that can resume it — which is why an async
5232        // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
5233        // generator's is just `yield`.
5234        let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
5235        match argument {
5236            Some(value) => self.expr(value)?,
5237            None => self.emit(Opcode::Undefined, &[]),
5238        }
5239        if is_async {
5240            self.emit(Opcode::Await, &[]);
5241            self.state().has_await = true;
5242        }
5243        self.emit(Opcode::Yield, &[]);
5244        let resume = self.new_label();
5245        self.emit_jump(Opcode::IfFalse, resume, &[]);
5246        // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
5247        // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
5248        // finished the generator and never ran the `finally`.
5249        if is_async {
5250            self.emit(Opcode::Await, &[]);
5251        }
5252        self.emit_unwind_for_return(true);
5253        self.emit(Opcode::ReturnAsync, &[]);
5254        self.place_label(resume);
5255        // Nothing is emitted here: the value the caller passed to `next` *is* the value
5256        // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
5257        // it through the ordinary expression-statement discard.
5258        Ok(())
5259    }
5260
5261    /// `yield* iterable`.
5262    ///
5263    /// The shape is the reference's, and it is a fall-through chain rather than a
5264    /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
5265    /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
5266    /// the inner iterator and finishes, `throw` forwards the exception into it and
5267    /// continues only if it has a `throw` method.
5268    ///
5269    /// The stack is `iter next catch value` throughout, `catch` being the offset
5270    /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
5271    fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
5272        match argument {
5273            Some(value) => self.expr(value)?,
5274            // The parser rejects a bare `yield*`, so this is unreachable in practice.
5275            None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
5276        }
5277        // `for await of` is the same protocol as `for of` with two differences that matter
5278        // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
5279        // every `next()` result is a promise the delegate has to await.
5280        let is_async = self.cur().kind.is_async();
5281        self.emit(
5282            if is_async {
5283                Opcode::ForAwaitOfStart
5284            } else {
5285                Opcode::ForOfStart
5286            },
5287            &[],
5288        );
5289        self.emit(Opcode::Drop, &[]);
5290        self.emit(Opcode::Undefined, &[]);
5291        self.emit(Opcode::Undefined, &[]);
5292        let next = self.new_label();
5293        let resume = self.new_label();
5294        let finished = self.new_label();
5295        let rethrow = self.new_label();
5296        let throw_no_method = self.new_label();
5297        let done = self.new_label();
5298        self.place_label(next);
5299        self.emit(Opcode::IteratorNext, &[]);
5300        if is_async {
5301            self.emit(Opcode::Await, &[]);
5302            self.state().has_await = true;
5303        }
5304        self.emit(Opcode::IteratorCheckObject, &[]);
5305        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5306        self.emit_jump(Opcode::IfTrue, done, &[]);
5307        // The suspension. `resume` is both the label the return path jumps back to in order
5308        // to yield one more value and where the caller's answer arrives, as the value
5309        // followed by the magic number.
5310        //
5311        // The two forms differ in what they hand the suspension: `yield_star` takes the
5312        // result object itself, `async_yield_star` takes `.value`, because an async
5313        // generator awaits and re-wraps whatever it yields.
5314        self.place_label(resume);
5315        if is_async {
5316            self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5317            self.emit(Opcode::AsyncYieldStar, &[]);
5318        } else {
5319            self.emit(Opcode::YieldStar, &[]);
5320        }
5321        self.emit(Opcode::Dup, &[]);
5322        self.emit_jump(Opcode::IfTrue, rethrow, &[]);
5323        self.emit(Opcode::Drop, &[]);
5324        self.emit_jump(Opcode::Goto, next, &[]);
5325
5326        // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
5327        self.place_label(rethrow);
5328        self.emit(Opcode::PushI32, &[Op::Int(2)]);
5329        self.emit(Opcode::StrictEq, &[]);
5330        self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
5331        // A `return` closes the inner iterator; if it had none, the delegate simply
5332        // finishes with the requested value. In an async generator both the call and its
5333        // result are awaited, because the inner `return` may itself be async.
5334        if is_async {
5335            self.emit(Opcode::Await, &[]);
5336        }
5337        self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
5338        self.emit_jump(Opcode::IfTrue, finished, &[]);
5339        if is_async {
5340            self.emit(Opcode::Await, &[]);
5341        }
5342        self.emit(Opcode::IteratorCheckObject, &[]);
5343        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5344        self.emit_jump(Opcode::IfFalse, resume, &[]);
5345        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5346        self.place_label(finished);
5347        self.emit(Opcode::Nip, &[]);
5348        self.emit(Opcode::Nip, &[]);
5349        self.emit(Opcode::Nip, &[]);
5350        // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
5351        // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
5352        // awaits the value in an async generator and then runs the same `finally`/iterator
5353        // unwinding a written `return` would. Skipping the unwinding made
5354        // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
5355        if is_async {
5356            self.emit(Opcode::Await, &[]);
5357        }
5358        self.emit_unwind_for_return(true);
5359        self.emit(Opcode::ReturnAsync, &[]);
5360
5361        // `throw(e)`: forward it into the inner iterator.
5362        self.place_label(throw_no_method);
5363        self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
5364        let no_throw = self.new_label();
5365        self.emit_jump(Opcode::IfTrue, no_throw, &[]);
5366        if is_async {
5367            self.emit(Opcode::Await, &[]);
5368        }
5369        self.emit(Opcode::IteratorCheckObject, &[]);
5370        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5371        self.emit_jump(Opcode::IfFalse, resume, &[]);
5372        self.emit_jump(Opcode::Goto, done, &[]);
5373        // No `throw` method: close the iterator, then report the spec's TypeError. The
5374        // `if_true` before the `await` is the reference's shape — the flag it consumes is
5375        // what `iterator_call` leaves behind, and a close that *did* find no `return`
5376        // method has nothing to await.
5377        self.place_label(no_throw);
5378        self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
5379        let no_close = self.new_label();
5380        self.emit_jump(Opcode::IfTrue, no_close, &[]);
5381        if is_async {
5382            self.emit(Opcode::Await, &[]);
5383        }
5384        self.place_label(no_close);
5385        self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
5386
5387        // The inner iterator finished: the delegate's value is the `yield*` expression's
5388        // value, so it is left on the stack for whatever consumes it.
5389        self.place_label(done);
5390        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5391        self.emit(Opcode::Nip, &[]);
5392        self.emit(Opcode::Nip, &[]);
5393        self.emit(Opcode::Nip, &[]);
5394        Ok(())
5395    }
5396
5397    /// `await expr`: exactly one instruction.
5398    ///
5399    /// No resume-magic branch follows it. The reference's `await` leaves a single value
5400    /// on the stack and completion is signalled by the `return_async` at the end of the
5401    /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
5402    /// reference never emits, and a `for await` loop — which reaches `await` through the
5403    /// same opcode — would then spill a value the loop's unpacking does not expect.
5404    fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
5405        self.expr(argument)?;
5406        self.emit(Opcode::Await, &[]);
5407        self.state().has_await = true;
5408        Ok(())
5409    }
5410
5411    /// The `super` base: the receiver followed by the home object's prototype.
5412    ///
5413    /// Everything `super` does needs both. A *read* starts at the prototype but reports
5414    /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
5415    /// prototype but calls it with the receiver.
5416    fn super_base(&mut self) {
5417        self.this_expression();
5418        self.home_object();
5419        self.emit(Opcode::GetSuper, &[]);
5420    }
5421
5422    /// `[[HomeObject]]` as `super` sees it.
5423    ///
5424    /// A method, a constructor and a field initialiser each carry one — `set_home_object`
5425    /// put it there — so for them the special object *is* the answer. An arrow and a
5426    /// static block have none: they read the enclosing function's, which has to be
5427    /// materialised into a local, exactly as `this` is for an arrow.
5428    ///
5429    /// The name matches what the reference stores, so the disassembly agrees; it is not a
5430    /// name any program can write.
5431    fn home_object(&mut self) {
5432        if !self.cur().is_arrow {
5433            self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
5434            return;
5435        }
5436        if let Some(target) = self.enclosing_function() {
5437            self.state_at(target).needs_home_object_local = true;
5438            self.declare_at(target, HOME_OBJECT);
5439        }
5440        self.emit_var(VarAction::Get, HOME_OBJECT);
5441    }
5442
5443    /// `super(args)`: construct the parent class and adopt the result as `this`.
5444    ///
5445    /// The parent is the prototype of the constructor that is running, which is exactly
5446    /// what `extends` set up. `new.target` is passed through unchanged so that
5447    /// `new.target` inside the parent is the class actually being constructed.
5448    fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5449        self.active_func_expression();
5450        self.emit(Opcode::GetSuper, &[]);
5451        self.new_target_expression();
5452        if Self::has_spread(arguments) {
5453            self.argument_array(arguments)?;
5454            self.emit(Opcode::Apply, &[Op::Int(1)]);
5455        } else {
5456            for argument in arguments {
5457                self.expr(argument)?;
5458            }
5459            self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
5460        }
5461        // The value stays on the stack: `super()` is an expression, and a derived
5462        // constructor's `this` may only be initialised once.
5463        self.emit(Opcode::Dup, &[]);
5464        self.emit_var(VarAction::PutInitChecked, "this");
5465        // Instance fields are installed here, not at the top of the body: a derived
5466        // constructor has no `this` to install them on until `super()` returns. The
5467        // reference emits the same call at every `super()` site.
5468        self.call_field_initialiser();
5469        Ok(())
5470    }
5471
5472    /// `this` as a local, which every class constructor and field initialiser needs.
5473    ///
5474    /// The reference materialises the receiver into a local rather than reading
5475    /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
5476    /// and a field initialiser has to see the final value.
5477    fn begin_this_local(&mut self) {
5478        self.declare_hidden_local("this", VarKind::Normal);
5479        self.emit(Opcode::PushThis, &[]);
5480        self.emit_var(VarAction::Put, "this");
5481        // The store is already at the top of the body, so `provide_this_local` has
5482        // nothing left to prepend. Without this the initialiser ended up with
5483        // `push_this; put_loc0 this` twice whenever the class also held a field
5484        // initialiser whose body read `this` through an arrow.
5485        self.state().has_this_prologue = true;
5486    }
5487
5488    /// Compile a constructor the class wrote.
5489    ///
5490    /// The flags have to be in place before the body is compiled, but
5491    /// `compile_function_with_name` creates its own state — so the caller's state is
5492    /// marked instead and the new one inherits it. That is the same trick the parameter
5493    /// prologue uses, and it keeps one code path for both.
5494    fn compile_class_constructor(
5495        &mut self,
5496        func: &ast::Function,
5497        has_heritage: bool,
5498    ) -> Result<CompiledFunction, SyntaxError> {
5499        let saved = self.cur().ctor_kind;
5500        self.state().class_ctor_pending = Some(if has_heritage {
5501            CtorKind::Derived
5502        } else {
5503            CtorKind::Base
5504        });
5505        let result = self.compile_function_with_name(func, false);
5506        self.state().ctor_kind = saved;
5507        self.state().class_ctor_pending = None;
5508        result
5509    }
5510
5511    /// The constructor a class gets when it does not declare one.
5512    ///
5513    /// A base class's is empty; a derived class's forwards every argument to the parent
5514    /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
5515    /// instance field initialiser afterwards when the class has fields, which is why the
5516    /// initialiser is captured rather than inlined.
5517    fn compile_implicit_constructor(
5518        &mut self,
5519        class: &Class,
5520        has_heritage: bool,
5521    ) -> Result<CompiledFunction, SyntaxError> {
5522        self.compile_synthetic_function(
5523            "",
5524            true,
5525            Span::new(class.body_end, class.body_end),
5526            |compiler| {
5527                if has_heritage {
5528                    // A derived constructor's `this` does not exist until `super()` returns,
5529                    // so it starts in the dead zone and `init_ctor` fills it.
5530                    compiler.declare("this", VarDef::lexical("this"));
5531                    compiler.emit(
5532                        Opcode::SetLocUninitialized,
5533                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5534                    );
5535                    compiler.emit(Opcode::InitCtor, &[]);
5536                    compiler.emit(
5537                        Opcode::PutLocCheckInit,
5538                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5539                    );
5540                } else {
5541                    compiler.begin_this_local();
5542                    compiler.emit(Opcode::CheckCtor, &[]);
5543                }
5544                compiler.call_field_initialiser();
5545                // A derived constructor returns `this`, the object `super()` built. Without
5546                // this the implicit constructor fell through to `return_undef`, and `new B()`
5547                // handed back the empty object `construct` had made instead of the one the
5548                // parent constructor initialised.
5549                if has_heritage {
5550                    compiler.emit_var(VarAction::Get, "this");
5551                    compiler.emit(Opcode::Return, &[]);
5552                }
5553                Ok(())
5554            },
5555        )
5556    }
5557
5558    /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
5559    ///
5560    /// A class with no instance fields leaves the binding `undefined`, and calling it
5561    /// would throw; the reference emits the same guard rather than branching at compile
5562    /// time because a class can be extended by a subclass whose fields still have to run.
5563    fn call_field_initialiser(&mut self) {
5564        let skip = self.new_label();
5565        self.emit_var(VarAction::Get, "<class_fields_init>");
5566        self.emit(Opcode::Dup, &[]);
5567        self.emit_jump(Opcode::IfFalse, skip, &[]);
5568        self.emit_var(VarAction::Get, "this");
5569        self.emit(Opcode::Swap, &[]);
5570        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
5571        self.place_label(skip);
5572        self.emit(Opcode::Drop, &[]);
5573    }
5574
5575    /// The function that defines one class's fields on `this`, and runs its static blocks.
5576    ///
5577    /// `define_field` rather than `put_field`: a field is an own property created
5578    /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
5579    /// `x = 1` field must not call the setter.
5580    ///
5581    /// One function serves the whole class: it is called once per instance (or once, for
5582    /// the static half) and walks the members in source order. Static blocks are compiled
5583    /// into the same function because they *are* part of the same sequence — `static a =
5584    /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
5585    /// different values, so the two kinds cannot be split apart.
5586    fn compile_field_initialiser(
5587        &mut self,
5588        items: &[StaticInitItem<'_>],
5589        span: Span,
5590        instance: bool,
5591        add_brand: bool,
5592    ) -> Result<CompiledFunction, SyntaxError> {
5593        self.compile_synthetic_function("", true, span, |compiler| {
5594            if instance {
5595                // An instance initialiser always carries a `<home_object>` local, because the
5596                // brand block below reads it — even when that block turns out to be dead. The
5597                // reference has the same artefact, and the store is visible in its dump.
5598                let current = compiler.stack.len() - 1;
5599                compiler.stack[current].needs_home_object_local = true;
5600            }
5601            compiler.begin_this_local();
5602            if instance {
5603                // `this` gets the brand the prototype created, before any field is defined —
5604                // which is what makes `#m()` usable from inside a field initialiser.
5605                //
5606                // The reference always emits `push_false; if_false L; this; home; add_brand;
5607                // L:` and patches the `push_false` to `push_true` from the class parse when
5608                // the class has private methods; either way the branch folds, but the *mark*
5609                // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
5610                // `this` local from being fused into a `set_loc`.
5611                let skip = compiler.new_label();
5612                if add_brand {
5613                    compiler.emit(Opcode::PushTrue, &[]);
5614                } else {
5615                    compiler.emit(Opcode::PushFalse, &[]);
5616                }
5617                compiler.emit_jump(Opcode::IfFalse, skip, &[]);
5618                compiler.emit_var(VarAction::Get, "this");
5619                compiler.emit_var(VarAction::Get, HOME_OBJECT);
5620                compiler.emit(Opcode::AddBrand, &[]);
5621                compiler.place_label(skip);
5622            }
5623            for item in items {
5624                match item {
5625                    StaticInitItem::Field(key, value) => {
5626                        // A private field is *defined*, not assigned: `define_private_field`
5627                        // reads `obj symbol value`, and its point is that it fails on a
5628                        // receiver that is not this class's — which `put_field` would not.
5629                        //
5630                        // The three shapes are the reference's: `define_field <atom>` for a
5631                        // static name, `define_array_el` for a key that is only known at run
5632                        // time (`obj key value`), `define_private_field` for `#x`, and a
5633                        // computed key is read from its binding rather than recomputed.
5634                        compiler.emit_var(VarAction::Get, "this");
5635                        match key {
5636                            FieldKey::Private(binding) | FieldKey::Computed(binding) => {
5637                                compiler.emit_var(VarAction::Get, binding);
5638                            }
5639                            FieldKey::Literal(_) => {}
5640                        }
5641                        match value {
5642                            Some(value) => compiler.expr(value)?,
5643                            None => compiler.emit(Opcode::Undefined, &[]),
5644                        }
5645                        match key {
5646                            FieldKey::Literal(literal) => {
5647                                let text = compiler.property_key_text(literal, span)?;
5648                                compiler
5649                                    .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
5650                            }
5651                            FieldKey::Computed(_) => {
5652                                compiler.emit(Opcode::DefineArrayEl, &[]);
5653                                // `define_array_el` leaves `obj key`; the key is consumed by
5654                                // the copy the pattern machinery wants, so both go.
5655                                compiler.emit(Opcode::Drop, &[]);
5656                            }
5657                            FieldKey::Private(_) => {
5658                                compiler.emit(Opcode::DefinePrivateField, &[]);
5659                            }
5660                        }
5661                        compiler.emit(Opcode::Drop, &[]);
5662                    }
5663                    StaticInitItem::Block { body, body_start } => {
5664                        let block = compiler.compile_static_block(body, *body_start)?;
5665                        let index = compiler.push_constant(Constant::Function(Box::new(block)));
5666                        // `this fclosure`, so `call_method` finds the receiver below the
5667                        // callee: the block runs with `this` bound to the class.
5668                        compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
5669                        compiler.emit_var(VarAction::Get, "this");
5670                        compiler.emit(Opcode::Swap, &[]);
5671                        compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
5672                        // Nothing the block evaluates is wanted; its effects are the point.
5673                        compiler.emit(Opcode::Drop, &[]);
5674                    }
5675                }
5676            }
5677            Ok(())
5678        })
5679    }
5680
5681    /// Compile a `static { … }` body into the function the class calls for it.
5682    ///
5683    /// Shaped like an arrow, because that is the one function form with no `this`,
5684    /// `new.target` or `arguments` of its own: all three reach the enclosing static
5685    /// initialiser, and through it the class. `arguments` never gets that far — the parser
5686    /// rejects the reference — but `this` and `super` both depend on it.
5687    ///
5688    /// The body is hoisted like a function body's, because the reference parses it as one:
5689    /// `var` inside a block is a local of the block's function, not of whatever encloses
5690    /// the class.
5691    fn compile_static_block(
5692        &mut self,
5693        body: &[Stmt],
5694        body_start: Position,
5695    ) -> Result<CompiledFunction, SyntaxError> {
5696        let mut state = FnState::new(String::new(), FunctionKind::Normal);
5697        // Class bodies are strict, so a static block is too.
5698        state.strict = true;
5699        // The one property that makes this an arrow: nothing of its own to bind `this` to,
5700        // so `this` and `super` come from the initialiser that calls it.
5701        state.is_arrow = true;
5702        state.created_in_block = self.cur().current_block;
5703        state.with_names = self.cur().with_names.clone();
5704        state.line = body_start.line;
5705        state.column = body_start.column;
5706        let depth = self.stack.len();
5707        self.stack.push(state);
5708        let body_key = body_start.offset as u64;
5709        self.push_block(body_key, NO_PARENT);
5710        self.state().body_block = body_key;
5711        let result = (|| {
5712            self.hoist(body, body_key)?;
5713            self.emit_scope_enter(body_key);
5714            for statement in body {
5715                self.stmt(statement)?;
5716            }
5717            if self.end_is_reachable() {
5718                self.emit(Opcode::ReturnUndef, &[]);
5719            }
5720            Ok(())
5721        })();
5722        if result.is_err() {
5723            self.stack.truncate(depth);
5724            return result.map(|()| unreachable!());
5725        }
5726        Ok(self.finish_current())
5727    }
5728
5729    /// Compile a class, leaving the constructor on the stack when `keep`.
5730    ///
5731    /// The shape follows the reference: the class body is its own scope holding the
5732    /// class's *inner* name as a `const` — which is what lets a method refer to the
5733    /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
5734    /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
5735    /// on the top of the stack: the prototype for instance members, the constructor
5736    /// itself for `static` ones, which is why a static member costs an extra `swap`.
5737    fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
5738        let parent_block = self.cur().current_block;
5739        let key = class.span.start.offset as u64;
5740        self.push_block(key, parent_block);
5741        let name = class.name.as_ref().map(|ident| ident.name.clone());
5742        // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
5743        // resolves `E` without a global lookup. An *unnamed* class expression has no such
5744        // binding, and `define_class` is handed the empty name.
5745        if let Some(name) = &name {
5746            self.declare(name, VarDef::constant(name.clone()));
5747        }
5748        self.emit_scope_enter(key);
5749
5750        // The heritage clause is evaluated outside the class's own scope: it cannot see
5751        // the class binding it is about to initialise.
5752        let saved_block = self.cur().current_block;
5753        self.state().current_block = parent_block;
5754        match &class.super_class {
5755            Some(parent) => self.expr(parent)?,
5756            None => self.emit(Opcode::Undefined, &[]),
5757        }
5758        self.state().current_block = saved_block;
5759        let has_heritage = class.super_class.is_some();
5760
5761        // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
5762        // lands after the heritage's code — which is where the reference puts it, because it
5763        // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
5764        // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
5765        // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
5766        // came out in the opposite order from the reference's.
5767        //
5768        // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
5769        // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
5770        // a const accepts — so the old comment's worry ("a const would refuse the second
5771        // store") did not apply: there is no second store.
5772        // Every `#name` the class declares gets a `const` binding in the class scope, and so
5773        // does every computed field key. That is how the reference does it
5774        // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
5775        // what makes a private name resolve like any other class-scope variable — including
5776        // through a nested function's closure — while remaining invisible outside.
5777        //
5778        // All of them are declared *before* `<class_fields_init>`, in member order, because
5779        // that is when the reference's parser creates them.
5780        let plan = ClassPlan::build(class);
5781        // The body's private names are visible from here to the end of the class, and shadow
5782        // any outer class's of the same spelling. Pushed *before* the constructor is compiled
5783        // — it is compiled first because `define_class` consumes it, but its body can name
5784        // `#x` like any other member's.
5785        self.private_scopes.push(plan.uses.clone());
5786        let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
5787        for binding in &plan.bindings {
5788            class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
5789        }
5790        let fci = self.declare(
5791            "<class_fields_init>",
5792            VarDef::constant("<class_fields_init>"),
5793        );
5794        // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
5795        // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
5796        // members' bindings follow in reverse.
5797        self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
5798        for slot in class_slots.iter().rev() {
5799            self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
5800        }
5801
5802        // The constructor is compiled before `define_class` because that instruction
5803        // consumes it; a class without one gets the implicit version.
5804        let constructor = class.elements.iter().find_map(|element| match element {
5805            ClassElement::Method {
5806                kind: MethodKind::Constructor,
5807                func,
5808                ..
5809            } => Some(&**func),
5810            _ => None,
5811        });
5812        // A constructor is compiled differently from a method: it owns `this`. The flags
5813        // go on the *enclosing* state because a constructor is a nested function and
5814        // `compile_function_with_name` starts a fresh one.
5815        let ctor = match constructor {
5816            Some(func) => self.compile_class_constructor(func, has_heritage)?,
5817            None => self.compile_implicit_constructor(class, has_heritage)?,
5818        };
5819        // A closure, not the bare constant: the constructor captures
5820        // `<class_fields_init>`, which is only filled after `define_class` has run, so it
5821        // has to hold the cell rather than a copy of its value.
5822        //
5823        // The pool slot is left unassigned for now, because the reference gives the
5824        // constructor the *last* index of the members' range: `js_parse_class` emits a
5825        // `push_const` whose operand is patched at the end of the class parse, after every
5826        // method has taken a slot. Emitting the members first and the constant second is how
5827        // the numbering comes out the same; the instruction itself stays where it is.
5828        let ctor_insn = self.cur().insns.len();
5829        self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
5830        let flags = if has_heritage { 1 } else { 0 };
5831        self.emit(
5832            Opcode::DefineClass,
5833            &[
5834                Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
5835                Op::Int(flags),
5836            ],
5837        );
5838
5839        // Instance fields and static fields are two different functions: the first runs
5840        // per instance from the constructor, the second runs once, here.
5841        let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
5842        let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
5843        for (index, element) in class.elements.iter().enumerate() {
5844            match element {
5845                ClassElement::Method {
5846                    key: member_key,
5847                    is_static,
5848                    kind,
5849                    func,
5850                    span,
5851                } => {
5852                    if *kind == MethodKind::Constructor {
5853                        continue;
5854                    }
5855                    // `static(x)` is a *method* named `static`, not a static method; the
5856                    // parser already decided which by putting it in `kind`.
5857                    if *is_static {
5858                        self.emit(Opcode::Swap, &[]);
5859                    }
5860                    // A computed key is evaluated *here*, before the method's closure
5861                    // exists, and stays under it: `define_method_computed` pops
5862                    // `function, key, object`, so the stack has to read
5863                    // `[class, prototype, key, function]`. Evaluating the key after the
5864                    // `fclosure` and swapping the two put the prototype *below* the
5865                    // closure, which defined the method on the function and lost the
5866                    // prototype: `class C { [k]() {} }` left `C` undefined. The order is
5867                    // also the spec's — a class body evaluates every element's name before
5868                    // that element's function.
5869                    if let PropName::Computed(key) = member_key {
5870                        self.expr(key)?;
5871                    }
5872                    let function = self.compile_function_with_name(func, true)?;
5873                    let index = self.push_constant(Constant::Function(Box::new(function)));
5874                    self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5875                    match member_key {
5876                        // A private method is not a property of the prototype: it is a
5877                        // closure in the class scope, which is why nothing outside can reach
5878                        // it and why a use site has to brand-check. `set_name` gives the
5879                        // function its `name` (`#m`), which an accessor does not get — the
5880                        // reference leaves that commented out.
5881                        PropName::Private(ident) => {
5882                            let name = format!("#{}", ident.name);
5883                            // `set_home_object` first: the brand check reads the function's
5884                            // home object, and for a method that is the prototype.
5885                            self.emit(Opcode::SetHomeObject, &[]);
5886                            let binding = if *kind == MethodKind::Set {
5887                                format!("{name}<set>")
5888                            } else {
5889                                name.clone()
5890                            };
5891                            if *kind == MethodKind::Method {
5892                                self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
5893                            }
5894                            self.emit_var(VarAction::PutInit, &binding);
5895                        }
5896                        PropName::Computed(_) => {
5897                            self.emit(
5898                                Opcode::DefineMethodComputed,
5899                                &[Op::Int(class_method_flags(*kind))],
5900                            );
5901                        }
5902                        PropName::Literal(literal) => {
5903                            let text = self.property_key_text(literal, *span)?;
5904                            self.emit(
5905                                Opcode::DefineMethod,
5906                                &[
5907                                    Op::Atom(Atom::from_wtf8(&text)),
5908                                    Op::Int(class_method_flags(*kind)),
5909                                ],
5910                            );
5911                        }
5912                    }
5913                    if *is_static {
5914                        self.emit(Opcode::Swap, &[]);
5915                    }
5916                }
5917                ClassElement::Field {
5918                    key: field_key,
5919                    is_static,
5920                    value,
5921                    ..
5922                } => {
5923                    // A private field's *symbol* is created here, at the member, and stored
5924                    // in its binding: the field's property is keyed by it, so it has to exist
5925                    // before any initialiser runs, and a fresh one per class body is what
5926                    // makes two classes that both write `#x` independent.
5927                    //
5928                    // A computed key is evaluated once, here, and `to_propkey`'d once — a key
5929                    // whose `toString` has a side effect must not run again per instance.
5930                    let key = match field_key {
5931                        PropName::Private(ident) => {
5932                            let binding = format!("#{}", ident.name);
5933                            if *is_static {
5934                                self.emit(Opcode::Swap, &[]);
5935                            }
5936                            self.emit(
5937                                Opcode::PrivateSymbol,
5938                                &[Op::Atom(Atom::from_text(&binding))],
5939                            );
5940                            self.emit_var(VarAction::PutInit, &binding);
5941                            if *is_static {
5942                                self.emit(Opcode::Swap, &[]);
5943                            }
5944                            FieldKey::Private(binding)
5945                        }
5946                        PropName::Computed(expression) => {
5947                            let binding = plan
5948                                .computed
5949                                .get(&index)
5950                                .cloned()
5951                                .expect("every computed key got a binding");
5952                            if *is_static {
5953                                self.emit(Opcode::Swap, &[]);
5954                            }
5955                            self.expr(expression)?;
5956                            self.emit(Opcode::ToPropkey, &[]);
5957                            self.emit_var(VarAction::PutInit, &binding);
5958                            if *is_static {
5959                                self.emit(Opcode::Swap, &[]);
5960                            }
5961                            FieldKey::Computed(binding)
5962                        }
5963                        PropName::Literal(literal) => FieldKey::Literal(literal),
5964                    };
5965                    if *is_static {
5966                        static_items.push(StaticInitItem::Field(key, value.as_deref()));
5967                    } else {
5968                        instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
5969                    }
5970                }
5971                ClassElement::StaticBlock {
5972                    body, body_start, ..
5973                } => static_items.push(StaticInitItem::Block {
5974                    body,
5975                    body_start: *body_start,
5976                }),
5977            }
5978        }
5979
5980        // Now that every member has its slot, the constructor can have the next one and the
5981        // `fclosure` above can name it.
5982        let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
5983        match self.state().insns.get_mut(ctor_insn) {
5984            Some(Insn::Fixed { operands, .. }) => {
5985                operands[0] = Op::Const(ctor_index);
5986            }
5987            // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
5988            // loudly beats emitting a `fclosure` of slot 4294967295.
5989            _ => {
5990                return Err(SyntaxError::new(
5991                    "the class constructor's fclosure went missing",
5992                    class.span,
5993                ));
5994            }
5995        }
5996
5997        // The instance brand: a symbol created once on the prototype, which every instance
5998        // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
5999        // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
6000        // copy is created. The prototype is on top of the stack at this point.
6001        if plan.instance_brand {
6002            self.emit(Opcode::Dup, &[]);
6003            self.emit(Opcode::Null, &[]);
6004            self.emit(Opcode::Swap, &[]);
6005            self.emit(Opcode::AddBrand, &[]);
6006        }
6007
6008        // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
6009        // class has no instance fields. The constructor calls it only when it is defined.
6010        //
6011        // A class with private *methods* but no fields still needs one, because adding the
6012        // brand to each new instance is the initialiser's job.
6013        if instance_fields.is_empty() && !plan.instance_brand {
6014            self.emit(Opcode::Undefined, &[]);
6015        } else {
6016            let initialiser = self.compile_field_initialiser(
6017                &instance_fields,
6018                class.span,
6019                true,
6020                plan.instance_brand,
6021            )?;
6022            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6023            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6024            // `set_home_object` reads `obj func`, so the prototype stays where it is.
6025            self.emit(Opcode::SetHomeObject, &[]);
6026        }
6027        self.emit_var(VarAction::PutInit, "<class_fields_init>");
6028        // The prototype has done its job: every instance member is defined on it. What
6029        // is left under it is the constructor.
6030        self.emit(Opcode::Drop, &[]);
6031
6032        // The static brand, for `static #m() {}`: same opcode, but the home object is the
6033        // constructor itself, so the symbol lands on the class and the class carries it.
6034        if plan.static_brand {
6035            self.emit(Opcode::Dup, &[]);
6036            self.emit(Opcode::Dup, &[]);
6037            self.emit(Opcode::AddBrand, &[]);
6038        }
6039
6040        // The class binding is initialised *before* static fields run, so a static field
6041        // can refer to the class by name (`static y = S.x`).
6042        // `set_loc` leaves the constructor on the stack, which is what the static field
6043        // call and the outer store both consume.
6044        //
6045        // Only when there *is* such a binding: an anonymous class expression declares no
6046        // class-scope name, and asking for one by the empty string resolved to nothing —
6047        // which made `var x = class {}` assign `undefined` and put a bogus global store in
6048        // the instruction stream.
6049        if let Some(name) = &name {
6050            self.emit_var(VarAction::SetInit, name);
6051        }
6052        if !static_items.is_empty() {
6053            // The static half has no brand prologue of its own: the constructor got its
6054            // brand above, before this runs.
6055            let initialiser =
6056                self.compile_field_initialiser(&static_items, class.span, false, false)?;
6057            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6058            self.emit(Opcode::Dup, &[]);
6059            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6060            self.emit(Opcode::SetHomeObject, &[]);
6061            self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6062            self.emit(Opcode::Drop, &[]);
6063        }
6064        // The body is over, and with it this class's private names.
6065        let _ = self.private_scopes.pop();
6066        self.emit_scope_leave(key);
6067        self.state().current_block = parent_block;
6068        if keep {
6069            // A class *expression* is its own value; the class-scope binding was only
6070            // ever an alias for it.
6071            return Ok(());
6072        }
6073        // A declaration stores into the binding the enclosing statement declared.
6074        self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
6075        Ok(())
6076    }
6077
6078    fn push_this(&mut self) {
6079        self.emit(Opcode::PushThis, &[]);
6080    }
6081
6082    /// `this`, which an arrow does not have of its own.
6083    ///
6084    /// The reference gives the enclosing function a local named `this`, initialised from
6085    /// `push_this` at the top of its body, and the arrow then reads it as a captured
6086    /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
6087    /// the arrow is called with none.
6088    fn this_expression(&mut self) {
6089        // In a class constructor `this` is a local: a derived constructor only gets one
6090        // when `super()` returns, and reading the raw receiver would give the *outer*
6091        // one instead.
6092        if self.cur().ctor_kind != CtorKind::None {
6093            self.emit_var(VarAction::Get, "this");
6094            return;
6095        }
6096        if !self.cur().is_arrow {
6097            self.push_this();
6098            return;
6099        }
6100        if let Some(target) = self.enclosing_function() {
6101            self.state_at(target).needs_this_local = true;
6102            self.declare_at(target, "this");
6103        }
6104        self.emit_var(VarAction::Get, "this");
6105    }
6106
6107    /// `new.target`, which an arrow likewise does not own.
6108    fn new_target_expression(&mut self) {
6109        if !self.cur().is_arrow {
6110            self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
6111            return;
6112        }
6113        if let Some(target) = self.enclosing_function() {
6114            self.state_at(target).needs_new_target_local = true;
6115            self.declare_at(target, NEW_TARGET);
6116        }
6117        self.emit_var(VarAction::Get, NEW_TARGET);
6118    }
6119
6120    /// `this.active_func`: the function `super()` resolves against.
6121    ///
6122    /// In a constructor or a method that is the function being run, so the special object
6123    /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
6124    /// a closure variable — see [`FnState::needs_active_func_local`].
6125    fn active_func_expression(&mut self) {
6126        if !self.cur().is_arrow {
6127            self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
6128            return;
6129        }
6130        if let Some(target) = self.enclosing_function() {
6131            self.state_at(target).needs_active_func_local = true;
6132            self.declare_at(target, ACTIVE_FUNC);
6133        }
6134        self.emit_var(VarAction::Get, ACTIVE_FUNC);
6135    }
6136
6137    /// Give the function a local `<active_func>`, for an arrow inside it to capture.
6138    fn provide_active_func_local(&mut self) {
6139        let current = self.stack.len() - 1;
6140        if !self.stack[current].needs_active_func_local {
6141            return;
6142        }
6143        if !self.stack[current]
6144            .vars
6145            .iter()
6146            .any(|var| var.name == ACTIVE_FUNC)
6147        {
6148            self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
6149        }
6150        self.prepend_initialiser(
6151            ACTIVE_FUNC,
6152            Insn::Fixed {
6153                op: Opcode::SpecialObject,
6154                operands: vec![Op::Int(2)],
6155            },
6156        );
6157    }
6158
6159    /// Give the function a local `new.target`, for an arrow inside it to capture.
6160    fn provide_new_target_local(&mut self) {
6161        let current = self.stack.len() - 1;
6162        if !self.stack[current].needs_new_target_local {
6163            return;
6164        }
6165        if !self.stack[current]
6166            .vars
6167            .iter()
6168            .any(|var| var.name == NEW_TARGET)
6169        {
6170            self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
6171        }
6172        self.prepend_initialiser(
6173            NEW_TARGET,
6174            Insn::Fixed {
6175                op: Opcode::SpecialObject,
6176                operands: vec![Op::Int(3)],
6177            },
6178        );
6179    }
6180
6181    /// `arguments` reached from an arrow, which likewise belongs to the enclosing
6182    /// function.
6183    fn ensure_enclosing_arguments(&mut self) {
6184        // An arrow created in a parameter list needs the *parameter* scope's
6185        // `arguments`, not the body's: the two are separate bindings and the arrow was
6186        // born before the body existed.
6187        let from_params = self.cur().created_in_params;
6188        if let Some(target) = self.enclosing_function() {
6189            self.state_at(target).needs_arguments_local = true;
6190            if from_params {
6191                self.state_at(target).needs_param_arguments = true;
6192                // Declare it now, not at the enclosing function's `finish_current`: the
6193                // arrow resolves its own `arguments` before that runs, and a binding that
6194                // does not exist yet resolves as a global.
6195                declare_param_var_at(&mut self.stack[target], "arguments");
6196            }
6197            self.declare_at(target, "arguments");
6198        }
6199    }
6200
6201    /// The innermost enclosing frame that is a real function — an arrow inherits from it
6202    /// rather than starting a scope of its own.
6203    fn enclosing_function(&self) -> Option<usize> {
6204        (0..self.stack.len())
6205            .rev()
6206            .find(|index| !self.stack[*index].is_arrow && !self.stack[*index].is_script)
6207    }
6208
6209    fn state_at(&mut self, index: usize) -> &mut FnState {
6210        &mut self.stack[index]
6211    }
6212
6213    /// Declare a `var` binding directly in a specific frame.
6214    fn declare_at(&mut self, index: usize, name: &str) {
6215        let state = &mut self.stack[index];
6216        if state.vars.iter().any(|var| var.name == name) {
6217            return;
6218        }
6219        state.var_block.push(FUNCTION_SCOPE);
6220        state.vars.push(VarDef::var(name));
6221    }
6222
6223    /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
6224    /// the reference calls a `special_object` gets initialised on entry.
6225    fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
6226        let current = self.stack.len() - 1;
6227        let init = [
6228            producer,
6229            Insn::Var {
6230                action: VarAction::Put,
6231                name: name.to_string(),
6232                block: 0,
6233                // A prologue initialiser runs before the body proper, but it is body
6234                // code: `this` and `arguments` are provided for it, not by it.
6235                in_params: false,
6236            },
6237        ];
6238        let inserted = init.len();
6239        for (index, instruction) in init.into_iter().enumerate() {
6240            self.stack[current].insns.insert(index, instruction);
6241        }
6242        for placed in self.stack[current].labels.iter_mut().flatten() {
6243            *placed += inserted;
6244        }
6245        self.stack[current].label_since_insn = true;
6246    }
6247
6248    fn push_constant(&mut self, constant: Constant) -> u32 {
6249        let state = self.state();
6250        let index = state.cpool.len() as u32;
6251        state.cpool.push(constant);
6252        index
6253    }
6254
6255    /// Compile `a && b`, `a || b`, `a ?? b`.
6256    ///
6257    /// A run of the *same* operator shares one end label, so `a || b || c` tests
6258    /// `a` once and jumps past everything when it is truthy, instead of falling
6259    /// into `b`'s test. The parser builds such a run left-associated —
6260    /// `((a || b) || c)` — so the operands are collected off the left spine.
6261    ///
6262    /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
6263    /// `||`'s label, because the inner chain really does end before `&&` begins.
6264    fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
6265        let mut operands = Vec::new();
6266        collect_same_operator(op, left, &mut operands);
6267        operands.push(right);
6268
6269        let end = self.new_label();
6270        // Every operand but the last decides whether the chain stops here.
6271        let last = operands.pop().expect("the right operand is always present");
6272        for operand in operands {
6273            self.expr(operand)?;
6274            self.emit(Opcode::Dup, &[]);
6275            match op {
6276                LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
6277                LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
6278                // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
6279                // `0 || b` is `b`. The dedicated test keeps the value unless it is
6280                // null-ish, so the jump is taken on `false`.
6281                LogicalOp::Coalesce => {
6282                    self.emit(Opcode::IsUndefinedOrNull, &[]);
6283                    self.emit_jump(Opcode::IfFalse, end, &[]);
6284                }
6285            }
6286            self.emit(Opcode::Drop, &[]);
6287        }
6288        self.expr(last)?;
6289        self.place_label(end);
6290        Ok(())
6291    }
6292
6293    fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
6294        match op {
6295            UnaryOp::Typeof => {
6296                // `typeof x` must not throw on an undeclared name.
6297                if let ExprKind::Ident(name) = &argument.kind {
6298                    self.emit_var(VarAction::GetUndef, &name.name);
6299                } else {
6300                    self.expr(argument)?;
6301                }
6302                self.emit(Opcode::Typeof, &[]);
6303            }
6304            UnaryOp::Delete => {
6305                // `delete obj.prop` really deletes, and answers whether it could.
6306                // Deleting a *binding* is always `false`: a local, an argument and a
6307                // declared global are all non-configurable, which the reference encodes
6308                // as a constant `push_false` rather than a runtime check. Only a
6309                // property access has anything to do at run time.
6310                // `delete super.x` is not a delete at all: the spec refuses it, and the
6311                // reference encodes the refusal as a `throw_error`. The receiver and the
6312                // key are still evaluated first, which is what keeps the evaluation order
6313                // of the operand intact.
6314                // `delete z?.b.c` answers `true` when the chain short-circuits: there is
6315                // nothing to delete, and a failed delete is not the same as a skipped
6316                // one. The reference emits the guards so they land on a `drop; push_true`
6317                // tail, which is what this reproduces.
6318                if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
6319                    && let ExprKind::Member {
6320                        object, property, ..
6321                    } = &inner.unparen().kind
6322                {
6323                    let end = self.new_label();
6324                    let done = self.new_label();
6325                    self.chain_link(object, end)?;
6326                    match property {
6327                        MemberProp::Ident(name) => self.emit(
6328                            Opcode::PushAtomValue,
6329                            &[Op::Atom(Atom::from_text(&name.name))],
6330                        ),
6331                        MemberProp::Computed(index) => self.expr(index)?,
6332                        MemberProp::Private(_) => {
6333                            return Err(SyntaxError::new(
6334                                "deleting a private field is not allowed",
6335                                argument.span,
6336                            ));
6337                        }
6338                    }
6339                    self.emit(Opcode::Delete, &[]);
6340                    self.emit_jump(Opcode::Goto, done, &[]);
6341                    self.place_label(end);
6342                    self.emit(Opcode::Drop, &[]);
6343                    self.emit(Opcode::PushTrue, &[]);
6344                    self.place_label(done);
6345                    return Ok(());
6346                }
6347                if let ExprKind::Member { object, .. } = &argument.unparen().kind
6348                    && matches!(object.unparen().kind, ExprKind::SuperProp)
6349                {
6350                    self.super_base();
6351                    self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
6352                    return Ok(());
6353                }
6354                match &argument.kind {
6355                    ExprKind::Member {
6356                        object, property, ..
6357                    } => {
6358                        self.expr(object)?;
6359                        match property {
6360                            MemberProp::Ident(name) => {
6361                                self.emit(
6362                                    Opcode::PushAtomValue,
6363                                    &[Op::Atom(Atom::from_text(&name.name))],
6364                                );
6365                            }
6366                            MemberProp::Computed(index) => self.expr(index)?,
6367                            MemberProp::Private(_) => {
6368                                return Err(SyntaxError::new(
6369                                    "deleting a private field is not allowed",
6370                                    argument.span,
6371                                ));
6372                            }
6373                        }
6374                        self.emit(Opcode::Delete, &[]);
6375                    }
6376                    ExprKind::Ident(name) => {
6377                        // `delete name`: a declared global, a local and an argument all
6378                        // answer `false`, but an *implicit* global (`x = 1` with no
6379                        // declaration) is a configurable property of the global object
6380                        // and really goes away. Which of those a name is only the
6381                        // resolver knows, so the decision waits for it.
6382                        let pos = self.cur().cur_pos;
6383                        self.state().insns.push(Insn::DeleteVar {
6384                            name: name.name.clone(),
6385                        });
6386                        self.state().insn_pos.push(pos);
6387                    }
6388                    _ => self.emit(Opcode::PushFalse, &[]),
6389                }
6390            }
6391            UnaryOp::Void => {
6392                self.expr(argument)?;
6393                self.emit(Opcode::Drop, &[]);
6394                self.emit(Opcode::Undefined, &[]);
6395            }
6396            UnaryOp::Minus => {
6397                self.expr(argument)?;
6398                self.emit(Opcode::Neg, &[]);
6399            }
6400            UnaryOp::Plus => {
6401                self.expr(argument)?;
6402                self.emit(Opcode::Plus, &[]);
6403            }
6404            UnaryOp::Not => {
6405                self.expr(argument)?;
6406                self.emit(Opcode::Lnot, &[]);
6407            }
6408            UnaryOp::BitNot => {
6409                self.expr(argument)?;
6410                self.emit(Opcode::Not, &[]);
6411            }
6412        }
6413        Ok(())
6414    }
6415
6416    /// Compile an assignment.
6417    ///
6418    /// Three operator families, three shapes:
6419    ///
6420    /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
6421    ///   the value is kept, because `put_field`/`put_array_el` consume both the
6422    ///   object and the value: `insert2` is `obj a -> a obj a`, so the store sees
6423    ///   the pair it wants and leaves a copy on top.
6424    /// * **compound** `+=` … — read the place, apply the operator, store. A member
6425    ///   reads through `get_field2`/`get_array_el3`, which leave the object (and
6426    ///   index) underneath the value precisely so the store can follow.
6427    /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
6428    ///   right-hand side. The test *keeps* the current value and skips the store
6429    ///   entirely, which is the whole point: `a ||= b` must not evaluate `b` when
6430    ///   `a` is already truthy.
6431    fn assign(&mut self, op: AssignOp, target: &Pattern, value: &Expr) -> Result<(), SyntaxError> {
6432        // Reading the flag clears it: only the outermost assignment of an
6433        // expression statement may drop its value.
6434        let keep = !std::mem::take(&mut self.state().discard_value);
6435        match &target.kind {
6436            PatternKind::Ident(name) => {
6437                // A *simple* store is blamed on the identifier, not on the `=`: a
6438                // strict-mode `not_def = 1` raises when the name is written, which the
6439                // reference reports at the name's column. A compound store is blamed on
6440                // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
6441                // which the reference reports at the `+=`), so only the simple case
6442                // moves the position.
6443                let saved = self.cur().cur_pos;
6444                let name_pos = Some(name.span.start);
6445                if matches!(op, AssignOp::Assign) {
6446                    self.state().cur_pos = name_pos;
6447                }
6448                // A *compound* store reads the binding before it combines, and that read
6449                // is blamed on the identifier: `not_def += 2` fails while reading
6450                // `not_def`, so the position is the name's, not the `+=`'s. The
6451                // combination that follows is blamed on the operator, which is why
6452                // `cur_pos` is put back to the operator position before it is emitted.
6453                self.state().cur_pos = name_pos;
6454                match op {
6455                    AssignOp::Assign => {
6456                        self.expr(value)?;
6457                        self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
6458                        // A discarded store to a *slot* consumes its value, so no copy
6459                        // is needed. A global store goes through `put_var`, which the
6460                        // reference always pairs with a `dup` — matching it keeps the
6461                        // bytecode identical. Getting this wrong is not only an extra
6462                        // instruction: a stray copy gives the peephole a chance to fold
6463                        // the store into an unrelated later read.
6464                        let slot = self.is_slot(&name.name);
6465                        if keep || !slot {
6466                            self.emit(Opcode::Dup, &[]);
6467                        }
6468                        self.state().no_value = !keep && slot;
6469                        self.emit_var(VarAction::Put, &name.name);
6470                    }
6471                    AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6472                        let end = self.new_label();
6473                        self.emit_var(VarAction::Get, &name.name);
6474                        self.state().cur_pos = saved;
6475                        self.emit(Opcode::Dup, &[]);
6476                        self.emit_logical_test(op);
6477                        self.emit_jump(logical_jump(op), end, &[]);
6478                        self.emit(Opcode::Drop, &[]);
6479                        self.expr(value)?;
6480                        self.emit(Opcode::Dup, &[]);
6481                        self.emit_var(VarAction::Put, &name.name);
6482                        self.place_label(end);
6483                    }
6484                    _ => {
6485                        self.emit_var(VarAction::Get, &name.name);
6486                        self.expr(value)?;
6487                        self.state().cur_pos = saved;
6488                        self.emit(compound_opcode(op), &[]);
6489                        self.emit(Opcode::Dup, &[]);
6490                        self.emit_var(VarAction::Put, &name.name);
6491                    }
6492                }
6493                self.state().cur_pos = saved;
6494                Ok(())
6495            }
6496            PatternKind::Member(member) => {
6497                // `super.x = v` is not a store through a value: it starts at the home
6498                // object's prototype but writes to `this`, so it goes through
6499                // `put_super_value` rather than `put_field`. The receiver, prototype, key
6500                // and value are handed over together.
6501                if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
6502                    return self.assign_super(member, op, value);
6503                }
6504                // A store is blamed on the selector punctuator (`.` or `[`), the same
6505                // token a load is blamed on — the reference records `put_field obj.a`
6506                // at the `.`, so a setter that throws reports that column and not the
6507                // `=` of the assignment it sits in. The inner expressions restore their
6508                // own positions, so the selector's sticks for the store instructions.
6509                let saved = self.cur().cur_pos;
6510                self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6511                self.expr(&member.object)?;
6512                match &member.property {
6513                    MemberProp::Ident(property) => {
6514                        let atom = Atom::from_text(&property.name);
6515                        match op {
6516                            AssignOp::Assign => {
6517                                self.expr(value)?;
6518                                // `put_field` consumes the object and the value, so
6519                                // without `insert2` nothing is left over for the
6520                                // statement to drop.
6521                                self.state().no_value = !keep;
6522                                if keep {
6523                                    self.emit(Opcode::Insert2, &[]);
6524                                }
6525                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6526                            }
6527                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6528                                // `get_field2` leaves the object under the value, so
6529                                // the keep path has an object to dispose of. The store
6530                                // path must jump *over* that cleanup: falling into it
6531                                // would `nip` a stack that only holds the value.
6532                                let (keep_label, end) = (self.new_label(), self.new_label());
6533                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6534                                self.emit(Opcode::Dup, &[]);
6535                                self.emit_logical_test(op);
6536                                self.emit_jump(logical_jump(op), keep_label, &[]);
6537                                self.emit(Opcode::Drop, &[]);
6538                                self.expr(value)?;
6539                                self.emit(Opcode::Insert2, &[]);
6540                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6541                                self.emit_jump(Opcode::Goto, end, &[]);
6542                                self.place_label(keep_label);
6543                                self.emit(Opcode::Nip, &[]);
6544                                self.place_label(end);
6545                            }
6546                            _ => {
6547                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6548                                self.expr(value)?;
6549                                self.emit(compound_opcode(op), &[]);
6550                                self.state().no_value = !keep;
6551                                if keep {
6552                                    self.emit(Opcode::Insert2, &[]);
6553                                }
6554                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6555                            }
6556                        }
6557                    }
6558                    MemberProp::Computed(index) => {
6559                        self.expr(index)?;
6560                        match op {
6561                            AssignOp::Assign => {
6562                                self.expr(value)?;
6563                                self.state().no_value = !keep;
6564                                if keep {
6565                                    self.emit(Opcode::Insert3, &[]);
6566                                }
6567                                self.emit(Opcode::PutArrayEl, &[]);
6568                            }
6569                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6570                                let (keep_label, end) = (self.new_label(), self.new_label());
6571                                self.emit(Opcode::GetArrayEl3, &[]);
6572                                self.emit(Opcode::Dup, &[]);
6573                                self.emit_logical_test(op);
6574                                self.emit_jump(logical_jump(op), keep_label, &[]);
6575                                self.emit(Opcode::Drop, &[]);
6576                                self.expr(value)?;
6577                                self.emit(Opcode::Insert3, &[]);
6578                                self.emit(Opcode::PutArrayEl, &[]);
6579                                self.emit_jump(Opcode::Goto, end, &[]);
6580                                self.place_label(keep_label);
6581                                // Both the object and the index are left over.
6582                                self.emit(Opcode::Nip, &[]);
6583                                self.emit(Opcode::Nip, &[]);
6584                                self.place_label(end);
6585                            }
6586                            _ => {
6587                                self.emit(Opcode::GetArrayEl3, &[]);
6588                                self.expr(value)?;
6589                                self.emit(compound_opcode(op), &[]);
6590                                self.state().no_value = !keep;
6591                                if keep {
6592                                    self.emit(Opcode::Insert3, &[]);
6593                                }
6594                                self.emit(Opcode::PutArrayEl, &[]);
6595                            }
6596                        }
6597                    }
6598                    MemberProp::Private(name) => {
6599                        // `obj value` is on the stack, and every private store wants exactly
6600                        // that. A top-level private name cannot be assigned (the parser rejects
6601                        // `#x = 1`), so the only way here is `this.#x = …` inside the class.
6602                        //
6603                        // The reference emits `insert2` whether or not the value is wanted,
6604                        // so this does too: the copy left behind is the assignment expression's
6605                        // value, and a discarded one is simply never read.
6606                        let binding = format!("#{}", name.name);
6607                        let (kind, setter) = self.private_use(&binding, member.span)?;
6608                        match op {
6609                            AssignOp::Assign => {
6610                                self.expr(value)?;
6611                                if keep {
6612                                    self.emit(Opcode::Insert2, &[]);
6613                                }
6614                                self.private_store(&binding, kind, setter.as_deref())?;
6615                                self.state().no_value = !keep;
6616                            }
6617                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6618                                let (keep_label, end) = (self.new_label(), self.new_label());
6619                                self.emit(Opcode::Dup, &[]);
6620                                self.private_load(&binding, kind, member.span)?;
6621                                self.emit(Opcode::Dup, &[]);
6622                                self.emit_logical_test(op);
6623                                self.emit_jump(logical_jump(op), keep_label, &[]);
6624                                self.emit(Opcode::Drop, &[]);
6625                                self.expr(value)?;
6626                                self.emit(Opcode::Insert2, &[]);
6627                                self.private_store(&binding, kind, setter.as_deref())?;
6628                                self.emit_jump(Opcode::Goto, end, &[]);
6629                                self.place_label(keep_label);
6630                                self.emit(Opcode::Nip, &[]);
6631                                self.place_label(end);
6632                            }
6633                            _ => {
6634                                self.emit(Opcode::Dup, &[]);
6635                                self.private_load(&binding, kind, member.span)?;
6636                                self.expr(value)?;
6637                                self.emit(compound_opcode(op), &[]);
6638                                self.emit(Opcode::Insert2, &[]);
6639                                self.private_store(&binding, kind, setter.as_deref())?;
6640                            }
6641                        }
6642                    }
6643                }
6644                self.state().cur_pos = saved;
6645                Ok(())
6646            }
6647            // A destructuring assignment: the right-hand side is the expression's own
6648            // value, so it is evaluated once and kept under the pattern's stores.
6649            PatternKind::Array { .. } | PatternKind::Object { .. } => {
6650                self.expr(value)?;
6651                if keep {
6652                    self.emit(Opcode::Dup, &[]);
6653                }
6654                self.destructure(target, None)?;
6655                self.state().no_value = !keep;
6656                Ok(())
6657            }
6658            _ => Err(SyntaxError::new(
6659                "this assignment target is not supported by the compiler yet",
6660                target.span,
6661            )),
6662        }
6663    }
6664
6665    /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
6666    ///
6667    /// The stack has to carry four values — receiver, prototype, key, value — because
6668    /// `put_super_value` takes them together; the receiver is what makes a setter found on
6669    /// the prototype run with `this`, and the key has to survive until the store, which is
6670    /// why a compound form converts it to a property key once and `dup3`s rather than
6671    /// evaluating it twice.
6672    fn assign_super(
6673        &mut self,
6674        member: &MemberPattern,
6675        op: AssignOp,
6676        value: &Expr,
6677    ) -> Result<(), SyntaxError> {
6678        let saved = self.cur().cur_pos;
6679        self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6680        self.super_base();
6681        match &member.property {
6682            MemberProp::Ident(property) => self.emit(
6683                Opcode::PushAtomValue,
6684                &[Op::Atom(Atom::from_text(&property.name))],
6685            ),
6686            MemberProp::Computed(index) => self.expr(index)?,
6687            MemberProp::Private(_) => {
6688                return Err(SyntaxError::new(
6689                    "private fields are not supported by the compiler yet",
6690                    member.span,
6691                ));
6692            }
6693        }
6694        match op {
6695            AssignOp::Assign => {
6696                // The key is only converted once, by `put_super_value` itself, so a
6697                // computed key's `toString` runs exactly once.
6698                self.expr(value)?;
6699                self.emit(Opcode::Insert4, &[]);
6700                self.emit(Opcode::PutSuperValue, &[]);
6701            }
6702            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6703                let (keep_label, end) = (self.new_label(), self.new_label());
6704                self.emit(Opcode::ToPropkey, &[]);
6705                self.emit(Opcode::Dup3, &[]);
6706                self.emit(Opcode::GetSuperValue, &[]);
6707                self.emit(Opcode::Dup, &[]);
6708                self.emit_logical_test(op);
6709                self.emit_jump(logical_jump(op), keep_label, &[]);
6710                self.emit(Opcode::Drop, &[]);
6711                self.expr(value)?;
6712                self.emit(Opcode::Insert4, &[]);
6713                self.emit(Opcode::PutSuperValue, &[]);
6714                self.emit_jump(Opcode::Goto, end, &[]);
6715                self.place_label(keep_label);
6716                // The prototype and the key are still under the value that was read.
6717                self.emit(Opcode::Nip, &[]);
6718                self.emit(Opcode::Nip, &[]);
6719                self.emit(Opcode::Nip, &[]);
6720                self.place_label(end);
6721            }
6722            _ => {
6723                self.emit(Opcode::ToPropkey, &[]);
6724                self.emit(Opcode::Dup3, &[]);
6725                self.emit(Opcode::GetSuperValue, &[]);
6726                self.expr(value)?;
6727                self.emit(compound_opcode(op), &[]);
6728                self.emit(Opcode::Insert4, &[]);
6729                self.emit(Opcode::PutSuperValue, &[]);
6730            }
6731        }
6732        // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
6733        // is still on the stack when the store finishes, and the expression statement is
6734        // what disposes of it — the same arrangement as `put_field`, reached from the other
6735        // side: there the store consumes the value (`no_value`), here it leaves it
6736        // (`keep` already false, so nothing tells the statement otherwise).
6737        self.state().cur_pos = saved;
6738        Ok(())
6739    }
6740
6741    /// The test a logical assignment applies to the current value.
6742    ///
6743    /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
6744    /// assign, while `0 ||= b` must not.
6745    fn emit_logical_test(&mut self, op: AssignOp) {
6746        if op == AssignOp::Coalesce {
6747            self.emit(Opcode::IsUndefinedOrNull, &[]);
6748        }
6749    }
6750
6751    /// The private name `#name` this use site resolves against.
6752    ///
6753    /// The parser has already rejected a name no enclosing class declares, so a miss here
6754    /// means the compiler lost track of a class scope — which is worth a real error rather
6755    /// than an `unwrap`.
6756    fn private_use(
6757        &self,
6758        binding: &str,
6759        span: Span,
6760    ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
6761        ClassPlan::find(self, binding)
6762            .map(|use_| (use_.kind, use_.setter.clone()))
6763            .ok_or_else(|| {
6764                SyntaxError::new(
6765                    format!("the private name '{binding}' is out of scope here"),
6766                    span,
6767                )
6768            })
6769    }
6770
6771    /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
6772    ///
6773    /// The three readable kinds take three different instructions, because a private name
6774    /// holds three different things — a symbol, a method function, a getter function — and
6775    /// only the first one is a property read at all.
6776    fn private_load(
6777        &mut self,
6778        binding: &str,
6779        kind: PrivateKind,
6780        span: Span,
6781    ) -> Result<(), SyntaxError> {
6782        match kind {
6783            PrivateKind::Field => {
6784                self.emit_var(VarAction::Get, binding);
6785                self.emit(Opcode::GetPrivateField, &[]);
6786            }
6787            PrivateKind::Method => {
6788                self.emit_var(VarAction::Get, binding);
6789                self.emit(Opcode::CheckBrand, &[]);
6790                // `check_brand` reads `obj func` and leaves both; the method itself is what
6791                // `this.#m` evaluates to.
6792                self.emit(Opcode::Nip, &[]);
6793            }
6794            PrivateKind::Getter => {
6795                self.emit_var(VarAction::Get, binding);
6796                self.emit(Opcode::CheckBrand, &[]);
6797                self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6798            }
6799            // `#a` is declared but never filled when only a setter exists, so reading it is
6800            // the same refusal as assigning to a `const`. The reference reports it with the
6801            // generic read-only wording and leaves the better message as a `XXX`.
6802            PrivateKind::Setter => self.emit(
6803                Opcode::ThrowError,
6804                &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
6805            ),
6806        }
6807        let _ = span;
6808        Ok(())
6809    }
6810
6811    /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
6812    fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
6813        match kind {
6814            // A method *is* the callee, so only the check goes in between.
6815            PrivateKind::Method => {
6816                self.emit_var(VarAction::Get, binding);
6817                self.emit(Opcode::CheckBrand, &[]);
6818            }
6819            _ => self.private_load(binding, kind, Span::default())?,
6820        }
6821        Ok(())
6822    }
6823
6824    /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
6825    /// wanted back.
6826    ///
6827    /// A getter/setter pair is a *method call*, not a property store: the reference reads
6828    /// the setter out of its own binding and calls it with the receiver, which is why the
6829    /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
6830    /// keeps the assignment's value for an expression context.
6831    fn private_store(
6832        &mut self,
6833        binding: &str,
6834        kind: PrivateKind,
6835        setter: Option<&str>,
6836    ) -> Result<(), SyntaxError> {
6837        match kind {
6838            PrivateKind::Field => {
6839                self.emit_var(VarAction::Get, binding);
6840                self.emit(Opcode::PutPrivateField, &[]);
6841            }
6842            PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
6843                Some(setter) => {
6844                    self.emit_var(VarAction::Get, setter);
6845                    // `obj func value` -> `value obj func` for the check, and back again for
6846                    // the call, which wants `obj func arg`.
6847                    self.emit(Opcode::Swap, &[]);
6848                    self.emit(Opcode::Rot3r, &[]);
6849                    self.emit(Opcode::CheckBrand, &[]);
6850                    self.emit(Opcode::Rot3l, &[]);
6851                    self.emit(Opcode::CallMethod, &[Op::Int(1)]);
6852                    // The setter's return value is discarded; the assignment's own value is
6853                    // whatever the caller left underneath.
6854                    self.emit(Opcode::Drop, &[]);
6855                }
6856                None => self.emit(
6857                    Opcode::ThrowError,
6858                    &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
6859                ),
6860            },
6861        }
6862        Ok(())
6863    }
6864
6865    fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
6866        let instruction = match (op, prefix) {
6867            (UpdateOp::Increment, true) => Opcode::Inc,
6868            (UpdateOp::Increment, false) => Opcode::PostInc,
6869            (UpdateOp::Decrement, true) => Opcode::Dec,
6870            (UpdateOp::Decrement, false) => Opcode::PostDec,
6871        };
6872        if let ExprKind::Member {
6873            object,
6874            property,
6875            optional: _,
6876        } = &argument.kind
6877        {
6878            // `o.x++` needs the receiver twice, so the last link is read with the
6879            // `get_*2`/`get_*3` form that keeps it, and the update is written back
6880            // with `put_field`/`put_array_el`. The reordering in between is what puts
6881            // the old value below the receiver for a postfix update and the new one
6882            // above it for a prefix one:
6883            //
6884            //   `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
6885            //   `obj val` → `inc`      → `obj new new` → `insert2` → `new obj new`
6886            //
6887            // This mirrors the reference instruction for instruction.
6888            self.expr(object)?;
6889            match property {
6890                MemberProp::Ident(name) => {
6891                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
6892                    self.emit(instruction, &[]);
6893                    self.emit(
6894                        if prefix {
6895                            Opcode::Insert2
6896                        } else {
6897                            Opcode::Perm3
6898                        },
6899                        &[],
6900                    );
6901                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
6902                }
6903                MemberProp::Computed(index) => {
6904                    self.expr(index)?;
6905                    self.emit(Opcode::GetArrayEl3, &[]);
6906                    self.emit(instruction, &[]);
6907                    self.emit(
6908                        if prefix {
6909                            Opcode::Insert3
6910                        } else {
6911                            Opcode::Perm4
6912                        },
6913                        &[],
6914                    );
6915                    self.emit(Opcode::PutArrayEl, &[]);
6916                }
6917                MemberProp::Private(name) => {
6918                    // The receiver is duplicated and the read keeps it, exactly as `get_field2`
6919                    // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
6920                    // `perm3` -> `old obj new` -> store.
6921                    let binding = format!("#{}", name.name);
6922                    let (kind, setter) = self.private_use(&binding, argument.span)?;
6923                    self.emit(Opcode::Dup, &[]);
6924                    self.private_load(&binding, kind, argument.span)?;
6925                    self.emit(instruction, &[]);
6926                    self.emit(
6927                        if prefix {
6928                            Opcode::Insert2
6929                        } else {
6930                            Opcode::Perm3
6931                        },
6932                        &[],
6933                    );
6934                    self.private_store(&binding, kind, setter.as_deref())?;
6935                }
6936            }
6937            return Ok(());
6938        }
6939        let ExprKind::Ident(name) = &argument.kind else {
6940            return Err(SyntaxError::new(
6941                "increment of a non-variable is not supported by the compiler yet",
6942                argument.span,
6943            ));
6944        };
6945        // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
6946        // reference's `inc_loc` folds those three into one, but it does so only in some
6947        // positions (a `for` update and not a bare statement, and never for a lexical
6948        // binding), so emitting it unconditionally would move *away* from its output.
6949        // The instruction is equivalent either way; matching the reference matters more
6950        // than saving two instructions.
6951        let _ = !std::mem::take(&mut self.state().discard_value);
6952        self.emit_var(VarAction::Get, &name.name);
6953        self.emit(instruction, &[]);
6954        if prefix {
6955            self.emit(Opcode::Dup, &[]);
6956        }
6957        self.emit_var(VarAction::Put, &name.name);
6958        Ok(())
6959    }
6960
6961    /// Compile an array literal.
6962    ///
6963    /// The reference splits this into three phases, and the split is load-bearing
6964    /// rather than an optimisation detail:
6965    ///
6966    /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
6967    ///    the array in one instruction.
6968    /// 2. **Everything up to the first spread** is appended with explicit indices
6969    ///    (`define_field <index>`), because a hole has no element to pass to
6970    ///    `array_from`. A hole here is what makes `length` need fixing up: an
6971    ///    explicit index does not extend the array the way a pushed element does.
6972    /// 3. **From the first spread on** the index lives on the stack, so `append` and
6973    ///    `define_array_el` can consume it and `inc` advances it.
6974    ///
6975    /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
6976    /// forces phase 2, and `[...a]` forces phase 3.
6977    fn array_literal(
6978        &mut self,
6979        elements: &[Option<ArrayElement>],
6980        span: Span,
6981    ) -> Result<(), SyntaxError> {
6982        let _ = span;
6983        let mut index: u32 = 0;
6984        let mut cursor = 0usize;
6985
6986        // Phase 1: a leading run of plain elements, at most 32 of them.
6987        while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
6988            if index >= 32 {
6989                break;
6990            }
6991            self.expr(element)?;
6992            index += 1;
6993            cursor += 1;
6994        }
6995        self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
6996
6997        // Phase 2: explicit indices, up to the first spread.
6998        let mut need_length = false;
6999        while let Some(element) = elements.get(cursor) {
7000            if matches!(element, Some(ArrayElement::Spread(_))) {
7001                break;
7002            }
7003            need_length = true;
7004            if let Some(ArrayElement::Expr(expression)) = element {
7005                self.expr(expression)?;
7006                self.emit_define_index(index);
7007                need_length = false;
7008            }
7009            index += 1;
7010            cursor += 1;
7011        }
7012
7013        if cursor >= elements.len() {
7014            if need_length {
7015                // `define_field` cannot set `length`, which is not configurable.
7016                self.emit(Opcode::Dup, &[]);
7017                self.push_number(index as f64);
7018                self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7019            }
7020            return Ok(());
7021        }
7022
7023        // Phase 3: the index moves onto the stack for the spreading tail.
7024        //
7025        // `need_length` deliberately carries over from phase 2: a hole before the
7026        // first spread still has to be reflected in `length`, and only the final
7027        // check can do it because the array is not finished until the tail is
7028        // appended.
7029        self.push_number(index as f64);
7030        while let Some(element) = elements.get(cursor) {
7031            match element {
7032                Some(ArrayElement::Spread(expression)) => {
7033                    // `append` copies an iterable and leaves the next index behind,
7034                    // so no `inc` is needed here.
7035                    self.expr(spread_argument(expression))?;
7036                    self.emit(Opcode::Append, &[]);
7037                }
7038                None | Some(ArrayElement::Expr(_)) => {
7039                    need_length = true;
7040                    if let Some(ArrayElement::Expr(expression)) = element {
7041                        self.expr(expression)?;
7042                        self.emit(Opcode::DefineArrayEl, &[]);
7043                        need_length = false;
7044                    }
7045                    self.emit(Opcode::Inc, &[]);
7046                }
7047            }
7048            cursor += 1;
7049        }
7050        if need_length {
7051            self.emit(Opcode::Dup1, &[]);
7052            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7053        } else {
7054            self.emit(Opcode::Drop, &[]);
7055        }
7056        Ok(())
7057    }
7058
7059    /// `define_field` with an array-index atom, which is how phase 2 stores elements.
7060    fn emit_define_index(&mut self, index: u32) {
7061        self.emit(
7062            Opcode::DefineField,
7063            &[Op::Atom(Atom::from_text(&index.to_string()))],
7064        );
7065    }
7066
7067    // -- functions ---------------------------------------------------------
7068
7069    fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
7070        self.compile_function_with_name(func, false)
7071    }
7072
7073    /// Compile a function, recording whether it is a *named function expression*.
7074    ///
7075    /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
7076    /// must not leak outside. The reference does that by declaring `g` as a local of
7077    /// the function itself and initialising it with `special_object 2` (the current
7078    /// function), which is why this has to be known at compile time.
7079    fn compile_function_with_name(
7080        &mut self,
7081        func: &ast::Function,
7082        is_expression: bool,
7083    ) -> Result<CompiledFunction, SyntaxError> {
7084        let kind = match (func.is_generator, func.is_async) {
7085            (false, false) => FunctionKind::Normal,
7086            (true, false) => FunctionKind::Generator,
7087            (false, true) => FunctionKind::Async,
7088            (true, true) => FunctionKind::AsyncGenerator,
7089        };
7090        let mut state = FnState::new(
7091            func.name
7092                .as_ref()
7093                .map(|n| n.name.clone())
7094                .unwrap_or_default(),
7095            kind,
7096        );
7097        // The function's own mode, recorded by the parser. Inheriting the enclosing
7098        // function's instead let a nested `"use strict"` directive be ignored, so the
7099        // body ran with sloppy `this`, sloppy `arguments` and no const checks.
7100        state.strict = func.strict;
7101        // A function defined inside a `with` block keeps seeing that object: the guard
7102        // chain names the enclosing `<with>` locals, which resolve outward into closure
7103        // variables exactly like any other captured binding.
7104        state.with_names = self.cur().with_names.clone();
7105        state.is_arrow = func.is_arrow;
7106        state.created_in_block = self.cur().current_block;
7107        // A default anywhere in the parameter list is what gives the function two
7108        // variable environments. The reference decides this the same way: it scans the
7109        // parenthesis for a top-level `=`, so a destructured name without a default
7110        // stays a plain function-scope binding.
7111        state.in_params = false;
7112        // The reference scans the parenthesis for *any* `=`, including one nested inside
7113        // a pattern, so `function f({a = 1})` has parameter expressions even though the
7114        // parameter itself carries no initialiser.
7115        state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
7116        // `IsSimpleParameterList`: no default, no rest, no destructuring. Unlike the
7117        // flag above this looks at the *shape* of each parameter, not just for `=`.
7118        state.simple_parameter_list = func
7119            .params
7120            .iter()
7121            .all(|pattern| matches!(pattern.kind, PatternKind::Ident(_)));
7122        // A function born inside a parameter list inherits the prohibition: it must not
7123        // see the body bindings of the function it was created in.
7124        state.created_in_params = self.cur().in_params || self.cur().created_in_params;
7125        // A class constructor knows what it is only because the class told it.
7126        if let Some(kind) = self.cur().class_ctor_pending {
7127            state.ctor_kind = kind;
7128        }
7129        // A named *expression* binds its own name; a declaration's name is already
7130        // bound in the enclosing scope.
7131        state.self_name = if is_expression && !func.is_arrow {
7132            func.name.as_ref().map(|n| n.name.clone())
7133        } else {
7134            None
7135        };
7136        // Keep the written range so `Function.prototype.toString` can answer with the
7137        // original text rather than `[native code]`.
7138        //
7139        // It starts at the *parameter list*, not at the function: §20.2.3.5 removes the
7140        // accessor and generator prefixes, and for a method it must not include the name
7141        // or a leading `static`. `params_span` is exactly that boundary.
7142        // A *method* keeps the old `[native code]` answer: its reported text is defined
7143        // by the method-definition grammar (no name, no `static`, no `get`/`set`, but
7144        // the comments in between kept verbatim), and reconstructing that from a byte
7145        // span got it wrong in more cases than it got right. A plain function and an
7146        // arrow are the shapes libraries actually introspect, and those are exact.
7147        let method = is_method_syntax(self.source.as_deref(), func);
7148        state.span = if method {
7149            None
7150        } else {
7151            Some((
7152                func.span.start.offset as usize,
7153                func.span.end.offset as usize,
7154            ))
7155        };
7156        state.line = func.span.start.line;
7157        state.column = func.span.start.column;
7158        // A function body has no hidden `<ret>` local; the value comes back on
7159        // the stack. Only a script keeps one.
7160        // Parameters are positional, so even a pattern occupies one argument slot. A
7161        // simple name is that slot itself; anything else (a pattern, a default, a rest
7162        // parameter) takes an anonymous slot and is unpicked into locals at the top of
7163        // the body, which is the only way one argument can bind several names.
7164        let mut prologue: Vec<(usize, Pattern)> = Vec::new();
7165        // `.length` stops at the first parameter that can be substituted: a default
7166        // fills a missing argument in, and a rest parameter absorbs the rest.
7167        let mut defined_args = func.params.len() as u32;
7168        for (index, param) in func.params.iter().enumerate() {
7169            match simple_parameter(param) {
7170                Some(name) => state.args.push(VarDef::var(name.name.clone())),
7171                None => {
7172                    state.args.push(VarDef::var(ANONYMOUS_BINDING));
7173                    prologue.push((index, param.clone()));
7174                }
7175            }
7176        }
7177        // A default anywhere before the end also ends the count, which the loop above
7178        // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
7179        for (position, param) in func.params.iter().enumerate() {
7180            if matches!(
7181                param.kind,
7182                PatternKind::Assign { .. } | PatternKind::Rest(_)
7183            ) {
7184                defined_args = position as u32;
7185                break;
7186            }
7187        }
7188        state.defined_args = defined_args;
7189        state.param_prologue = prologue;
7190        let depth = self.stack.len();
7191        self.stack.push(state);
7192        let result = self.compile_function_body(func);
7193        if result.is_err() {
7194            // A failed compile must not leave its `FnState` behind. Every caller
7195            // reads `self.state()` as "the function being compiled", so a leftover
7196            // frame silently retargets all later bookkeeping at a dead function.
7197            self.stack.truncate(depth);
7198        }
7199        result
7200    }
7201
7202    /// The body of a function, with its frame already pushed.
7203    fn compile_function_body(
7204        &mut self,
7205        func: &ast::Function,
7206    ) -> Result<CompiledFunction, SyntaxError> {
7207        let body_key = func.params_span.end.offset as u64;
7208        // Where the body begins, in source order. The runtime needs this to tell a
7209        // closure created by a default expression from one the body creates — the two see
7210        // different variable environments — and a bytecode offset would not survive the
7211        // instruction shuffling that building the frame does. Positions are in source
7212        // order, so a comparison answers it.
7213        self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
7214        self.push_block(body_key, NO_PARENT);
7215        self.state().body_block = body_key;
7216        // An arrow with an expression body has no statements; the expression is
7217        // its `return`. Building the statement here keeps one code path below, and
7218        // matters for correctness beyond convenience: returning early with the new
7219        // `FnState` still on the stack would leave the compiler looking at the
7220        // wrong function, which surfaces as an unrelated underflow later.
7221        let concise = match &func.body {
7222            js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
7223                StmtKind::Return(Some(Box::new((**value).clone()))),
7224                value.span,
7225            )),
7226            js_parse::ast::FunctionBody::Block(_) => None,
7227        };
7228        let body: &[Stmt] = match &concise {
7229            Some(stmt) => std::slice::from_ref(stmt),
7230            None => func
7231                .body
7232                .statements()
7233                .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
7234        };
7235        let prologue = std::mem::take(&mut self.state().param_prologue);
7236        let has_param_scope = self.cur().has_parameter_expressions;
7237        // The parameter scope's own bindings, declared in source order.
7238        //
7239        // With parameter expressions the list gets a variable environment of its own, and
7240        // every name it binds is a `let` there. That is what puts the *list* in the
7241        // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
7242        // and `function f(x = y, y){}` does the same, where a single shared environment
7243        // would answer `undefined` to both.
7244        if has_param_scope {
7245            let mut declared: Vec<String> = Vec::new();
7246            for param in &func.params {
7247                let mut names = Vec::new();
7248                param.bound_names(&mut names);
7249                for name in names {
7250                    if declared.contains(&name.name) {
7251                        continue;
7252                    }
7253                    declared.push(name.name.clone());
7254                    self.declare_param_binding(&name.name);
7255                }
7256            }
7257        }
7258        // A pattern parameter binds its names as function-scope locals, so they have to
7259        // exist — and be unpicked from the argument — before the body runs. With a
7260        // parameter scope these are the *second* environment: the pattern fills the
7261        // parameter's copy, and the body's binding is filled from it afterwards.
7262        for (_, pattern) in &prologue {
7263            let mut names = Vec::new();
7264            pattern.bound_names(&mut names);
7265            for name in names {
7266                self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
7267            }
7268        }
7269        self.hoist(body, body_key)?;
7270        // A constructor's prologue is not a parameter unpacking but the `this` binding:
7271        // a base constructor takes the receiver, a derived one starts in the dead zone
7272        // because only `super()` may produce it.
7273        match self.cur().ctor_kind {
7274            CtorKind::None => {}
7275            CtorKind::Base => {
7276                self.begin_this_local();
7277                self.emit(Opcode::CheckCtor, &[]);
7278                // Instance fields are installed at the top of a base constructor's body,
7279                // before any statement — `class C { x = 1; constructor() { this.x } }` sees
7280                // `1`. This used to be emitted at the *tail*, which made every field read
7281                // `undefined` inside the constructor that declared it.
7282                self.call_field_initialiser();
7283            }
7284            CtorKind::Derived => {
7285                self.declare("this", VarDef::lexical("this"));
7286                let slot = self.cur().vars.len() as u32 - 1;
7287                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7288                self.emit(Opcode::CheckCtor, &[]);
7289            }
7290        }
7291        // Entering the parameter list: everything it binds starts in the dead zone.
7292        // The order is the reference's — it walks the scope chain, which is prepended, so
7293        // the bindings come out newest first.
7294        for name in self.param_binding_names().into_iter().rev() {
7295            if let Some(slot) = self.param_binding_slot(&name) {
7296                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7297            }
7298        }
7299        // The whole parameter list is one scope, and nothing in the body exists yet, so
7300        // every name it mentions resolves against the parameter bindings and outward.
7301        self.state().in_params = has_param_scope;
7302        for (index, param) in func.params.iter().enumerate() {
7303            if let Some(pattern) = prologue_pattern(&prologue, index) {
7304                // A destructuring parameter *initialises* its bindings: with a parameter
7305                // scope they are the list's own `let`s, which is why the stores skip the
7306                // dead-zone check, and why the reference reads their properties with
7307                // `get_field2` — a `let` needs no reference.
7308                let kind = if has_param_scope {
7309                    VarDeclKind::Let
7310                } else {
7311                    VarDeclKind::Var
7312                };
7313                match &pattern.kind {
7314                    // `...rest` collects what is left rather than reading one slot.
7315                    PatternKind::Rest(inner) => {
7316                        self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7317                        self.destructure(inner, Some(kind))?;
7318                    }
7319                    _ => {
7320                        self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7321                        self.destructure(pattern, Some(kind))?;
7322                    }
7323                }
7324                continue;
7325            }
7326            // A plain name binds straight from its argument slot. With a parameter scope
7327            // the slot is also copied into the parameter binding, which is what a later
7328            // default (or a closure made among the defaults) reads.
7329            let Some(name) = simple_parameter(param) else {
7330                continue;
7331            };
7332            let target = self.param_binding_slot(&name.name);
7333            if matches!(param.kind, PatternKind::Rest(_)) {
7334                self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7335                if let Some(slot) = target {
7336                    self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
7337                }
7338                // `put_arg` rather than `set_arg`: the array is the last thing on the
7339                // stack and nothing keeps it. Named by hand because a name in the
7340                // parameter list resolves to the parameter binding, and this store has to
7341                // reach the *argument* — that is what the body reads.
7342                self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
7343                continue;
7344            }
7345            if let PatternKind::Assign { default, .. } = &param.kind {
7346                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7347                let has_value = self.new_label();
7348                self.emit(Opcode::Dup, &[]);
7349                self.emit(Opcode::IsUndefined, &[]);
7350                self.emit_jump(Opcode::IfFalse, has_value, &[]);
7351                self.emit(Opcode::Drop, &[]);
7352                self.expr(default)?;
7353                self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
7354                // The argument slot keeps the substituted value, because the *body* reads
7355                // the slot rather than the parameter binding — so this store is named
7356                // explicitly, like the rest parameter's.
7357                self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7358                self.place_label(has_value);
7359                if let Some(slot) = target {
7360                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7361                }
7362                continue;
7363            }
7364            if let Some(slot) = target {
7365                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7366                self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7367            }
7368        }
7369        // Copy the parameter scope into the body. A plain parameter needs nothing: the
7370        // body reads its argument slot, and the list kept the two in step. A name a
7371        // pattern bound has no argument slot of its own, so the body gets a `var` filled
7372        // from the parameter's copy — and *that* is why an assignment inside a default
7373        // does not reach the body.
7374        if has_param_scope {
7375            for (_, pattern) in &prologue {
7376                let mut names = Vec::new();
7377                pattern.bound_names(&mut names);
7378                for name in names {
7379                    let Some(slot) = self.param_binding_slot(&name.name) else {
7380                        continue;
7381                    };
7382                    let Some(body) = self.body_var_slot(&name.name) else {
7383                        continue;
7384                    };
7385                    self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
7386                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
7387                }
7388            }
7389        }
7390        // The parameter list is over; from here on a direct `eval` belongs to the body.
7391        self.state().in_params = false;
7392        // Entering the body's own scope comes *after* the parameter list: the body's
7393        // `let`s are not in existence while the defaults run, and the reference emits
7394        // their `set_loc_uninitialized` only once the parameters are bound.
7395        self.emit_scope_enter(body_key);
7396        // A generator starts suspended: `initial_yield` parks the body so that creating one
7397        // runs no body code until the first `next()`.
7398        //
7399        // It comes *after* the parameter unpacking, not before, because a parameter
7400        // initialiser is not body code — `function* g(a = sideEffect())` must run
7401        // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
7402        // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
7403        // until the first `next()` and 29 test262 cases that check for a synchronous throw
7404        // saw none at all.
7405        //
7406        // An async function does **not** get one. Its body runs synchronously up to the
7407        // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
7408        // before its caller's next statement — so an `initial_yield` here would park the
7409        // body before it started, which is not fixable at run time: the suspension looks
7410        // exactly like a real `await`.
7411        if self.cur().kind.is_generator() {
7412            self.emit(Opcode::InitialYield, &[]);
7413        }
7414        // Through `stmts`: the body is a block, and a `using` declaration in it is a
7415        // disposal region.
7416        self.stmts(body)?;
7417        // The implicit return only exists if control can actually get here: an
7418        // infinite loop never falls off the end.
7419        if self.end_is_reachable() {
7420            if self.cur().is_suspending() {
7421                // Falling off the end finishes the generator with `undefined`, and the
7422                // value is what tells the resume machinery "completed" rather than
7423                // "suspended".
7424                self.emit(Opcode::Undefined, &[]);
7425                self.emit(Opcode::ReturnAsync, &[]);
7426            } else {
7427                self.emit_class_constructor_tail();
7428            }
7429        }
7430        // Resolution runs while this function is still on the stack: capturing a
7431        // variable from an enclosing function means reaching into that
7432        // function's state, which requires the whole chain to be present.
7433        Ok(self.finish_current())
7434    }
7435
7436    /// Put every binding of a function that contains a direct `eval` into a cell.
7437    ///
7438    /// A direct eval can name any binding in scope, and any closure it creates has to
7439    /// keep sharing that binding after the function returns — `for (let i …)
7440    /// eval("push(() => i)")` collects one closure per iteration and each must read its
7441    /// own `i`. A copy in a side table would freeze the value, so the binding has to be
7442    /// a cell. Doing this unconditionally for such functions is the cheap, honest
7443    /// answer: the alternative is knowing at compile time which names a string will
7444    /// mention.
7445    fn capture_everything_for_eval(&mut self) {
7446        let current = self.stack.len() - 1;
7447        if !self.stack[current].has_direct_eval {
7448            return;
7449        }
7450        for arg in &mut self.stack[current].args {
7451            arg.is_captured = true;
7452        }
7453        for var in &mut self.stack[current].vars {
7454            var.is_captured = true;
7455        }
7456    }
7457
7458    /// Whether the current position in the instruction stream can be reached.
7459    ///
7460    /// A walk over the control-flow graph, using labels as instruction indices.
7461    /// The reference does the same thing to decide whether an implicit
7462    /// `return_undef` is needed.
7463    fn end_is_reachable(&self) -> bool {
7464        let state = self.cur();
7465        reachable_instructions(state, state.insns.len())[state.insns.len()]
7466    }
7467
7468    /// Resolve and assemble the function on top of the compiler stack, then pop
7469    /// it.
7470    fn finish_current(&mut self) -> CompiledFunction {
7471        self.provide_param_arguments();
7472        self.provide_arguments();
7473        self.provide_this_local();
7474        self.provide_new_target_local();
7475        self.provide_home_object_local();
7476        self.provide_active_func_local();
7477        self.provide_self_name();
7478        self.materialize_eval_sites();
7479        self.capture_everything_for_eval();
7480        let (mut resolved, resolved_pos) = resolve(&mut self.stack);
7481        // Captured bindings need a reference cell; the count goes in the header so
7482        // the runtime knows how many cells to allocate on entry.
7483        let current = self.stack.len() - 1;
7484        let captured = self.stack[current]
7485            .args
7486            .iter()
7487            .filter(|a| a.is_captured)
7488            .count()
7489            + self.stack[current]
7490                .vars
7491                .iter()
7492                .filter(|v| v.is_captured)
7493                .count();
7494        self.stack[current].var_ref_count = captured as u32;
7495        // The scope chain is only final now that every binding is known.
7496        rebuild_scope_chain(&mut self.stack[current]);
7497        let (code, stack_size, positions) =
7498            assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
7499        let _ = &mut resolved;
7500        let mut state = self.stack.pop().expect("a function is being compiled");
7501        CompiledFunction {
7502            name: state.name,
7503            kind: state.kind,
7504            strict: state.strict,
7505            is_arrow: state.is_arrow,
7506            has_parameter_expressions: state.has_parameter_expressions,
7507            simple_parameter_list: state.simple_parameter_list,
7508            body_start: state.body_start,
7509            args: state.args,
7510            defined_args: state.defined_args,
7511            vars: state.vars,
7512            closure_vars: state.closure_vars,
7513            cpool: state.cpool,
7514            atoms: state.atoms,
7515            code,
7516            stack_size,
7517            var_ref_count: state.var_ref_count,
7518            positions,
7519            source: self.function_source(state.span, state.line, state.column),
7520            line: state.line,
7521            column: state.column,
7522            filename: None,
7523            eval_sites: state.eval_sites,
7524            module: state.module.take().map(Box::new),
7525        }
7526    }
7527}
7528
7529/// Assign each binding a scope level and rebuild the scope chains.
7530///
7531/// Levels are numbered in the order the blocks appear, with 0 reserved for the
7532/// function scope where `var` and hoisted functions live. Every binding outside
7533/// level 0 gets a `scope_next` link to the next binding visible from the same
7534/// point, so walking a block's chain enumerates exactly the bindings live there.
7535///
7536/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
7537/// point at `b`, which is declared later in the source but earlier in the chain.
7538fn rebuild_scope_chain(state: &mut FnState) {
7539    // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
7540    // real block that happens to start at offset zero keeps its own level instead of
7541    // being merged into the function scope.
7542    let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
7543    for block in &state.blocks {
7544        if !levels.contains(&block.key) {
7545            levels.push(block.key);
7546        }
7547    }
7548    let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
7549    let parent_level = |level: usize| -> usize {
7550        if level == 0 {
7551            return 0;
7552        }
7553        let key = levels[level];
7554        let parent = state
7555            .blocks
7556            .iter()
7557            .find(|b| b.key == key)
7558            .map(|b| b.parent)
7559            .unwrap_or(FUNCTION_SCOPE);
7560        level_of(parent)
7561    };
7562
7563    // Own bindings per level, in declaration order.
7564    let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
7565    let keys: Vec<u64> = (0..state.vars.len())
7566        .map(|index| {
7567            state
7568                .var_block
7569                .get(index)
7570                .copied()
7571                .unwrap_or(FUNCTION_SCOPE)
7572        })
7573        .collect();
7574    for (index, key) in keys.into_iter().enumerate() {
7575        // The parameter scope is not a block: it is a level of its own with no parent,
7576        // assigned below. Letting it land in level 0 would chain the body's bindings onto
7577        // it, which the reference does not do — the two environments are siblings.
7578        if key == PARAM_SCOPE {
7579            continue;
7580        }
7581        let level = level_of(key);
7582        state.vars[index].scope_level = level as u32;
7583        // A `catch` parameter is part of the runtime scope chain even though it is
7584        // not lexical: the handler's own bindings chain on to it, which is why the
7585        // reference prints `let y [next:1]` with `e` at 1.
7586        if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
7587        {
7588            own[level].push(index);
7589        }
7590    }
7591
7592    // A scope's chain is its own bindings in reverse declaration order followed
7593    // by the enclosing scope's chain.
7594    let mut head = vec![-1i32; levels.len()];
7595    for level in 0..levels.len() {
7596        let inherited = if level == 0 {
7597            -1
7598        } else {
7599            head[parent_level(level)]
7600        };
7601        let chain: Vec<usize> = own[level].iter().rev().copied().collect();
7602        head[level] = chain.first().map_or(inherited, |first| *first as i32);
7603        for (position, &index) in chain.iter().enumerate() {
7604            let next = chain
7605                .get(position + 1)
7606                .map_or(inherited, |next| *next as i32);
7607            state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
7608        }
7609    }
7610    state.block_heads = head;
7611
7612    // The parameter list is a scope of its own, and it has no parent: the reference pops
7613    // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
7614    // the `-1` a block uses. A level past every real block keeps it out of the walk above
7615    // — nothing but the dump reads it — and the links run newest-to-oldest through the
7616    // bindings themselves, which is the order `set_loc_uninitialized` walks.
7617    let param_level = levels.len() as u32;
7618    let mut previous: Option<usize> = None;
7619    for index in 0..state.vars.len() {
7620        if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
7621        {
7622            continue;
7623        }
7624        state.vars[index].scope_level = param_level;
7625        state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
7626        previous = Some(index);
7627    }
7628}
7629
7630/// This is where names become slots and where the temporal dead zone shows up in
7631/// the instruction stream: a read of a `let`/`const` binding compiles to
7632/// `get_loc_check`, which throws if the binding is still uninitialised.
7633///
7634/// The peephole pass from the reference implementation is applied at the end,
7635/// for the same reason it is applied to resolved bytecode there: the patterns are
7636/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
7637/// resolution. Deleted instructions stay in the list as `None` so that label
7638/// indices remain valid; [`Assembler`] maps them to byte offsets.
7639/// A resolved instruction and the source position it came from.
7640type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
7641
7642/// A resolved instruction paired with its position, which is what `assemble` consumes.
7643type PositionedInsn = (Opcode, Vec<Op>);
7644
7645fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
7646    let current = stack.len() - 1;
7647    // Dead-code elimination, on the symbolic form where labels are still
7648    // instruction indices. A `break` inside a loop leaves the trailing `goto`
7649    // unreachable, and a `return` leaves everything after it unreachable; the
7650    // reference drops both. Doing it here means the emitter never has to think
7651    // about reachability.
7652    strip_empty_gosubs(stack, current);
7653    eliminate_dead_code(stack, current);
7654    let insns = std::mem::take(&mut stack[current].insns);
7655    // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
7656    // `insns`, and every arm below pushes exactly one instruction, so the positions
7657    // stay aligned with `out`.
7658    let positions = std::mem::take(&mut stack[current].insn_pos);
7659    let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
7660    let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
7661    for (index, insn) in insns.iter().enumerate() {
7662        let pos = positions.get(index).copied().flatten();
7663        out_pos.push(pos);
7664        match insn {
7665            Insn::Fixed { op, operands } => {
7666                let operands = operands
7667                    .iter()
7668                    .map(|operand| match operand {
7669                        Op::Atom(atom) => {
7670                            Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
7671                        }
7672                        other => other.clone(),
7673                    })
7674                    .collect();
7675                out.push(Some((*op, operands)));
7676            }
7677            Insn::Var {
7678                action,
7679                name,
7680                block,
7681                in_params,
7682            } => {
7683                // Both reads and writes in the parameter list address the parameter
7684                // scope. That is what puts the list in the temporal dead zone — a read of
7685                // a later parameter is `get_loc_check` on an uninitialised slot — and it
7686                // is also what keeps an assignment made inside a default away from the
7687                // body, which sees a separate environment.
7688                let slot = resolve_slot(stack, current, name, *block, *in_params);
7689                // A store to the name of a named function expression is special: the
7690                // reference drops it in sloppy mode and throws in strict mode, because
7691                // the binding is immutable but only *checked* when the body is strict.
7692                // The same rule applies when the name is reached through a closure:
7693                // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
7694                // the store in the arrow too, not just in the function that owns the
7695                // binding. Reaching the owner means walking the chain of closure
7696                // entries, which is what `self_name_binding` does.
7697                let self_name = matches!(action, VarAction::Put | VarAction::Set)
7698                    .then(|| {
7699                        // A local of this function is the common case and needs no
7700                        // chain walk; only an access that resolves elsewhere can be
7701                        // pointing at an enclosing function's name binding.
7702                        if let Slot::Loc(index) = slot {
7703                            stack[current]
7704                                .vars
7705                                .get(index as usize)
7706                                .filter(|var| var.kind == VarKind::FunctionName)
7707                                .map(|var| var.is_const)
7708                        } else {
7709                            self_name_binding(stack, current, name, *block)
7710                        }
7711                    })
7712                    .flatten();
7713                if let Some(is_const) = self_name {
7714                    out.push(Some(if is_const {
7715                        (
7716                            Opcode::ThrowError,
7717                            vec![
7718                                Op::AtomId(intern_atom(&mut stack[current], name)),
7719                                Op::Int(0),
7720                            ],
7721                        )
7722                    } else {
7723                        (Opcode::Drop, Vec::new())
7724                    }));
7725                    continue;
7726                }
7727                out.push(Some(variable_instruction(stack, current, *action, slot)));
7728            }
7729            Insn::CloseCaptured { name, block } => {
7730                // The block matters: a loop variable is scoped to the `for` head's own
7731                // block, so resolving it against block 0 would miss it entirely and
7732                // silently emit nothing.
7733                let slot = resolve_slot(stack, current, name, *block, false);
7734                // Only a local with a reference cell has anything to close. A global
7735                // or a never-captured local resolves to no instruction at all, which
7736                // keeps the bytecode identical to the reference's.
7737                if let Slot::Loc(index) = slot
7738                    && stack[current]
7739                        .vars
7740                        .get(index as usize)
7741                        .is_some_and(|v| v.is_captured)
7742                {
7743                    out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
7744                } else {
7745                    out.push(None);
7746                }
7747            }
7748            Insn::DeleteVar { name } => {
7749                // A binding — a local, an argument, or a declared global — cannot be
7750                // deleted, and the reference encodes that as a constant `push_false`.
7751                // Only an implicit global needs the runtime lookup.
7752                if matches!(
7753                    resolve_slot(stack, current, name, 0, false),
7754                    Slot::Global(_)
7755                ) {
7756                    let atom = intern_atom(&mut stack[current], name);
7757                    out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
7758                } else {
7759                    out.push(Some((Opcode::PushFalse, Vec::new())));
7760                }
7761            }
7762            Insn::Dead => out.push(None),
7763        }
7764    }
7765    // Which label (if any) sits on each instruction, so the jump patterns can
7766    // tell whether they would cross a jump target.
7767    let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
7768    for (id, placed) in stack[current].labels.iter().enumerate() {
7769        if let Some(index) = *placed
7770            && index < label_at.len()
7771            && label_at[index].is_none()
7772        {
7773            label_at[index] = Some(id as u32);
7774        }
7775    }
7776    if std::env::var_os("QJS_DEBUG").is_some() {
7777        eprintln!("--- peephole entry ---");
7778        for (i, e) in out.iter().enumerate() {
7779            eprintln!("{i}: {e:?}");
7780        }
7781        eprintln!("label_at: {label_at:?}");
7782    }
7783    peephole(&mut out, &label_at, &stack[current].labels);
7784    (out, out_pos)
7785}
7786
7787/// Find where `name` lives, capturing it in an enclosing function when needed.
7788///
7789/// The search runs outward through the enclosing functions' states, which are
7790/// still on the compiler stack while a nested function is resolved. Finding the
7791/// name in an enclosing function is what creates a closure reference, and every
7792/// function in between has to forward it — a function can only reach its own
7793/// parent's frame.
7794///
7795/// A name declared nowhere is a global. The reference does *not* look it up by
7796/// name from the inner function: the top-level function gets one `[global]`
7797/// entry and every nested function gets a `[global_ref<n>]` pointing at its
7798/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
7799/// rather than `[global]`.
7800/// The lexical blocks enclosing `block`, innermost first.
7801fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
7802    let mut chain = Vec::new();
7803    let mut current = Some(block);
7804    while let Some(key) = current {
7805        // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
7806        // explicitly (rather than on "no block with this key") is what keeps a block
7807        // that happens to sit at offset zero from being mistaken for the terminator.
7808        if key == NO_PARENT || chain.contains(&key) {
7809            break;
7810        }
7811        chain.push(key);
7812        current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
7813    }
7814    chain
7815}
7816
7817/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
7818///
7819/// The binding may be several functions away: an arrow nested in `function myfunc`
7820/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
7821/// means following `Ref` entries down and then reading the owning function's var table.
7822fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
7823    let state = stack.get(current)?;
7824    // A parameter shadows everything and is never a function-expression name.
7825    if state.args.iter().any(|arg| arg.name == name) {
7826        return None;
7827    }
7828    // A local of this very function: the answer is in its var table.
7829    if let Some(index) = local_slot_index(state, name, block) {
7830        let var = state.vars.get(index)?;
7831        return (var.kind == VarKind::FunctionName).then_some(var.is_const);
7832    }
7833    // Otherwise the name lives further out, and the closure entry says how to get
7834    // there. `Local` names the owner's slot directly; `Ref` names the next level's
7835    // closure entry, so the walk continues downwards.
7836    let mut level = current;
7837    let mut index = state
7838        .closure_vars
7839        .iter()
7840        .position(|closure| closure.name == name)?;
7841    loop {
7842        let state = stack.get(level)?;
7843        let closure = state.closure_vars.get(index)?;
7844        match closure.closure_type {
7845            ClosureType::Local => {
7846                let owner = stack.get(level.checked_sub(1)?)?;
7847                let var = owner.vars.get(closure.var_idx as usize)?;
7848                return (var.kind == VarKind::FunctionName).then_some(var.is_const);
7849            }
7850            ClosureType::Arg => return None,
7851            ClosureType::Ref => {
7852                level -= 1;
7853                index = closure.var_idx as usize;
7854            }
7855            // A global is never a function-expression name.
7856            ClosureType::Global
7857            | ClosureType::GlobalDecl
7858            | ClosureType::GlobalRef
7859            | ClosureType::ModuleDecl
7860            | ClosureType::ModuleImport => return None,
7861        }
7862    }
7863}
7864
7865/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
7866fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
7867    block_chain(state, block).into_iter().find_map(|scope| {
7868        state.vars.iter().enumerate().find_map(|(index, var)| {
7869            (var.name == name && state.var_block.get(index).copied() == Some(scope))
7870                .then_some(index)
7871        })
7872    })
7873}
7874
7875/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
7876fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
7877    if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
7878        var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
7879    }) {
7880        return index as u32;
7881    }
7882    state.var_block.push(PARAM_SCOPE);
7883    state.vars.push(VarDef::var(name));
7884    state.vars.len() as u32 - 1
7885}
7886
7887/// The name a parameter binds straight from its argument slot, if it has one.
7888///
7889/// A plain name does — with or without a default, and with or without `...`. Everything
7890/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
7891/// reference names the argument in the first case and leaves it `<null>` in the second,
7892/// so both the dump and the closures that capture the argument depend on this.
7893fn simple_parameter(param: &Pattern) -> Option<&Ident> {
7894    match &param.kind {
7895        PatternKind::Ident(name) => Some(name),
7896        PatternKind::Assign { target, .. } => match &target.kind {
7897            PatternKind::Ident(name) => Some(name),
7898            _ => None,
7899        },
7900        PatternKind::Rest(inner) => match &inner.kind {
7901            PatternKind::Ident(name) => Some(name),
7902            _ => None,
7903        },
7904        _ => None,
7905    }
7906}
7907
7908/// The pattern a parameter list has to unpick, if `index` is one of them.
7909fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
7910    prologue
7911        .iter()
7912        .find(|(at, _)| *at == index)
7913        .map(|(_, pattern)| pattern)
7914}
7915
7916/// Whether a parameter pattern contains a default anywhere, at any depth.
7917///
7918/// The reference decides "this function has parameter expressions" by scanning the
7919/// parenthesis for a top-level `=`, which a default buried in a pattern still counts as —
7920/// `function f({a = 1})` has a parameter scope just like `function f(a = 1)`.
7921/// Whether a function was written in *method* position, which `Function.prototype.toString`
7922/// reports without the leading name or modifiers.
7923///
7924/// The AST does not record this — a method is compiled as an ordinary `Function` — so it
7925/// is read back off the source: everything between the start of the definition and its
7926/// parameter list. A `function` keyword there means a function expression or declaration;
7927/// the absence of one means `m(){}`, `static m(){}`, `get x(){}` and friends.
7928fn is_method_syntax(source: Option<&str>, func: &ast::Function) -> bool {
7929    let Some(source) = source else {
7930        return false;
7931    };
7932    let start = func.span.start.offset as usize;
7933    let params = func.params_span.start.offset as usize;
7934    if start >= params {
7935        return false;
7936    }
7937    let Some(head) = source.get(start..params) else {
7938        return false;
7939    };
7940    !head.contains("function")
7941}
7942
7943fn pattern_has_default(pattern: &Pattern) -> bool {
7944    match &pattern.kind {
7945        PatternKind::Assign { .. } => true,
7946        PatternKind::Rest(inner) => pattern_has_default(inner),
7947        PatternKind::Array { elements, rest } => {
7948            elements.iter().flatten().any(element_has_default)
7949                || rest.as_deref().is_some_and(rest_has_default)
7950        }
7951        PatternKind::Object { properties, rest } => {
7952            properties.iter().flatten().any(element_has_default)
7953                || rest.as_deref().is_some_and(rest_has_default)
7954        }
7955        _ => false,
7956    }
7957}
7958
7959fn element_has_default(element: &PatternElement) -> bool {
7960    match element {
7961        PatternElement::Pattern(pattern) => pattern_has_default(pattern),
7962        PatternElement::Property { value, .. } => pattern_has_default(value),
7963    }
7964}
7965
7966fn rest_has_default(rest: &RestElement) -> bool {
7967    match rest {
7968        RestElement::Pattern(pattern) => pattern_has_default(pattern),
7969        RestElement::Member(_) => false,
7970    }
7971}
7972
7973/// Whether a function-scope binding is visible to the parameter list.
7974///
7975/// The parameter list runs before the body, so the body's `var`s and function
7976/// declarations do not exist yet — a name that only the body declares has to resolve
7977/// outward instead. What *does* exist by then is the compiler's own prologue: the
7978/// self-name of a named function expression (bound by `special_object 2` before anything
7979/// else), `this` and `new.target`. Those stay visible, which is what makes
7980/// `function f(a = this)` and `var f = function f(a = f)` work.
7981///
7982/// `arguments` is handled separately, as a binding of the parameter scope itself: with
7983/// parameter expressions the reference creates two of them, and the one the parameter
7984/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
7985fn visible_in_params(var: &VarDef) -> bool {
7986    var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
7987}
7988
7989fn resolve_slot(
7990    stack: &mut [FnState],
7991    current: usize,
7992    name: &str,
7993    block: u64,
7994    in_params: bool,
7995) -> Slot {
7996    // The parameter list's own bindings. They are consulted first because they shadow
7997    // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
7998    // `a` in the parameter scope, so a closure made there reads the parameter even after
7999    // the body assigns to its own `a`.
8000    if in_params
8001        && let Some(index) = stack[current]
8002            .vars
8003            .iter()
8004            .enumerate()
8005            .position(|(index, var)| {
8006                var.name == name
8007                    && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
8008            })
8009    {
8010        return Slot::Loc(index as u32);
8011    }
8012    // A name can be bound more than once: two `catch` parameters in nested
8013    // handlers are two slots. The binding that wins is the one whose scope encloses
8014    // the access, and among those the innermost — so the blocks are walked outward
8015    // and the first binding found on the way is the one that counts. A binding in
8016    // no block (`var`) is reachable from anywhere, which is why the function scope
8017    // is the end of the walk.
8018    //
8019    // The block walk comes *before* the argument slots, because a block may shadow a
8020    // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
8021    // slot is only the answer once nothing nearer claims the name.
8022    let chain = block_chain(&stack[current], block);
8023    for scope in &chain {
8024        let found = stack[current]
8025            .vars
8026            .iter()
8027            .enumerate()
8028            .find(|(index, var)| {
8029                var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
8030            })
8031            .map(|(index, _)| index);
8032        if let Some(index) = found {
8033            return Slot::Loc(index as u32);
8034        }
8035    }
8036    // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
8037    // its own slot, and `var` of the same name in the body is the same binding.
8038    if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
8039        return Slot::Arg(index as u32);
8040    }
8041    // Function-scope bindings — `var` and function declarations — are recorded with
8042    // the sentinel block `0`, which no real scope uses, so the walk above cannot see
8043    // them. They are reachable from anywhere in the function, which is exactly what
8044    // the sentinel means.
8045    //
8046    // This pass is *only* for those. A lexical binding has to be found through the
8047    // chain or not at all, and looking a name up without its block is precisely how
8048    // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
8049    // block leaked out of it.
8050    let function_scoped = stack[current]
8051        .vars
8052        .iter()
8053        .enumerate()
8054        .find(|(index, var)| {
8055            var.name == name
8056                && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
8057                && (!in_params || visible_in_params(var))
8058        })
8059        .map(|(index, _)| index);
8060    if let Some(index) = function_scoped {
8061        return Slot::Loc(index as u32);
8062    }
8063    if let Some(index) = stack[current]
8064        .closure_vars
8065        .iter()
8066        .position(|c| c.name == name)
8067    {
8068        return slot_for_closure(&stack[current].closure_vars[index], index as u32);
8069    }
8070
8071    for owner in (0..current).rev() {
8072        // The nested function was created inside one of this frame's blocks, and the
8073        // outermost visible binding is the innermost block on that chain — not whatever
8074        // comes first in the variable table. `function f(){ class S{} }` has two `S`
8075        // bindings: the `let S` inside `f` and the `const S` inside the class body, and
8076        // the class body is the one a method may see.
8077        let entry = stack
8078            .get(owner + 1)
8079            .map(|s| s.created_in_block)
8080            .unwrap_or(0);
8081        let lexical = block_chain(&stack[owner], entry)
8082            .into_iter()
8083            .find_map(|scope| {
8084                stack[owner]
8085                    .vars
8086                    .iter()
8087                    .enumerate()
8088                    .find(|(index, var)| {
8089                        var.name == name
8090                            && stack[owner].var_block.get(*index).copied() == Some(scope)
8091                    })
8092                    .map(|(index, _)| index)
8093            });
8094        // A function born in a parameter list sees that list's bindings, not the body's:
8095        // the parameter scope is the environment it was created in.
8096        let in_param_scope = stack
8097            .get(owner + 1)
8098            .is_some_and(|child| child.created_in_params)
8099            .then(|| {
8100                stack[owner]
8101                    .vars
8102                    .iter()
8103                    .enumerate()
8104                    .position(|(index, var)| {
8105                        var.name == name
8106                            && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
8107                    })
8108            })
8109            .flatten();
8110        let found = if let Some(index) = in_param_scope {
8111            let var = &stack[owner].vars[index];
8112            Some(Found::Local(
8113                ClosureType::Local,
8114                index as u32,
8115                var.is_const,
8116                var.needs_check(),
8117            ))
8118        } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
8119            Some(Found::Local(ClosureType::Arg, index as u32, false, false))
8120        } else if let Some(index) = lexical {
8121            let var = &stack[owner].vars[index];
8122            Some(Found::Local(
8123                ClosureType::Local,
8124                index as u32,
8125                var.is_const,
8126                var.needs_check(),
8127            ))
8128        } else if let Some(index) = stack[owner]
8129            .vars
8130            .iter()
8131            .enumerate()
8132            .find_map(|(index, var)| {
8133                // A function created inside a parameter list must not see the body of the
8134                // function it was born in; see [`FnState::created_in_params`].
8135                let hidden = stack
8136                    .get(owner + 1)
8137                    .is_some_and(|child| child.created_in_params);
8138                (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
8139            })
8140        {
8141            let var = &stack[owner].vars[index];
8142            Some(Found::Local(
8143                ClosureType::Local,
8144                index as u32,
8145                var.is_const,
8146                var.needs_check(),
8147            ))
8148        } else if stack[owner].self_name.as_deref() == Some(name) {
8149            // A named function expression's own name. The reference declares it here,
8150            // on the first lookup that fails, rather than up front — and that is what
8151            // makes it reachable from a *nested* function: the nested lookup is what
8152            // walks out and creates the binding. A direct reference in the body is
8153            // caught the same way, which is why `provide_self_name` only has to add
8154            // the prologue.
8155            let strict = stack[owner].strict;
8156            stack[owner].var_block.push(FUNCTION_SCOPE);
8157            stack[owner].vars.push(VarDef {
8158                kind: VarKind::FunctionName,
8159                // In strict mode the name is immutable, so a store raises; sloppy
8160                // mode drops the store instead (see `variable_instruction`).
8161                is_const: strict,
8162                ..VarDef::var(name)
8163            });
8164            let index = stack[owner].vars.len() as u32 - 1;
8165            Some(Found::Local(ClosureType::Local, index, strict, false))
8166        } else if let Some(index) = stack[owner]
8167            .closure_vars
8168            .iter()
8169            .position(|c| c.name == name)
8170        {
8171            let closure = &stack[owner].closure_vars[index];
8172            Some(match closure.closure_type {
8173                // `GlobalRef` belongs here too: it is a *global* reached through this
8174                // frame's reference table, so treating it as a `Ref` to a local cell makes
8175                // the reader look for a cell no frame ever fills. That is how a second
8176                // function using `eval` in its parameter list read `undefined` after a
8177                // sibling had already made `eval` a closure entry.
8178                ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
8179                    Found::Global(index as u32)
8180                }
8181                // A module variable is a cell in the *module's* environment, which is
8182                // the module body's parent as far as a nested function is concerned — so
8183                // it is captured as a plain reference, not looked up as a global.
8184                ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
8185                    ClosureType::Ref,
8186                    index as u32,
8187                    closure.is_const,
8188                    closure.is_lexical,
8189                ),
8190                _ => Found::Local(
8191                    ClosureType::Ref,
8192                    index as u32,
8193                    closure.is_const,
8194                    closure.is_lexical,
8195                ),
8196            })
8197        } else {
8198            None
8199        };
8200        let Some(found) = found else { continue };
8201
8202        let (is_const, is_lexical) = match found {
8203            Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
8204            Found::Global(_) => (false, false),
8205        };
8206        // Mark the owner's binding as captured so it moves into a reference cell.
8207        if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
8208            let slot = match found {
8209                Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
8210                _ => &mut stack[owner].vars[index as usize],
8211            };
8212            slot.is_captured = true;
8213        }
8214        // Forward the reference through every function in between.
8215        let mut previous = match found {
8216            Found::Local(kind, index, _, _) => (kind, index),
8217            Found::Global(index) => (ClosureType::Global, index),
8218        };
8219        for level in owner + 1..=current {
8220            let kind = match (previous.0, level) {
8221                // A global stays a global at *every* level. Without `GlobalRef` in
8222                // this arm the second nested function over the same global got a
8223                // `Ref` to a cell no frame ever held, so the innermost closure read
8224                // `undefined` — which is how a two-deep getter lost its outer
8225                // variable.
8226                (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
8227                    ClosureType::GlobalRef
8228                }
8229                (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
8230                _ => ClosureType::Ref,
8231            };
8232            let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
8233            previous = (kind, index);
8234        }
8235        let index = previous.1;
8236        return slot_for_closure(&stack[current].closure_vars[index as usize], index);
8237    }
8238
8239    // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
8240    // creating a property. The top-level function holds the entry.
8241    let mut previous = (
8242        ClosureType::Global,
8243        ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
8244    );
8245    for level in 1..=current {
8246        let index = ensure_closure(
8247            stack,
8248            level,
8249            name,
8250            false,
8251            false,
8252            ClosureType::GlobalRef,
8253            previous.1,
8254        );
8255        previous = (ClosureType::GlobalRef, index);
8256    }
8257    Slot::Global(previous.1)
8258}
8259
8260/// What an outward search turned up.
8261#[derive(Debug, Clone, Copy)]
8262enum Found {
8263    /// A binding in an enclosing function, reachable through a closure of this
8264    /// type, with its const/lexical flags.
8265    Local(ClosureType, u32, bool, bool),
8266    /// A global, reached through the enclosing function's closure entry.
8267    Global(u32),
8268}
8269
8270/// Add a closure entry to `level` if it is not there yet.
8271fn ensure_closure(
8272    stack: &mut [FnState],
8273    level: usize,
8274    name: &str,
8275    is_const: bool,
8276    is_lexical: bool,
8277    closure_type: ClosureType,
8278    var_idx: u32,
8279) -> u32 {
8280    if let Some(index) = stack[level]
8281        .closure_vars
8282        .iter()
8283        .position(|c| c.name == name)
8284    {
8285        return index as u32;
8286    }
8287    stack[level].closure_vars.push(ClosureVar {
8288        name: name.to_string(),
8289        is_const,
8290        is_lexical,
8291        closure_type,
8292        var_idx: var_idx as u16,
8293    });
8294    stack[level].closure_vars.len() as u32 - 1
8295}
8296
8297fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
8298    match closure.closure_type {
8299        // A `global_ref` only says *how* the binding is found (through the
8300        // parent's closure table); the access itself is an ordinary global one.
8301        ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
8302        ClosureType::GlobalDecl => Slot::GlobalDecl(index),
8303        // A module variable is a real cell in the module's environment, so it is reached
8304        // exactly like a captured local — the host, not the global object, is what fills
8305        // the slot.
8306        ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
8307        _ => Slot::VarRef(index),
8308    }
8309}
8310
8311/// Pick the opcode for one variable access.
8312///
8313/// The `_check` variants are what enforce the temporal dead zone. They are used
8314/// for every access to a `let`/`const` binding except its own initialisation —
8315/// which is exactly the operation that takes the binding out of the dead zone.
8316fn variable_instruction(
8317    stack: &[FnState],
8318    current: usize,
8319    action: VarAction,
8320    slot: Slot,
8321) -> (Opcode, Vec<Op>) {
8322    let lexical = match slot {
8323        Slot::Loc(index) => stack[current]
8324            .vars
8325            .get(index as usize)
8326            .is_some_and(|v| v.needs_check()),
8327        Slot::VarRef(index) => stack[current]
8328            .closure_vars
8329            .get(index as usize)
8330            .is_some_and(|c| c.is_lexical),
8331        _ => false,
8332    };
8333    let operand = vec![Op::Slot(slot)];
8334    match (action, slot) {
8335        (VarAction::Get, Slot::Loc(index)) => (
8336            if lexical {
8337                Opcode::GetLocCheck
8338            } else {
8339                Opcode::GetLoc
8340            },
8341            vec![Op::Slot(Slot::Loc(index))],
8342        ),
8343        (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
8344        (VarAction::Get, Slot::VarRef(index)) => (
8345            if lexical {
8346                Opcode::GetVarRefCheck
8347            } else {
8348                Opcode::GetVarRef
8349            },
8350            vec![Op::Slot(Slot::VarRef(index))],
8351        ),
8352        (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
8353        (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
8354        (VarAction::GetUndef, Slot::Loc(_)) => (Opcode::GetLoc, operand),
8355        (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
8356        (VarAction::GetUndef, Slot::VarRef(_)) => (Opcode::GetVarRef, operand),
8357        (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8358            (Opcode::GetVarUndef, operand)
8359        }
8360
8361        (VarAction::Put, Slot::Loc(_)) => (
8362            if lexical {
8363                Opcode::PutLocCheck
8364            } else {
8365                Opcode::PutLoc
8366            },
8367            operand,
8368        ),
8369        (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
8370        (VarAction::Put, Slot::VarRef(_)) => (
8371            if lexical {
8372                Opcode::PutVarRefCheck
8373            } else {
8374                Opcode::PutVarRef
8375            },
8376            operand,
8377        ),
8378        (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
8379        (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8380        // Initialisation is what ends the dead zone, so it never checks.
8381        (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8382        (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
8383        // `this` in a derived constructor is always a local, so these cannot happen;
8384        // routing them to the ordinary forms keeps the match total without inventing
8385        // opcodes the reference does not have.
8386        (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
8387        (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8388        (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8389            (Opcode::PutVarInit, operand)
8390        }
8391        (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
8392        (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8393        (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8394            (Opcode::PutVarInit, operand)
8395        }
8396        (VarAction::Set, Slot::Loc(_)) => (
8397            if lexical {
8398                Opcode::SetLocCheck
8399            } else {
8400                Opcode::SetLoc
8401            },
8402            operand,
8403        ),
8404        (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
8405        (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
8406        (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8407        (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8408        (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
8409        (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8410        (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
8411        (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
8412        (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8413        (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
8414        (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8415        (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
8416    }
8417}
8418
8419/// The instruction-rewriting pass.
8420///
8421/// These are the reference implementation's patterns, restricted to the ones the
8422/// constructs this compiler supports can produce. Each entry is a comment on the
8423/// bytecode it removes, because the whole point is that the result is one
8424/// instruction shorter than the literal translation of the AST.
8425fn peephole(
8426    insns: &mut [Option<(Opcode, Vec<Op>)>],
8427    label_at: &[Option<u32>],
8428    placed: &[Option<usize>],
8429) {
8430    fold_dup_patterns(insns, label_at);
8431
8432    // `drop` before `return_undef` is dead: the return discards the whole frame
8433    // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
8434    // consumes its own `drop`; removing the drop first would leave the `dup` and
8435    // produce a `set_` where the reference has a `put_`.
8436    for index in 0..insns.len() {
8437        if opcode_at(insns, index) != Some(Opcode::Drop) {
8438            continue;
8439        }
8440        // Skip over a run of drops, but stop at a jump target: removing code on
8441        // one side of a label would silently retarget the jump.
8442        let mut next = index + 1;
8443        while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
8444            next += 1;
8445        }
8446        if is_label_at(label_at, next) {
8447            continue;
8448        }
8449        if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
8450            for entry in &mut insns[index..next] {
8451                *entry = None;
8452            }
8453        }
8454    }
8455
8456    // The rewrites below all decide against one fixed snapshot, which is what the
8457    // reference sees: `code_match` reads the bytecode buffer as it was on entry to
8458    // the pass, so a rule never observes what an earlier rule removed. Gathering
8459    // every deletion first and applying them together reproduces that.
8460    let snapshot: Vec<Option<Opcode>> = insns
8461        .iter()
8462        .map(|entry| entry.as_ref().map(|(op, _)| *op))
8463        .collect();
8464    // The next instruction that is still there. Holes left by dead-code
8465    // elimination are not instructions, so a rule looks past them.
8466    let next_op = |index: usize| -> Option<usize> {
8467        (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
8468    };
8469
8470    let mut doomed = vec![false; insns.len()];
8471    for index in 0..insns.len() {
8472        // A constant pushed only to be dropped does nothing at all. This is what a
8473        // comma expression with a literal left operand compiles to — `(0, f)()` — and
8474        // the reference removes the pair rather than making the reader step over it.
8475        let constant = matches!(
8476            snapshot[index],
8477            Some(
8478                Opcode::Undefined
8479                    | Opcode::Null
8480                    | Opcode::PushMinus1
8481                    | Opcode::Push0
8482                    | Opcode::Push1
8483                    | Opcode::Push2
8484                    | Opcode::Push3
8485                    | Opcode::Push4
8486                    | Opcode::Push5
8487                    | Opcode::Push6
8488                    | Opcode::Push7
8489                    | Opcode::PushTrue
8490                    | Opcode::PushFalse
8491                    | Opcode::PushI32
8492            )
8493        );
8494        if constant
8495            && let Some(next) = next_op(index)
8496            && snapshot[next] == Some(Opcode::Drop)
8497        {
8498            doomed[index] = true;
8499            doomed[next] = true;
8500        }
8501    }
8502    for (index, entry) in insns.iter_mut().enumerate() {
8503        if doomed[index] {
8504            *entry = None;
8505        }
8506    }
8507
8508    // A conditional whose destination is the very next instruction just pops its
8509    // condition, so it becomes a plain `drop`. This is what an empty `case` clause
8510    // compiles to.
8511    //
8512    // Order matters, and it is the reference's order: this runs *before* the
8513    // folding below, on the instruction the conditional originally had. Folding
8514    // moves a conditional's destination, and the reference never re-examines it
8515    // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
8516    // a conditional even though folding leaves it pointing at the next
8517    // instruction.
8518    for (index, entry) in insns.iter_mut().enumerate() {
8519        let Some((op, operands)) = entry.clone() else {
8520            continue;
8521        };
8522        if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
8523            continue;
8524        }
8525        let Some(id) = label_id(&operands) else {
8526            continue;
8527        };
8528        if placed.get(id as usize).copied().flatten() == Some(index + 1) {
8529            *entry = Some((Opcode::Drop, Vec::new()));
8530        }
8531    }
8532
8533    // A constant condition is decided here rather than at run time.
8534    fold_constant_conditions(insns);
8535    // The conditional folding below is about pairs of *real* branches, so it runs
8536    // before a jump to the next instruction is dropped: `do { … if (c) continue }
8537    // while (t)` puts `continue` exactly on the condition, and the reference inverts
8538    // the branch first and only then notices the jump goes nowhere.
8539    fold_conditional_jumps(insns, label_at, placed);
8540
8541    // A jump whose destination is the very next instruction does nothing, which is
8542    // what constant folding leaves behind for `while (1) { … }`.
8543    remove_jump_to_next(insns, placed);
8544
8545    // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
8546    // a use of the same variable boils down to.
8547    for index in 0..insns.len() {
8548        let Some((put_op, _)) = insns[index].clone() else {
8549            continue;
8550        };
8551        if !is_foldable_put(put_op) {
8552            continue;
8553        }
8554        if is_label_at(label_at, index + 1) {
8555            continue;
8556        }
8557        let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
8558            continue;
8559        };
8560        if get_op != get_form_of(put_op) {
8561            continue;
8562        }
8563        let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
8564        if put_slot.is_none() || put_slot != get_operands.first().cloned() {
8565            continue;
8566        }
8567        insns[index] = Some((set_form_of(put_op), get_operands));
8568        insns[index + 1] = None;
8569    }
8570}
8571
8572/// Drop `gosub`s that call an empty subroutine.
8573///
8574/// A `gosub` whose target starts with `ret` returns immediately, so the reference
8575/// drops the call. This is how `try`/`catch` without a `finally` loses its
8576/// finalizer plumbing: the finalizer block is empty, its first instruction is
8577/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
8578/// [`eliminate_dead_code`] then removes.
8579fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
8580    let state = &stack[current];
8581    let mut targets = Vec::new();
8582    for insn in &state.insns {
8583        if let Insn::Fixed { op, operands } = insn
8584            && *op == Opcode::Gosub
8585            && let Some(id) = label_id(operands)
8586            && let Some(target) = state.labels.get(id as usize).copied().flatten()
8587        {
8588            targets.push(target);
8589        }
8590    }
8591    let empty: Vec<usize> = targets
8592        .into_iter()
8593        .filter(|target| {
8594            stack[current]
8595                .insns
8596                .get(*target)
8597                .map(|insn| {
8598                    matches!(
8599                        insn,
8600                        Insn::Fixed {
8601                            op: Opcode::Ret,
8602                            ..
8603                        }
8604                    )
8605                })
8606                .unwrap_or(false)
8607        })
8608        .collect();
8609    if empty.is_empty() {
8610        return;
8611    }
8612    for insn in stack[current].insns.iter_mut() {
8613        if let Insn::Fixed { op, operands } = insn
8614            && *op == Opcode::Gosub
8615            && let Some(id) = label_id(operands)
8616            && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
8617            && empty.contains(&target)
8618        {
8619            *insn = Insn::Dead;
8620        }
8621    }
8622}
8623
8624/// Replace unreachable instructions with [`Insn::Dead`].
8625fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
8626    let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
8627    for (index, insn) in stack[current].insns.iter_mut().enumerate() {
8628        if !reachable[index] {
8629            *insn = Insn::Dead;
8630        }
8631    }
8632}
8633
8634/// Mark every instruction index reachable from the entry, plus the index one past
8635/// the last instruction.
8636///
8637/// `seen[len]` answers "can control reach the end of this function", and the
8638/// entries before it identify dead code. Both DCE and the implicit-return decision
8639/// read the same result, which keeps them from disagreeing.
8640fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
8641    let mut seen = vec![false; count + 1];
8642    let mut worklist = vec![0usize];
8643    while let Some(index) = worklist.pop() {
8644        if index > count || seen[index] {
8645            continue;
8646        }
8647        seen[index] = true;
8648        if index == count {
8649            continue;
8650        }
8651        let (op, operands) = match &state.insns[index] {
8652            Insn::Fixed { op, operands } => (*op, operands.as_slice()),
8653            // A variable access never transfers control, and a removed
8654            // instruction is only reachable if it is already marked.
8655            Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
8656                worklist.push(index + 1);
8657                continue;
8658            }
8659        };
8660        match op {
8661            // A return, a throw and a `ret` all leave this instruction stream: the
8662            // first two give control to the caller or the handler, and `ret`
8663            // returns to a `gosub` elsewhere.
8664            // A tail call leaves the function too: the callee's result becomes this
8665            // function's result, so nothing after it runs.
8666            Opcode::Return
8667            | Opcode::ReturnUndef
8668            | Opcode::ReturnAsync
8669            | Opcode::TailCall
8670            | Opcode::TailCallMethod
8671            | Opcode::Throw
8672            | Opcode::ThrowError
8673            | Opcode::Ret => {}
8674            // A `catch` records where exceptions from the code that follows go.
8675            // That code is not reachable through normal control flow, but it is
8676            // reachable — through the exception edge — so the walk has to follow
8677            // it, or dead-code elimination would delete every handler.
8678            Opcode::Catch => {
8679                if let Some(target) = placed_label(state, operands) {
8680                    worklist.push(target);
8681                }
8682                worklist.push(index + 1);
8683            }
8684            // A `gosub` calls a subroutine and then continues, so both edges count.
8685            Opcode::Gosub => {
8686                if let Some(target) = placed_label(state, operands) {
8687                    worklist.push(target);
8688                }
8689                worklist.push(index + 1);
8690            }
8691            Opcode::Goto => {
8692                if let Some(target) = placed_label(state, operands) {
8693                    worklist.push(target);
8694                }
8695            }
8696            Opcode::IfTrue | Opcode::IfFalse => {
8697                if let Some(target) = placed_label(state, operands) {
8698                    worklist.push(target);
8699                }
8700                worklist.push(index + 1);
8701            }
8702            _ => worklist.push(index + 1),
8703        }
8704    }
8705    seen
8706}
8707
8708/// The instruction index a jump operand points at, resolved through the label
8709/// placement table.
8710fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
8711    let id = label_id(operands)?;
8712    state.labels.get(id as usize).copied().flatten()
8713}
8714
8715/// The label an instruction refers to.
8716fn label_id(operands: &[Op]) -> Option<u32> {
8717    operands.iter().find_map(|operand| match operand {
8718        Op::Label(label) => Some(label.0),
8719        _ => None,
8720    })
8721}
8722
8723/// Turn `if_false L; goto M; L:` into `if_true M`.
8724///
8725/// A conditional whose alternate branch is an unconditional jump needs one jump,
8726/// not two. This is the shape `if (c) break;` produces, so folding it removes an
8727/// instruction and a label from every conditional `break`.
8728/// The boolean a constant-push instruction produces, or `None` if it is not one.
8729///
8730/// Only the operators whose truthiness is decided by the opcode are covered; a
8731/// constant that needs the constant pool (a string) is left alone, because reading it
8732/// would mean threading the pool through the peephole for a case the reference also
8733/// skips.
8734fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
8735    match op {
8736        // `push_0` returns -1 for zero, `push_1` 1, and so on.
8737        Opcode::PushMinus1 => Some(true),
8738        Opcode::Push0 => Some(false),
8739        Opcode::Push1
8740        | Opcode::Push2
8741        | Opcode::Push3
8742        | Opcode::Push4
8743        | Opcode::Push5
8744        | Opcode::Push6
8745        | Opcode::Push7 => Some(true),
8746        Opcode::PushTrue => Some(true),
8747        Opcode::PushFalse => Some(false),
8748        Opcode::Undefined | Opcode::Null => Some(false),
8749        Opcode::PushI32 => match operands.first() {
8750            Some(Op::Int(value)) => Some(*value != 0),
8751            _ => None,
8752        },
8753        _ => None,
8754    }
8755}
8756
8757/// Fold a branch on a constant condition.
8758///
8759/// `if (0) a() else b()` must not test anything at run time, and the reference
8760/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
8761/// which is why the bytecode for a `while (1)` loop has no condition at all.
8762///
8763/// Two instructions become one, so the slot the test occupied is left empty rather
8764/// than shifting everything after it: labels have already been resolved to indices.
8765fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>]) {
8766    for index in 0..insns.len() {
8767        let Some((push_op, push_operands)) = insns[index].clone() else {
8768            continue;
8769        };
8770        let Some(truth) = constant_truth(push_op, &push_operands) else {
8771            continue;
8772        };
8773        let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
8774            continue;
8775        };
8776        let (destination, taken) = match branch_op {
8777            Opcode::IfTrue => (branch_operands.first().cloned(), truth),
8778            Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
8779            _ => continue,
8780        };
8781        let Some(destination) = destination else {
8782            continue;
8783        };
8784        insns[index] = if taken {
8785            // The branch is always taken, so it becomes an unconditional jump.
8786            Some((Opcode::Goto, vec![destination]))
8787        } else {
8788            // The branch never runs: both instructions disappear and control falls
8789            // through to what came after.
8790            None
8791        };
8792        insns[index + 1] = None;
8793    }
8794}
8795
8796/// Remove a jump whose destination is the instruction right after it.
8797///
8798/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
8799/// its test into nothing, and the loop-end jump then points at the following
8800/// instruction. The reference drops them, so `stack_size` and the listing agree.
8801fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
8802    for index in 0..insns.len() {
8803        let Some((op, operands)) = insns[index].clone() else {
8804            continue;
8805        };
8806        if !is_goto(op) {
8807            continue;
8808        }
8809        let Some(id) = label_id(&operands) else {
8810            continue;
8811        };
8812        // The next instruction that still exists, which is what "the instruction
8813        // after this jump" means once earlier folds have punched holes.
8814        let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
8815        if placed.get(id as usize).copied().flatten() == next {
8816            insns[index] = None;
8817        }
8818    }
8819}
8820
8821fn fold_conditional_jumps(
8822    insns: &mut [Option<(Opcode, Vec<Op>)>],
8823    label_at: &[Option<u32>],
8824    placed: &[Option<usize>],
8825) {
8826    for index in 0..insns.len() {
8827        let Some((op, operands)) = insns[index].clone() else {
8828            continue;
8829        };
8830        let inverted = match op {
8831            Opcode::IfFalse => Opcode::IfTrue,
8832            Opcode::IfTrue => Opcode::IfFalse,
8833            _ => continue,
8834        };
8835        // Next must be an unconditional jump that is not itself a target, and the
8836        // instruction after it must be exactly where the conditional goes.
8837        let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
8838            continue;
8839        };
8840        if !is_goto(next_op) || is_label_at(label_at, index + 1) {
8841            continue;
8842        }
8843        // The conditional must land on the instruction *after* the jump. Several
8844        // labels can share a position, so this asks where *this* label was put
8845        // rather than what label happens to sit there.
8846        let Some(taken) = label_id(&operands) else {
8847            continue;
8848        };
8849        if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
8850            continue;
8851        }
8852        let Some(destination) = next_operands.first().cloned() else {
8853            continue;
8854        };
8855        insns[index] = Some((inverted, vec![destination]));
8856        insns[index + 1] = None;
8857    }
8858}
8859
8860/// Whether a jump target is placed at this instruction index.
8861fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
8862    label_at.get(index).copied().flatten().is_some()
8863}
8864
8865fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
8866    // `dup put_x(n)` -> `set_x(n)`
8867    // `dup put_x(n) drop` -> `put_x(n)`
8868    // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
8869    for index in 0..insns.len() {
8870        if opcode_at(insns, index) != Some(Opcode::Dup) {
8871            continue;
8872        }
8873        if is_label_at(label_at, index + 1) {
8874            continue;
8875        }
8876        let Some((put_op, put_operands)) = insns[index + 1].clone() else {
8877            continue;
8878        };
8879        if !is_foldable_put(put_op) {
8880            continue;
8881        }
8882        let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
8883            continue;
8884        };
8885        let mut new_op = set_form_of(put_op);
8886        let mut end = index + 2;
8887        if is_label_at(label_at, end) {
8888            // The `put` has to stay as it is; only the `dup` can be folded.
8889            insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
8890            insns[index + 1] = None;
8891            continue;
8892        }
8893        // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
8894        // Deleting it moves the label's target onto whatever follows, and the code that
8895        // jumps there arrives with a different stack than the fall-through path: that is
8896        // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
8897        // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
8898        // an empty stack. The store had already consumed the value it was supposed to
8899        // leave behind.
8900        if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
8901            new_op = put_op;
8902            end += 1;
8903            if opcode_at(insns, end) == Some(get_form_of(put_op))
8904                && !is_label_at(label_at, end)
8905                && insns[end]
8906                    .as_ref()
8907                    .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
8908            {
8909                new_op = set_form_of(put_op);
8910                end += 1;
8911            }
8912        }
8913        insns[index] = Some((new_op, vec![Op::Slot(slot)]));
8914        for entry in &mut insns[index + 1..end] {
8915            *entry = None;
8916        }
8917    }
8918}
8919
8920fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
8921    insns
8922        .get(index)
8923        .and_then(|entry| entry.as_ref())
8924        .map(|(op, _)| *op)
8925}
8926
8927/// The four `put_` families that have a `set_` twin. Deliberately not including
8928/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
8929/// these, and folding the others would produce instructions that do not exist.
8930fn is_foldable_put(op: Opcode) -> bool {
8931    matches!(
8932        op,
8933        Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
8934    )
8935}
8936
8937fn set_form_of(op: Opcode) -> Opcode {
8938    match op {
8939        Opcode::PutLoc => Opcode::SetLoc,
8940        Opcode::PutLocCheck => Opcode::SetLocCheck,
8941        Opcode::PutArg => Opcode::SetArg,
8942        Opcode::PutVarRef => Opcode::SetVarRef,
8943        other => other,
8944    }
8945}
8946
8947fn get_form_of(op: Opcode) -> Opcode {
8948    match op {
8949        Opcode::PutLoc => Opcode::GetLoc,
8950        Opcode::PutLocCheck => Opcode::GetLocCheck,
8951        Opcode::PutArg => Opcode::GetArg,
8952        Opcode::PutVarRef => Opcode::GetVarRef,
8953        other => other,
8954    }
8955}
8956
8957/// Atom interning, per function.
8958///
8959/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
8960/// identifiers, so the array-index rule applies here rather than at the handful of
8961/// call sites that build property keys.
8962fn intern_atom(state: &mut FnState, name: &str) -> u32 {
8963    intern_atom_value(state, Atom::from_text(name))
8964}
8965
8966/// [`intern_atom`] for an operand that is already an [`Atom`].
8967///
8968/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
8969/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
8970/// would have looked up.
8971fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
8972    if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
8973        return index as u32;
8974    }
8975    state.atoms.push(atom);
8976    state.atoms.len() as u32 - 1
8977}
8978
8979fn binary_opcode(op: BinaryOp) -> Opcode {
8980    match op {
8981        BinaryOp::Add => Opcode::Add,
8982        BinaryOp::Sub => Opcode::Sub,
8983        BinaryOp::Mul => Opcode::Mul,
8984        BinaryOp::Div => Opcode::Div,
8985        BinaryOp::Mod => Opcode::Mod,
8986        BinaryOp::Pow => Opcode::Pow,
8987        BinaryOp::BitOr => Opcode::Or,
8988        BinaryOp::BitXor => Opcode::Xor,
8989        BinaryOp::BitAnd => Opcode::And,
8990        BinaryOp::Shl => Opcode::Shl,
8991        BinaryOp::Shr => Opcode::Sar,
8992        BinaryOp::UShr => Opcode::Shr,
8993        BinaryOp::Lt => Opcode::Lt,
8994        BinaryOp::LtEq => Opcode::Lte,
8995        BinaryOp::Gt => Opcode::Gt,
8996        BinaryOp::GtEq => Opcode::Gte,
8997        BinaryOp::Eq => Opcode::Eq,
8998        BinaryOp::NotEq => Opcode::Neq,
8999        BinaryOp::StrictEq => Opcode::StrictEq,
9000        BinaryOp::StrictNotEq => Opcode::StrictNeq,
9001        BinaryOp::In => Opcode::In,
9002        BinaryOp::Instanceof => Opcode::Instanceof,
9003    }
9004}
9005
9006fn compound_opcode(op: AssignOp) -> Opcode {
9007    match op {
9008        AssignOp::Add => Opcode::Add,
9009        AssignOp::Sub => Opcode::Sub,
9010        AssignOp::Mul => Opcode::Mul,
9011        AssignOp::Div => Opcode::Div,
9012        AssignOp::Mod => Opcode::Mod,
9013        AssignOp::Pow => Opcode::Pow,
9014        AssignOp::Shl => Opcode::Shl,
9015        AssignOp::Shr => Opcode::Sar,
9016        AssignOp::UShr => Opcode::Shr,
9017        AssignOp::BitOr => Opcode::Or,
9018        AssignOp::BitXor => Opcode::Xor,
9019        AssignOp::BitAnd => Opcode::And,
9020        AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
9021    }
9022}
9023
9024/// Encode the resolved instruction stream, choosing short forms where possible.
9025///
9026/// The peephole pass leaves holes in the instruction list so that label indices
9027/// stay valid. A label names an *instruction index*, and an index that was
9028/// deleted has to resolve to the next surviving instruction, which is what
9029/// [`resolve_label`] does before the byte offsets are known.
9030fn assemble(
9031    insns: &mut [Option<(Opcode, Vec<Op>)>],
9032    insn_pos: &[Option<Position>],
9033    state: &mut FnState,
9034) -> (Vec<u8>, u32, Vec<LineCol>) {
9035    // Compaction: surviving instructions in order, plus the index mapping.
9036    //
9037    // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
9038    // point below where instructions are removed — otherwise a stack trace would point
9039    // at the wrong source line as soon as dead-code elimination kicked in.
9040    let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
9041    let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
9042    let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
9043    for (original, entry) in insns.iter_mut().enumerate() {
9044        if let Some((op, operands)) = entry.take() {
9045            original_to_kept[original] = Some(kept.len());
9046            kept.push((op, operands));
9047            spans.push(insn_pos.get(original).copied().flatten());
9048        }
9049    }
9050
9051    if std::env::var_os("QJS_DEBUG").is_some() {
9052        eprintln!("--- assemble entry --- {kept:?}");
9053    }
9054    // How many labels are real, as opposed to the per-instruction ones allocated
9055    // just below. Only a real label marks a spot in the source program.
9056    let real_labels = state.labels.len();
9057
9058    // Give every surviving instruction a label of its own. Jump cleanup below
9059    // redirects jumps to arbitrary instructions, and a jump target has to be a
9060    // label; pre-allocating one per index means a redirect never has to invent
9061    // anything.
9062    let existing = state.labels.len();
9063    let base = kept.len();
9064    let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
9065    for offset in 0..=kept.len() {
9066        state.labels.push(Some(0));
9067        index_label.push(Label((existing + offset) as u32));
9068    }
9069    // Point each pre-allocated label at its instruction, reusing the count from
9070    // `original_to_kept` so the mapping survives compaction.
9071    let place_index_labels = |state: &mut FnState,
9072                              original_to_kept: &[Option<usize>],
9073                              kept_len: usize,
9074                              index_label: &[Label]| {
9075        for (original, mapped) in original_to_kept.iter().enumerate() {
9076            if let Some(kept_index) = mapped {
9077                let label = index_label[*kept_index].0 as usize;
9078                state.labels[label] = Some(original);
9079            }
9080        }
9081        state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
9082    };
9083    place_index_labels(state, &original_to_kept, base, &index_label);
9084
9085    // Resolve every label to a kept index once; the placement table maps labels
9086    // to original indices, so a second hop lands in kept space.
9087    let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
9088    for (id, placed) in state.labels.iter().enumerate() {
9089        let Some(original) = placed else { continue };
9090        label_kept[id] = if *original == usize::MAX {
9091            Some(base)
9092        } else {
9093            (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
9094        };
9095    }
9096
9097    // Code after an unconditional transfer is unreachable, and the reference drops it
9098    // as it walks past the transfer — the `skip_dead_code` in its first pass. It
9099    // scans forward until it finds a label something still jumps to, so a run of
9100    // dead instructions between a `throw` and the next live target disappears.
9101    //
9102    // The scan repeats because dropping a jump lowers the reference count of the
9103    // label it pointed at, which can strand what follows. Only a real label keeps an
9104    // instruction alive here; the per-instruction labels allocated above belong to
9105    // this pass, not to the program.
9106    loop {
9107        let mut references = vec![false; kept.len() + 1];
9108        for (_, operands) in &kept {
9109            if let Some(target) = target_kept_index(operands, &label_kept)
9110                && target < references.len()
9111            {
9112                references[target] = true;
9113            }
9114        }
9115        let mut doomed = vec![false; kept.len()];
9116        let mut any = false;
9117        for (index, (op, _)) in kept.iter().enumerate() {
9118            if !is_transfer(*op) {
9119                continue;
9120            }
9121            for next in index + 1..kept.len() {
9122                if references[next] {
9123                    break;
9124                }
9125                doomed[next] = true;
9126                any = true;
9127            }
9128        }
9129        if !any {
9130            break;
9131        }
9132        (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
9133    }
9134
9135    // A label that lands on an unconditional jump stands for wherever that jump
9136    // goes, so retarget it once and every jump to the label follows for free.
9137    // This is what makes `continue` in a `for` head reach the loop top instead of
9138    // stopping at the update's trailing jump.
9139    let folded: Vec<Option<usize>> = label_kept
9140        .iter()
9141        .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
9142        .collect();
9143    label_kept = folded;
9144
9145    // Jump cleanup, in compacted index space. Two rewrites the reference also
9146    // applies while it resolves labels:
9147    //   * a jump whose destination is the very next instruction does nothing;
9148    //   * a jump to a jump is redirected to its final destination.
9149    // The second can expose the first, so this repeats until it settles.
9150    loop {
9151        let mut delete = vec![false; kept.len()];
9152        let mut changed = false;
9153        for index in 0..kept.len() {
9154            let (op, operands) = &kept[index];
9155            if !is_goto(*op) {
9156                continue;
9157            }
9158            let Some(immediate) = target_kept_index(operands, &label_kept) else {
9159                continue;
9160            };
9161            let target = follow_jump_chain(&kept, &label_kept, immediate);
9162            if target == index + 1 {
9163                delete[index] = true;
9164                changed = true;
9165            } else if matches!(
9166                kept.get(target).map(|(op, _)| *op),
9167                Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
9168            ) {
9169                // Jumping straight to a return or throw is the same as doing it
9170                // here, so the jump becomes that instruction.
9171                kept[index] = (kept[target].0, Vec::new());
9172                changed = true;
9173            } else if target != immediate {
9174                // Redirect to the end of the chain.
9175                let label = index_label[target];
9176                kept[index].1 = vec![Op::Label(label)];
9177                changed = true;
9178            }
9179        }
9180        if !changed {
9181            break;
9182        }
9183        if !delete.iter().any(|deleted| *deleted) {
9184            break;
9185        }
9186        // Drop the deleted instructions and renumber everything.
9187        let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9188        let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9189        let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9190        for (old, entry) in kept.into_iter().enumerate() {
9191            if delete[old] {
9192                continue;
9193            }
9194            moved[old] = Some(next.len());
9195            next.push(entry);
9196            next_spans.push(spans[old]);
9197        }
9198        for (id, slot) in label_kept.iter_mut().enumerate() {
9199            let Some(old) = *slot else { continue };
9200            *slot = match moved.get(old).copied().flatten() {
9201                Some(new) => Some(new),
9202                // The target was deleted: the jump now lands on whatever follows.
9203                None => (old..moved.len())
9204                    .find_map(|i| moved[i])
9205                    .or(Some(next.len())),
9206            };
9207            let _ = id;
9208        }
9209        kept = next;
9210        spans = next_spans;
9211    }
9212
9213    // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
9214    // jump to the next instruction and is deleted, leaving the label at the end with
9215    // nothing pointing at it. If that also strands the last instruction, it goes
9216    // too — which is how a `try` whose body always returns ends on its `ret` rather
9217    // than an implicit `return_undef`.
9218    // Which instructions something still jumps to. Reading the surviving jumps is
9219    // what the reference's reference counts amount to: once a jump has been folded
9220    // away the label it named is unreferenced, even though the program still has a
9221    // label there.
9222    let mut references = vec![false; kept.len() + 1];
9223    let _ = real_labels;
9224    for (_, operands) in &kept {
9225        if let Some(target) = target_kept_index(operands, &label_kept)
9226            && target < references.len()
9227        {
9228            references[target] = true;
9229        }
9230    }
9231    let mut end = kept.len();
9232    while end > 0 {
9233        let last = end - 1;
9234        let reachable = references[last] || end < kept.len();
9235        if reachable {
9236            break;
9237        }
9238        let after_transfer = last
9239            .checked_sub(1)
9240            .map(|previous| {
9241                matches!(
9242                    kept[previous].0,
9243                    Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
9244                )
9245            })
9246            .unwrap_or(false);
9247        if !after_transfer {
9248            break;
9249        }
9250        end = last;
9251    }
9252    kept.truncate(end);
9253    spans.truncate(end);
9254
9255    // Choose an opcode for each instruction and its size, so label offsets can be
9256    // computed.
9257    let chosen = choose_opcodes(&kept, &label_kept);
9258    let offsets = instruction_offsets(&chosen);
9259    let offset = *offsets.last().unwrap_or(&0);
9260
9261    let mut code = Vec::with_capacity(offset);
9262    for (position, (_, operands)) in kept.iter().enumerate() {
9263        let op = chosen[position];
9264        code.push(op as u8);
9265        let operands = retarget_labels(operands, &label_kept, kept.len());
9266        encode_operands(&mut code, op, &operands, offsets[position], &offsets);
9267    }
9268    let stack_size = compute_stack_size(&code);
9269    // Keep only the offsets where the position actually changes: a run of
9270    // instructions on one line is one table entry, and the runtime binary searches
9271    // the table for the frame's pc.
9272    //
9273    // The table always starts at pc 0 with the *function's own* position, because the
9274    // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
9275    // last_line_num)` from `fd->source_pos`, the token the function definition starts at
9276    // (`function`, `async`, a method's property name). An instruction before the first
9277    // recorded operator therefore reports the function's own start, which is what makes a
9278    // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
9279    let mut positions: Vec<LineCol> = vec![LineCol {
9280        pc: 0,
9281        line: state.line,
9282        column: state.column,
9283    }];
9284    let mut last: Option<Position> = None;
9285    for (index, span) in spans.iter().enumerate() {
9286        let Some(pos) = *span else { continue };
9287        if last == Some(pos) {
9288            continue;
9289        }
9290        last = Some(pos);
9291        if pos.line == state.line && pos.column == state.column {
9292            // Already the seed entry above.
9293            continue;
9294        }
9295        positions.push(LineCol {
9296            pc: offsets[index] as u32,
9297            line: pos.line,
9298            column: pos.column,
9299        });
9300    }
9301    (code, stack_size, positions)
9302}
9303
9304/// Whether an instruction always transfers control away, so anything after it in the
9305/// same stream is unreachable.
9306fn is_transfer(op: Opcode) -> bool {
9307    matches!(
9308        op,
9309        Opcode::Goto
9310            | Opcode::Goto8
9311            | Opcode::Goto16
9312            | Opcode::Return
9313            | Opcode::ReturnUndef
9314            | Opcode::Throw
9315            | Opcode::ThrowError
9316            | Opcode::Ret
9317    )
9318}
9319
9320/// Remove the marked instructions and renumber the label table so it keeps pointing
9321/// at the same instructions. A label whose instruction went away moves to whatever
9322/// follows it, since a jump is never left with nowhere to land.
9323fn drop_instructions(
9324    kept: Vec<(Opcode, Vec<Op>)>,
9325    spans: Vec<Option<Position>>,
9326    label_kept: &mut [Option<usize>],
9327    doomed: &[bool],
9328) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
9329    let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9330    let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9331    let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9332    for (old, entry) in kept.into_iter().enumerate() {
9333        if doomed.get(old).copied().unwrap_or(false) {
9334            continue;
9335        }
9336        moved[old] = Some(result.len());
9337        result.push(entry);
9338        result_spans.push(spans[old]);
9339    }
9340    for slot in label_kept.iter_mut() {
9341        let Some(old) = *slot else { continue };
9342        *slot = match moved.get(old).copied().flatten() {
9343            Some(new) => Some(new),
9344            None => (old..moved.len())
9345                .find_map(|i| moved[i])
9346                .or(Some(result.len())),
9347        };
9348    }
9349    (result, result_spans)
9350}
9351
9352fn is_goto(op: Opcode) -> bool {
9353    matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
9354}
9355
9356/// The kept index a jump operand points at.
9357fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
9358    let id = label_id(operands)?;
9359    label_kept.get(id as usize).copied().flatten()
9360}
9361
9362/// Follow a chain of unconditional jumps to its first real destination.
9363fn follow_jump_chain(
9364    kept: &[(Opcode, Vec<Op>)],
9365    label_kept: &[Option<usize>],
9366    start: usize,
9367) -> usize {
9368    let mut current = start;
9369    // `for(;;)` jumps to itself, so the walk has to be bounded.
9370    for _ in 0..kept.len() {
9371        let Some((op, operands)) = kept.get(current) else {
9372            return current;
9373        };
9374        if !is_goto(*op) {
9375            return current;
9376        }
9377        let Some(next) = target_kept_index(operands, label_kept) else {
9378            return current;
9379        };
9380        if next == current {
9381            return current;
9382        }
9383        current = next;
9384    }
9385    current
9386}
9387
9388/// Rewrite label operands from label ids to kept instruction indices.
9389fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
9390    operands
9391        .iter()
9392        .map(|operand| match operand {
9393            Op::Label(label) => {
9394                let target = label_kept
9395                    .get(label.0 as usize)
9396                    .copied()
9397                    .flatten()
9398                    .unwrap_or(kept_len);
9399                Op::Label(Label(target as u32))
9400            }
9401            other => other.clone(),
9402        })
9403        .collect()
9404}
9405
9406/// Encode the resolved instruction stream, choosing short forms where possible.
9407///
9408/// Compute the maximum value-stack depth by exploring the control-flow graph.
9409///
9410/// This is a breadth-first walk from the first instruction, tracking the stack
9411/// depth on entry to each instruction. Every instruction has at most two
9412/// successors (fall through, and a jump target), so a worklist over byte offsets
9413/// is enough. The reference does the same thing in `compute_stack_size`, which is
9414/// why the resulting numbers match exactly.
9415///
9416/// Instructions that pop a variable number of values (`call`, `array_from`, …)
9417/// encode that count in their operand, which is added to the static `n_pop`.
9418fn compute_stack_size(code: &[u8]) -> u32 {
9419    let mut depth_at = vec![u16::MAX; code.len()];
9420    // Each entry carries the enclosing `catch` levels, innermost last, because
9421    // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
9422    // offset and forgets that level.
9423    let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
9424    let mut max_depth = 0u32;
9425
9426    while let Some((pc, depth, catch_levels)) = worklist.pop() {
9427        if pc >= code.len() {
9428            continue;
9429        }
9430        if depth_at[pc] != u16::MAX {
9431            continue;
9432        }
9433        force_depth(&mut depth_at, pc, depth);
9434
9435        let Some(op) = Opcode::from_u8(code[pc]) else {
9436            break;
9437        };
9438        let info = op.info();
9439        let next = pc + info.size as usize;
9440        if next > code.len() {
9441            break;
9442        }
9443        let mut n_pop = info.n_pop as u32;
9444        let mut n_push = info.n_push as u32;
9445        // Variable-length forms carry their count in the operand.
9446        match info.format {
9447            crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
9448                n_pop += read_u16(code, pc + 1) as u32;
9449            }
9450            crate::opcode::OpFormat::Npopx => {
9451                n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
9452            }
9453            _ => {}
9454        }
9455        // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
9456        // are the `set_` variant; the table already records that, so nothing to
9457        // adjust here.
9458        let _ = &mut n_push;
9459
9460        // The depth before this instruction's own push, which is what a `catch`
9461        // records as its level.
9462        let depth_before = depth;
9463        let mut depth = depth.saturating_sub(n_pop) + n_push;
9464        let mut catch_levels = catch_levels;
9465        if op == Opcode::NipCatch {
9466            // Discard everything above the innermost catch offset, keeping the value
9467            // on top: the frame the code after this sees is the same shape it would
9468            // have had if the `try` were not there.
9469            if let Some(base) = catch_levels.pop() {
9470                depth = base + 1;
9471            }
9472        }
9473        max_depth = max_depth.max(depth);
9474
9475        // Successors.
9476        let target = jump_target_of(code, pc, op);
9477        match op {
9478            Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9479                if let Some(target) = target {
9480                    worklist.push((target, depth, catch_levels));
9481                }
9482            }
9483            Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
9484                if let Some(target) = target {
9485                    worklist.push((target, depth, catch_levels.clone()));
9486                }
9487                worklist.push((next, depth, catch_levels));
9488            }
9489            // A `catch` records an exception edge to the handler. The handler is
9490            // entered with the thrown value on top of the stack, in the slot the
9491            // catch offset occupies on the normal path — which is why the handler's
9492            // first instruction can `put_loc` the exception away, and why the depth
9493            // is the same on both paths.
9494            Opcode::Catch => {
9495                if let Some(target) = target {
9496                    // The handler is protected by the *enclosing* catch, not by this
9497                    // one: an error raised inside it is what the handler's own
9498                    // `catch` catches.
9499                    worklist.push((target, depth, catch_levels.clone()));
9500                }
9501                catch_levels.push(depth_before);
9502                worklist.push((next, depth, catch_levels));
9503            }
9504            // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
9505            // rewind past it too. Its level sits one slot higher than a `catch`'s:
9506            // the iterator and next-method slots occupy the offset's place.
9507            Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
9508                if let Some(target) = target {
9509                    worklist.push((target, depth, catch_levels.clone()));
9510                }
9511                catch_levels.push(depth_before + 1);
9512                worklist.push((next, depth, catch_levels));
9513            }
9514            // `gosub` calls a subroutine with the return address on top. The opcode
9515            // table records no push for it — `ret` is what pops the slot — so the
9516            // extra one is added here, where the depth of the subroutine's first
9517            // instruction is being computed.
9518            Opcode::Gosub => {
9519                if let Some(target) = target {
9520                    worklist.push((target, depth + 1, catch_levels.clone()));
9521                }
9522                worklist.push((next, depth, catch_levels));
9523            }
9524            // `ret` goes back to a `gosub`; nothing here follows it.
9525            Opcode::Ret
9526            | Opcode::Return
9527            | Opcode::ReturnUndef
9528            | Opcode::Throw
9529            | Opcode::ThrowError => {}
9530            _ => worklist.push((next, depth, catch_levels)),
9531        }
9532    }
9533    max_depth
9534}
9535
9536/// Record the stack depth on entry to `pc`, keeping the deeper value if the
9537/// instruction is reachable more than once.
9538fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
9539    let clamped = depth.min(u16::MAX as u32 - 1) as u16;
9540    if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
9541        depth_at[pc] = clamped;
9542    }
9543}
9544
9545fn read_u16(code: &[u8], at: usize) -> u16 {
9546    let mut value = 0u16;
9547    for i in 0..2 {
9548        value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
9549    }
9550    value
9551}
9552
9553/// The absolute target of a jump instruction, if it has one.
9554fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
9555    let info = op.info();
9556    let position = pc + 1;
9557    match info.format {
9558        crate::opcode::OpFormat::Label8 => {
9559            let offset = *code.get(position)? as i8 as i64;
9560            Some((position as i64 + offset) as usize)
9561        }
9562        crate::opcode::OpFormat::Label16 => {
9563            let offset = read_u16(code, position) as i16 as i64;
9564            Some((position as i64 + offset) as usize)
9565        }
9566        crate::opcode::OpFormat::Label => {
9567            let mut offset = 0i32;
9568            for i in 0..4 {
9569                offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
9570            }
9571            Some((position as i64 + offset as i64) as usize)
9572        }
9573        _ => None,
9574    }
9575}
9576
9577fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
9578    use Opcode::*;
9579    match (op, operands.first()) {
9580        (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
9581            op.short_form(*value as u32).unwrap_or(op)
9582        }
9583        (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
9584        (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
9585        (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
9586        | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
9587        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
9588        // A declared global is reached through its reference cell, so it shares
9589        // the `var_ref` encodings, short forms included.
9590        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
9591            op.short_form(*index).unwrap_or(op)
9592        }
9593        (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
9594            op.short_form(*count as u32).unwrap_or(op)
9595        }
9596        _ => op,
9597    }
9598}
9599
9600/// The byte offset each instruction will start at, plus the total code size.
9601fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
9602    let mut offsets = Vec::with_capacity(chosen.len() + 1);
9603    let mut offset = 0usize;
9604    for op in chosen {
9605        offsets.push(offset);
9606        offset += op.size() as usize;
9607    }
9608    offsets.push(offset);
9609    offsets
9610}
9611
9612/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
9613/// the offset actually fits.
9614///
9615/// The choice is circular: an instruction's size decides the offsets of everything after
9616/// it, and the offsets decide whether a jump may be short. So this starts with every jump
9617/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
9618/// Shrinking only ever *shortens* distances, so the loop converges.
9619///
9620/// Doing it in one pass instead — which is what this used to do — silently truncated any
9621/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
9622/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
9623/// with four closures in its body simply stopped, with no error and no output past the
9624/// first iteration.
9625fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
9626    let mut chosen: Vec<Opcode> = kept
9627        .iter()
9628        .map(|(op, operands)| choose_short_form(*op, operands))
9629        .collect();
9630    // A jump the compiler emitted in its widest form, and the forms it may shrink to.
9631    let candidates = |op: Opcode| match op {
9632        Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
9633        Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
9634        Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
9635        _ => None,
9636    };
9637    loop {
9638        let offsets = instruction_offsets(&chosen);
9639        let mut changed = false;
9640        for index in 0..kept.len() {
9641            let (op, operands) = &kept[index];
9642            let Some((short, medium, has_medium)) = candidates(*op) else {
9643                continue;
9644            };
9645            if chosen[index] == short {
9646                continue;
9647            }
9648            let Some(target) = target_kept_index(operands, label_kept) else {
9649                continue;
9650            };
9651            let Some(&target_offset) = offsets.get(target) else {
9652                continue;
9653            };
9654            // A jump is relative to the byte after its opcode, which is the convention
9655            // `jump_target_of` decodes with.
9656            let relative = target_offset as i64 - (offsets[index] as i64 + 1);
9657            if (-128..=127).contains(&relative) {
9658                chosen[index] = short;
9659                changed = true;
9660            } else if has_medium
9661                && chosen[index] == Opcode::Goto
9662                && (-32_768..=32_767).contains(&relative)
9663            {
9664                // Too far for 8 bits and close enough for 16. Only `goto` has a medium
9665                // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
9666                // the reference encodes them.
9667                chosen[index] = medium;
9668                changed = true;
9669            }
9670        }
9671        if !changed {
9672            return chosen;
9673        }
9674    }
9675}
9676
9677fn encode_operands(
9678    code: &mut Vec<u8>,
9679    op: Opcode,
9680    operands: &[Op],
9681    position: usize,
9682    offsets: &[usize],
9683) {
9684    use crate::opcode::OpFormat::*;
9685    let info = op.info();
9686    let write_slot = |code: &mut Vec<u8>, slot: Slot| {
9687        let index = match slot {
9688            Slot::Arg(i)
9689            | Slot::Loc(i)
9690            | Slot::VarRef(i)
9691            | Slot::Global(i)
9692            | Slot::GlobalDecl(i) => i,
9693        };
9694        code.extend_from_slice(&(index as u16).to_be_bytes());
9695    };
9696    match info.format {
9697        None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
9698        U8 | Const8 => {
9699            if let Some(value) = operands.first().and_then(operand_uint) {
9700                code.push(value as u8);
9701            }
9702        }
9703        // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
9704        // like their wide counterparts, only one byte wide.
9705        Loc8 => {
9706            if let Some(Op::Slot(slot)) = operands.first() {
9707                let index = match slot {
9708                    Slot::Arg(i)
9709                    | Slot::Loc(i)
9710                    | Slot::VarRef(i)
9711                    | Slot::Global(i)
9712                    | Slot::GlobalDecl(i) => *i,
9713                };
9714                code.push(index as u8);
9715            }
9716        }
9717        I8 => {
9718            if let Some(value) = operands.first().and_then(operand_int) {
9719                code.push(value as i8 as u8);
9720            }
9721        }
9722        U16 | Npop => {
9723            if let Some(value) = operands.first().and_then(operand_int) {
9724                code.extend_from_slice(&(value as u16).to_be_bytes());
9725            }
9726        }
9727        I16 => {
9728            if let Some(value) = operands.first().and_then(operand_int) {
9729                code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
9730            }
9731        }
9732        I32 => {
9733            if let Some(value) = operands.first().and_then(operand_int) {
9734                code.extend_from_slice(&value.to_be_bytes());
9735            }
9736        }
9737        U32 | Const => {
9738            if let Some(value) = operands.first().and_then(operand_uint) {
9739                code.extend_from_slice(&value.to_be_bytes());
9740            }
9741        }
9742        Loc | Arg | VarRef => {
9743            if let Some(Op::Slot(slot)) = operands.first() {
9744                write_slot(code, *slot);
9745            }
9746        }
9747        Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
9748            if let Some(Op::AtomId(index)) = operands.first() {
9749                code.extend_from_slice(&index.to_be_bytes());
9750            }
9751            // The trailing immediate means different things per format, and the
9752            // atom forms that carry a *label* have to resolve it like any other
9753            // jump, so they cannot share the `U8`/`U16` arms above.
9754            match info.format {
9755                AtomU8 | AtomLabelU8 => {
9756                    if let Some(value) = operands.get(1).and_then(operand_uint) {
9757                        code.push(value as u8);
9758                    }
9759                }
9760                AtomU16 | AtomLabelU16 => {
9761                    if let Some(value) = operands.get(1).and_then(operand_uint) {
9762                        code.extend_from_slice(&(value as u16).to_be_bytes());
9763                    }
9764                }
9765                _ => {}
9766            }
9767        }
9768        NpopU16 => {
9769            for operand in operands.iter().take(2) {
9770                if let Some(value) = operand_uint(operand) {
9771                    code.extend_from_slice(&(value as u16).to_be_bytes());
9772                }
9773            }
9774        }
9775        Label | Label8 | Label16 | LabelU16 => {
9776            if let Some(Op::Label(label)) = operands.first() {
9777                // Labels were already remapped to kept-instruction indices.
9778                let Some(&target) = offsets.get(label.0 as usize) else {
9779                    debug_assert!(false, "label {} is past the end", label.0);
9780                    return;
9781                };
9782                let relative = target as i64 - (position as i64 + 1);
9783                match info.format {
9784                    Label8 => code.push(relative as i8 as u8),
9785                    Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
9786                    // `label_u16` stores the target followed by an unrelated u16.
9787                    LabelU16 => {
9788                        code.extend_from_slice(&(relative as i32).to_be_bytes());
9789                        if let Some(value) = operands.get(1).and_then(operand_uint) {
9790                            code.extend_from_slice(&(value as u16).to_be_bytes());
9791                        }
9792                    }
9793                    _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
9794                }
9795            }
9796        }
9797    }
9798}
9799
9800fn operand_int(op: &Op) -> Option<i32> {
9801    match op {
9802        Op::Int(value) => Some(*value),
9803        _ => None,
9804    }
9805}
9806
9807fn operand_uint(op: &Op) -> Option<u32> {
9808    match op {
9809        Op::Const(value) | Op::AtomId(value) => Some(*value),
9810        Op::Int(value) => Some(*value as u32),
9811        _ => None,
9812    }
9813}
9814
9815/// Disassemble a compiled function.
9816pub fn disassemble(function: &CompiledFunction) -> String {
9817    disasm::disassemble_program(function)
9818}