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, EvalPrivate, EvalPrivateKind,
27    EvalSite, EvalVisible, ExportEntry, Function as CompiledFunction, FunctionKind, ImportEntry,
28    ModuleMeta, ModuleRequest, VarDef, VarKind,
29};
30use crate::disasm;
31use crate::opcode::Opcode;
32use js_parse::Position;
33use js_parse::Span;
34use js_parse::SyntaxError;
35use js_parse::Wtf8;
36use js_parse::ast::{self, *};
37
38/// A label id, local to the function being compiled.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub struct Label(u32);
41
42/// The name of the hidden local that carries a function's `[[HomeObject]]` for `super`.
43///
44/// The reference calls the variable `home_object` and prints it as `"<home_object>"`, which
45/// is why the brackets are part of the name; nothing a program writes can collide with it.
46const HOME_OBJECT: &str = "<home_object>";
47
48/// The local holding the function `super()` constructs from.
49///
50/// The reference's `JS_ATOM_this_active_func`. Unlike `<home_object>` this one is printed
51/// with its dots, because that is the atom's text: its dump shows `1: var this.active_func`.
52const ACTIVE_FUNC: &str = "this.active_func";
53
54/// The local holding `new.target`, likewise spelled the way the reference's dump shows it.
55const NEW_TARGET: &str = "new.target";
56
57/// Stand-in for a constant-pool index that is only known later in the instruction stream.
58///
59/// One user: the class constructor's `fclosure`, whose slot the reference assigns after the
60/// members have taken theirs. `u32::MAX` is not a reachable pool index — a class with four
61/// billion members is not a thing — and the compiler patches it before resolution runs, so a
62/// missed patch is a panic-free compiler error rather than a wrong jump.
63const CTOR_INDEX_PLACEHOLDER: u32 = u32::MAX;
64
65/// One step of a class's initialisation, in source order.
66///
67/// A static block is not a member the class keeps — it is a run of statements that executes
68/// at the point the class definition reaches it — so it belongs *inside* the initialiser
69/// function rather than alongside the fields as a separate pass. Merging the two is what
70/// makes `static a = 1; static {}` and `static {}; static a = 1` order-sensitive in the
71/// same way the reference is.
72enum StaticInitItem<'a> {
73    /// `static x = value`, or `x = value` for the instance half.
74    Field(FieldKey<'a>, Option<&'a Expr>),
75    /// `static { … }`
76    Block {
77        body: &'a [Stmt],
78        /// Position of the `{`, which is where the reference puts the function.
79        body_start: Position,
80    },
81}
82
83/// The next template-site identity, process-wide.
84///
85/// A counter rather than something derived from the unit: two compilation units that both
86/// number their sites from zero would collide in the realm's registry, and a collision
87/// there is observable — it would hand the *same* template object to two unrelated sites.
88fn next_template_site() -> u32 {
89    static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
90    NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
91}
92
93/// How one field names its property.
94///
95/// A computed key is *not* re-evaluated per instance: the reference evaluates it once at
96/// class definition and stores it in a `<computed_field>N` binding, because the key of a field
97/// is fixed when the class is created. Keeping the expression here instead made
98/// `class C { [k] = 1 }` re-read `k` on every `new`, which is a different program when `k`
99/// changes — and worse, the operand order was wrong, so `class C { ["a"] = 1 }` produced
100/// `{1: "a"}`.
101enum FieldKey<'a> {
102    /// `x`, `"x"`, `0` — the property name is static text.
103    Literal(&'a PropKey),
104    /// `#x`: the class-scope binding that holds the private symbol.
105    Private(String),
106    /// `[expr]`: the class-scope binding that holds the evaluated key.
107    Computed(String),
108}
109
110/// The `var_block` sentinel for a binding that lives at function scope.
111///
112/// It has to be a value a *real* block key can never take. Block keys are source
113/// offsets, so `0` is a perfectly ordinary key — the first block statement of a file
114/// gets it — and using `0` as the sentinel made `{ let y = 2 }` at offset zero look
115/// like a function-scoped `var`, which is how a top-level block's `let` leaked out of
116/// its block. The body block already uses `u64::MAX` to stay clear of offsets, so the
117/// sentinel takes the slot below it.
118const FUNCTION_SCOPE: u64 = u64::MAX - 3;
119
120/// The `var_block` sentinel for a binding of the parameter list.
121///
122/// A function whose parameter list contains a default expression gets *two* variable
123/// environments: one for the parameters and one for the body, so a `var` in the body
124/// that shares a name with a parameter is a different binding. The parameter bindings
125/// therefore need a scope key of their own: reachable while the defaults are
126/// evaluated, invisible to the body, and never merged with a body `var` of the same
127/// name.
128///
129/// Without this, `function f(a = 1, p = () => a) { var a = 2 }` made `p()` return 2:
130/// the closure and the body shared one slot, when only the parameters were in scope
131/// when it was created.
132const PARAM_SCOPE: u64 = u64::MAX - 4;
133
134/// The name of the hidden local a `using` declaration caches its dispose method in.
135///
136/// It has to be a name no source can produce, because a script may declare anything: the
137/// angle brackets keep it out of the identifier grammar, exactly like `<ret>`.
138fn using_method_name(name: &str) -> String {
139    format!("<using.method {name}>")
140}
141
142/// The `blocks` parent sentinel for "this block has no enclosing block".
143///
144/// Same reasoning as [`FUNCTION_SCOPE`]: `0` is a legal block key, and when it was
145/// also the terminator the chain walk from the script body reached the file's
146/// offset-zero block and treated it as an *enclosing* block — so that block's `let`
147/// leaked into the body scope.
148const NO_PARENT: u64 = u64::MAX - 2;
149
150/// The block key for a script body. Distinct from both sentinels and unreachable from
151/// any source offset.
152const SCRIPT_BODY: u64 = u64::MAX - 1;
153
154/// An operand of a symbolic instruction.
155#[derive(Debug, Clone, PartialEq)]
156enum Op {
157    /// An immediate integer.
158    Int(i32),
159    /// A jump target.
160    Label(Label),
161    /// A constant pool index.
162    Const(u32),
163    /// An atom, before interning.
164    Atom(Atom),
165    /// An interned atom, as an index into [`Function::atoms`].
166    AtomId(u32),
167    /// A resolved slot.
168    Slot(Slot),
169}
170
171/// Where a resolved variable lives.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173enum Slot {
174    Arg(u32),
175    Loc(u32),
176    VarRef(u32),
177    /// A global, by closure-var index.
178    Global(u32),
179    /// A global *declared* in this script. The reference keeps these bindings in
180    /// reference cells so that the script and any closure share one variable, so
181    /// a store goes through `put_var_ref` while a read uses `get_var`.
182    GlobalDecl(u32),
183}
184
185/// What a symbolic variable access does, which decides the final opcode.
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187enum VarAction {
188    /// Read the value.
189    Get,
190    /// Read the value, yielding `undefined` for an undeclared global.
191    GetUndef,
192    /// Write, leaving nothing on the stack.
193    Put,
194    /// Write and initialise, leaving the value on the stack.
195    PutInit,
196    /// Write, leaving the value on the stack.
197    Set,
198    /// Initialise a binding that may only be initialised once, such as a derived
199    /// constructor's `this`.
200    PutInitChecked,
201    /// Initialise, leaving the value on the stack and without the `const` check.
202    ///
203    /// A class's own scope binding is a `const` that has to be initialised in the middle
204    /// of the definition — after the constructor exists but before the static fields run
205    /// — and the value has to survive for the outer store to use.
206    SetInit,
207    /// Write a binding that lives in a reference cell.
208    PutRef,
209}
210
211#[derive(Debug, Clone)]
212enum Insn {
213    /// A fully determined instruction.
214    Fixed { op: Opcode, operands: Vec<Op> },
215    /// A variable access, resolved in the second pass.
216    ///
217    /// `block` is the lexical block the access appears in, which is what makes
218    /// shadowing work: two bindings can share a name, and the one that wins is
219    /// whichever scope encloses the access.
220    Var {
221        action: VarAction,
222        name: String,
223        block: u64,
224        /// Whether the access was written in the parameter list; see
225        /// [`FnState::in_params`].
226        in_params: bool,
227    },
228    /// Close a binding *if* it turned out to be captured.
229    ///
230    /// Whether a `for (let i ...)` loop variable needs a fresh per-iteration cell is
231    /// only known once the body has been compiled — a closure created there is the
232    /// thing that makes it necessary. The reference emits `close_loc` exactly in that
233    /// case and nothing otherwise, so the decision is deferred to [`resolve`] instead
234    /// of emitted blind.
235    CloseCaptured { name: String, block: u64 },
236    /// `delete name`, which can only answer `false` once the binding is known.
237    ///
238    /// It is not a `Var` action because `delete_var` carries an *atom*: the runtime
239    /// looks the name up on the global object, which is what distinguishes an implicit
240    /// global (configurable, deletable) from a declared one (a binding, always `false`).
241    DeleteVar { name: String },
242    /// An instruction that dead-code elimination removed. It keeps its slot so
243    /// that label indices stay valid, and resolves to no bytecode.
244    Dead,
245}
246
247/// Where `break` and `continue` jump to.
248///
249/// Targets are stacked as the compiler enters loops and labelled statements, so a
250/// bare `break` needs no analysis: it is simply the innermost target. A labelled
251/// one searches outward by name.
252#[derive(Debug, Clone)]
253struct JumpTarget {
254    /// The labels attached to this target. `l: for(;;)` gives one name; a bare
255    /// loop gives none; `a: b: for(;;)` gives two, because both labels name the
256    /// same statement and `break a` must reach the same place as `break b`.
257    names: Vec<String>,
258    /// Where `break` lands. `None` for a construct `break` may only leave, not
259    /// target — a `try`, whose entry exists purely to unwind.
260    break_label: Option<Label>,
261    /// Where `continue` lands. `None` for anything that is not a loop.
262    continue_label: Option<Label>,
263    /// Stack slots to discard when control leaves this construct by a jump.
264    ///
265    /// Both `switch` and `try` leave something on the value stack for the duration
266    /// of the construct — the discriminant, or the `catch` offset — and a jump out
267    /// has to take it with it. A loop leaves nothing.
268    drop_count: u32,
269    /// The finalizer to run when control leaves this construct.
270    ///
271    /// Set on a `try` even when it has no `finally`: the label is always emitted and
272    /// the empty-subroutine removal cleans up afterwards, so the code that unwinds
273    /// does not have to know whether a finalizer exists.
274    finally_label: Option<Label>,
275    /// Whether this is a labelled non-loop statement, which an unlabelled `break`
276    /// does not reach.
277    is_regular_stmt: bool,
278    /// Whether leaving this construct has to close an iterator.
279    ///
280    /// A `for`/`of` loop keeps an iterator on the value stack, and leaving early has
281    /// to run its `return` method. `for`/`in` keeps only an enumeration object, which
282    /// is dropped rather than closed.
283    has_iterator: bool,
284    /// Whether that iterator speaks the *async* protocol.
285    ///
286    /// An async close has to `await` the inner `return`, so it is an inline instruction
287    /// sequence rather than one opcode — the reference's `emit_iterator_close`.
288    is_async_iterator: bool,
289}
290
291/// Whether a named property read should be `get_field2` rather than `dup; get_field`.
292///
293/// Both leave `source value` on the stack, so this is purely which spelling the reference
294/// picked, and it picked it by whether it had to build a *reference* for the target:
295///
296/// * a target that is itself a pattern starts by boxing the value, so the copy is what it
297///   consumes — `get_field2` (and a default does not change that: `{a: {b} = {}}` still
298///   destructures);
299/// * a `let`/`const` binding needs no reference, so the reference takes the short form;
300/// * a `var`, and any assignment target, go through `dup; get_field`, because the
301///   reference builds a reference for them — which is what `with` needs.
302fn reads_with_get_field2(decl: Option<VarDeclKind>, value: &Pattern) -> bool {
303    nests_a_pattern(value) || matches!(decl, Some(VarDeclKind::Let) | Some(VarDeclKind::Const))
304}
305
306/// Whether binding this pattern starts by boxing the value it was handed.
307fn nests_a_pattern(pattern: &Pattern) -> bool {
308    match &pattern.kind {
309        PatternKind::Array { .. } | PatternKind::Object { .. } => true,
310        PatternKind::Assign { target, .. } => nests_a_pattern(target),
311        _ => false,
312    }
313}
314
315/// `copy_data_properties` flags for an object-literal spread.
316///
317/// The byte packs three fields: the low bits are the stack offset of the source,
318/// the next three the offset of the exclusion list, and bit 2 asks for symbol keys
319/// as well as string keys. A spread passes a literal `null` exclusion list right
320/// below the source, so that field stays zero and only the source offset and the
321/// symbol bit are set — hence `{...v}` copies symbols, which the flag name says.
322const COPY_ALL_PROPERTIES: i32 = 2 | (1 << 2);
323
324/// The expression a `...` introduces.
325///
326/// The parser marks the spread in two places — the element/property variant and an
327/// [`ExprKind::Spread`] wrapper around the argument — so the wrapper has to be
328/// stepped through before the argument can be compiled.
329fn spread_argument(spread: &Expr) -> &Expr {
330    match &spread.kind {
331        ExprKind::Spread(inner) => inner,
332        _ => spread,
333    }
334}
335
336/// The flag byte `define_method` takes.
337///
338/// The low two bits pick value/getter/setter; bit 2 marks the property
339/// enumerable, which every object-literal method is.
340/// What kind of class constructor a function is being compiled as.
341///
342/// A constructor is not an ordinary method: a base one materialises `this` and refuses
343/// to run without `new`, and a derived one starts with `this` in the dead zone until
344/// `super()` produces it.
345#[derive(Debug, Clone, Copy, PartialEq, Eq)]
346enum CtorKind {
347    /// Not a class constructor.
348    None,
349    /// A constructor of a class without `extends`.
350    Base,
351    /// A constructor of a class with `extends`.
352    Derived,
353}
354
355/// The flag byte `define_method` takes for a class member.
356///
357/// The low two bits pick value/getter/setter; bit 2 marks the property enumerable, which
358/// a class method is *not* — that is the whole difference from an object-literal method,
359/// and the reason `Object.keys(C.prototype)` stays empty.
360fn class_method_flags(kind: MethodKind) -> i32 {
361    match kind {
362        MethodKind::Constructor | MethodKind::Method => 0,
363        MethodKind::Get => 1,
364        MethodKind::Set => 2,
365    }
366}
367
368fn define_method_flags(kind: PropertyKind) -> i32 {
369    let base = match kind {
370        PropertyKind::Value | PropertyKind::Method => 0,
371        PropertyKind::Get => 1,
372        PropertyKind::Set => 2,
373    };
374    base | 4
375}
376
377/// Convert a numeric property key to the text an atom would be made from.
378///
379/// `PropertyKey` of a number is `ToString(number)`, the same conversion every other place
380/// uses — so this goes through [`crate::number::number_to_string`] rather than formatting
381/// the value here. It used to accept only `[1e-6, 1e21)` and reject the rest, on the
382/// theory that Rust's `{}` and JavaScript's spelling diverge at the extremes; they do, and
383/// that is exactly why the spec's own algorithm is the thing to call. `get 0.0000001() {}`
384/// binds the key `"1e-7"`, and the rejection made it a `SyntaxError` instead.
385///
386/// The `Result` is kept because the call sites are in a `?` chain, and a key conversion
387/// that could still fail (a non-finite value from a source literal, which the lexer does
388/// not produce) belongs on the same path as the rest of a property name's errors.
389fn numeric_key_text(value: f64, _span: Span) -> Result<String, SyntaxError> {
390    Ok(crate::number::number_to_string(value))
391}
392
393/// Collect the operands of a same-operator logical run, in source order.
394///
395/// Recurses down the left spine only: `((a || b) || c)` contributes `a`, `b`, then
396/// the caller appends `c`. A node with a different operator is one operand.
397fn collect_same_operator<'a>(op: LogicalOp, expr: &'a Expr, out: &mut Vec<&'a Expr>) {
398    if let ExprKind::Logical {
399        op: inner_op,
400        left,
401        right,
402    } = &expr.kind
403        && *inner_op == op
404    {
405        collect_same_operator(op, left, out);
406        out.push(right);
407        return;
408    }
409    out.push(expr);
410}
411
412/// The jump a logical assignment or `??` takes when the value is kept.
413///
414/// `||` and `&&` branch on truthiness, so the same opcode serves both the operator
415/// and `??` once [`Compiler::emit_logical_test`] has pushed a boolean. `??` keeps
416/// the value when it is *not* null-ish, so it is the `if_false` side.
417fn logical_jump(op: AssignOp) -> Opcode {
418    match op {
419        AssignOp::Or => Opcode::IfTrue,
420        AssignOp::And | AssignOp::Coalesce => Opcode::IfFalse,
421        _ => Opcode::IfFalse,
422    }
423}
424
425/// Whether a loop enumerates keys or values.
426#[derive(Debug, Clone, Copy, PartialEq, Eq)]
427enum ForLoopKind {
428    /// `for (x in o)` — the keys of an object.
429    In,
430    /// `for (x of o)` — the values of an iterable.
431    Of,
432    /// `for await (x of o)` — the values of an async iterable, or of a sync one.
433    AwaitOf,
434}
435
436/// Which part of a `try` statement a block key refers to.
437#[derive(Debug, Clone, Copy)]
438enum TryPart {
439    /// The guarded block.
440    Block = 0,
441    /// The handler body, excluding the catch parameter.
442    Catch = 1,
443    /// The finalizer block.
444    Finally = 2,
445    /// The catch parameter's own scope.
446    Param = 3,
447}
448
449/// A lexical scope, identified while hoisting and numbered at the end.
450///
451/// Scope identity is needed in two passes that must agree: declarations are
452/// hoisted in source order (so slots come out in source order, as in the
453/// reference), but a binding belongs to the block it was written in, which is only
454/// entered later. Blocks are therefore keyed by the source position of their
455/// opening brace, which is stable across both walks.
456#[derive(Debug, Clone, Copy)]
457struct Block {
458    /// Source position of the block.
459    key: u64,
460    /// The block this one is nested in; `0` for the function scope.
461    parent: u64,
462}
463
464/// One function under construction.
465struct FnState {
466    /// The function's own source range, used to record its text for
467    /// `Function.prototype.toString`.
468    span: Option<(usize, usize)>,
469    name: String,
470    kind: FunctionKind,
471    strict: bool,
472    args: Vec<VarDef>,
473    vars: Vec<VarDef>,
474    closure_vars: Vec<ClosureVar>,
475    cpool: Vec<Constant>,
476    atoms: Vec<Atom>,
477    /// Every lexical scope, in creation order.
478    blocks: Vec<Block>,
479    /// The block currently being parsed or compiled.
480    current_block: u64,
481    /// The block a *nested* function was created in, so a capture made from here can be
482    /// resolved against the enclosing function's lexical scopes rather than against a
483    /// flat name table. Without it, `function f(){ class S{} }` capturing `S` found the
484    /// function's own `let S` instead of the class body's `const S`.
485    created_in_block: u64,
486    /// The block each local was declared in, parallel to `vars`. `0` means the
487    /// function scope, where `var` bindings live.
488    var_block: Vec<u64>,
489    /// Set when the expression just compiled left no value on the stack.
490    ///
491    /// Only a store can do that: `put_field` consumes the object and the value, so
492    /// an assignment whose result is unused emits nothing extra. The expression
493    /// statement then has nothing to drop.
494    no_value: bool,
495    /// Whether a label was placed since the last instruction was emitted.
496    ///
497    /// The `put`/`get` fold is only valid when the two are adjacent in the final
498    /// stream; a label in between means a jump can land on the read, so the store has
499    /// to keep consuming its value. A flag is enough and avoids having to reason about
500    /// which index a label recorded.
501    label_since_insn: bool,
502    /// Whether the value of the expression being compiled is thrown away.
503    ///
504    /// Only an expression *statement* discards its value, and only the outermost
505    /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
506    /// still has to produce a value. Consumed by [`Compiler::assign`], which is
507    /// the one construct whose bytecode depends on it.
508    discard_value: bool,
509    /// The block that holds the function body.
510    body_block: u64,
511    /// Head of each scope's binding chain, indexed by level. Filled in by
512    /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
513    block_heads: Vec<i32>,
514    /// Enclosing `break`/`continue` targets, innermost last.
515    jump_targets: Vec<JumpTarget>,
516    insns: Vec<Insn>,
517    labels: Vec<Option<usize>>,
518    /// Captured locals, which need a reference cell.
519    var_ref_count: u32,
520    line: u32,
521    column: u32,
522    /// Whether this is a script body. A script's top-level declarations create
523    /// global properties rather than locals, which is why they show up as
524    /// closure variables with `[global_decl]`.
525    is_script: bool,
526    /// Whether this is a module body.
527    ///
528    /// A module body is a script in every respect that matters here — no `arguments`,
529    /// no `this` of its own — but its top-level declarations are *module*-scoped
530    /// instead of global, which is what this flag changes.
531    is_module: bool,
532    /// Whether the function is an arrow, which never gets its own `arguments`.
533    is_arrow: bool,
534    /// The name a *named function expression* binds inside its own body.
535    /// How many parameters count towards `.length`.
536    defined_args: u32,
537    /// Parameters that are not a plain name, with the argument slot each came from.
538    param_prologue: Vec<(usize, Pattern)>,
539    /// What kind of class constructor this function is, if any.
540    ctor_kind: CtorKind,
541    /// Whether the class has instance fields, so the constructor has to run their
542    /// initialiser before it returns.
543    /// What the nested function about to be compiled should be told about its class.
544    class_ctor_pending: Option<CtorKind>,
545    /// Whether this function needs the hidden `this` local, because an arrow inside it
546    /// refers to `this`.
547    ///
548    /// An arrow has no `this` of its own, so the reference materialises the enclosing
549    /// function's receiver into a local and lets the arrow capture it as an ordinary
550    /// closure variable. Declaring the local is not enough on its own: the store that
551    /// fills it has to be prepended to the body, which is what this flag arranges.
552    needs_this_local: bool,
553    /// The same, for `arguments`.
554    needs_arguments_local: bool,
555    /// The same, for `new.target`.
556    needs_new_target_local: bool,
557    /// Whether the body already opens by filling a `this` local, which
558    /// [`Compiler::begin_this_local`] does for a constructor and a field initialiser.
559    has_this_prologue: bool,
560    /// The same, for `<home_object>`: the object `super` resolves against.
561    ///
562    /// An arrow and a static block have no home object of their own — only the method or
563    /// initialiser they were written in does — so `super.x` inside one is a read of the
564    /// enclosing function's `[[HomeObject]]`. The value is materialised into a local there
565    /// by `special_object 4`, the same way `this` is.
566    needs_home_object_local: bool,
567    /// Whether this function has an `arguments` binding of its own.
568    ///
569    /// False for a class field initialiser and a static block: §15.7 puts them outside any
570    /// function, so `arguments` does not exist there and `eval('arguments')` inside one is a
571    /// `SyntaxError` rather than the caller's arguments object. The parser already enforces
572    /// that for written code; this carries the same fact to the `eval` call site, which has
573    /// to compile the eval'd source under the caller's restriction.
574    no_arguments_binding: bool,
575    /// The same, for `this.active_func`: the function `super()` constructs from.
576    ///
577    /// An arrow has no `super` of its own, so it reads the enclosing function's — and that
578    /// is a *lexical* relationship, not a stack one. The reference keeps `this_active_func`
579    /// as a local of the enclosing function; an arrow that escaped the constructor
580    /// (`iter.return = () => super()`) then finds it in its closure even with the
581    /// constructor nowhere on the call stack.
582    needs_active_func_local: bool,
583    /// Hidden locals of the `with` blocks currently open, innermost last.
584    with_names: Vec<String>,
585    /// How many of [`FnState::with_names`] were already open when this function was
586    /// created, i.e. belong to an *enclosing* function.
587    ///
588    /// The distinction decides shadowing, and it is positional rather than lexical. A
589    /// `with` opened **inside** this function's body sits nearer than the function's own
590    /// environment, so it shadows even a `var` of this function:
591    /// `function f(){ with(o){ var v = 1 } }` writes `o.v`. A `with` opened **outside**
592    /// does not: `with(o){ function f(){ var v = 1 } }` writes `f`'s local `v`, because
593    /// `f`'s environment is the inner one. Treating both alike broke one family or the
594    /// other — `S12.10_A1.2` and `S12.10_A1.7` are these two cases.
595    inherited_with_names: usize,
596    /// Set while a with-guard is being emitted, so the guard's own accesses are not
597    /// wrapped in another guard.
598    emitting_with_guard: bool,
599    self_name: Option<String>,
600    /// Where the function body starts, in source order; see [`Function::body_start`].
601    body_start: (u32, u32),
602    /// Whether the body contains a *direct* `eval(...)` call.
603    ///
604    /// A direct eval sees every binding of the function that called it, including ones
605    /// no other code mentions. It also hands those bindings to any closure it creates,
606    /// which can outlive the function. Both need the bindings to live in cells, so this
607    /// flag makes the function treat all of them as captured.
608    has_direct_eval: bool,
609    /// Whether the parameter list contains a default expression, which is what gives
610    /// the function a second variable environment (see [`PARAM_SCOPE`]).
611    has_parameter_expressions: bool,
612    /// `IsSimpleParameterList`: every parameter is a plain binding identifier.
613    simple_parameter_list: bool,
614    /// Whether the instructions being emitted belong to the parameter list.
615    ///
616    /// References made here must not see the body's `var`s: the body has not run yet,
617    /// and the reference's own model keeps the two scopes apart.
618    in_params: bool,
619    /// Whether an arrow created in this function's parameter list needs the parameter
620    /// scope's `arguments` binding.
621    needs_param_arguments: bool,
622    /// Whether this function was *created* inside a parameter list.
623    ///
624    /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
625    /// arrow too. The name reference is the arrow's, but the scope it must not see
626    /// belongs to the function the arrow was born in.
627    created_in_params: bool,
628    /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
629    ///
630    /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
631    /// final while the body is still being compiled: a named function expression declares
632    /// its own name binding *after* the body, and that binding is exactly what
633    /// `eval("myfunc = 1")` has to find.
634    eval_sites: Vec<EvalSite>,
635    /// Direct `eval` call sites seen so far: where, and the block that was current.
636    pending_eval_sites: Vec<(Span, u64, bool, Vec<EvalPrivate>, bool)>,
637    /// Whether this body contains `await`.
638    ///
639    /// For a *module* this decides whether its body is an async function: top-level
640    /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
641    /// to survive to the compiled function rather than being a local of the compiler.
642    has_await: bool,
643    /// The module tables, when this body is a module.
644    ///
645    /// Only the top-level state ever has one: `export` and `import` are top-level
646    /// statements, so nothing nested can add to these tables.
647    module: Option<ModuleMeta>,
648    /// Whether the self-name prologue (`special_object 2` then the store) has been
649    /// emitted for this function.
650    ///
651    /// A *nested* function's lookup declares the binding early (see
652    /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
653    /// prologue is still needed — the binding existing is not the same as it being
654    /// initialised.
655    self_name_initialized: bool,
656    /// Whether the code emitted so far leaves the program's result on the stack.
657    /// The reference tracks this for the hidden `<ret>` local of an eval script.
658    leaves_value: bool,
659    /// Statement nesting depth, used to tell top-level statements apart.
660    stmt_depth: u32,
661    /// Function declarations waiting to be instantiated at scope entry, as
662    /// (target slot, constant pool index). The reference emits these from
663    /// `instantiate_hoisted_definitions` rather than at the statement, because a
664    /// declaration is visible before it is reached.
665    hoisted: Vec<(u64, HoistTarget, u32)>,
666    /// Function declarations whose bodies are compiled only once the enclosing scope
667    /// has finished hoisting, as (owning block, declaration).
668    ///
669    /// Compiling a body at the declaration makes the result depend on source order: in
670    /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
671    /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
672    /// names first and the bodies second is what removes that dependence.
673    deferred_funcs: Vec<(u64, Box<ast::Function>)>,
674    /// The source position of the node being compiled. Every instruction emitted
675    /// takes it, which is how the position table that feeds stack traces is built.
676    cur_pos: Option<Position>,
677    /// One position per entry in `insns`, index-aligned.
678    insn_pos: Vec<Option<Position>>,
679}
680
681/// Where a hoisted function declaration is stored.
682#[derive(Debug, Clone)]
683enum HoistTarget {
684    Arg(u32),
685    Loc(u32),
686    /// A global, which the resolver looks up by name.
687    Global(String),
688}
689
690impl FnState {
691    /// Whether this function suspends: a generator or an async function.
692    ///
693    /// A suspending function's `return` is a `return_async` and its body starts with an
694    /// `initial_yield`, so almost every statement that touches control flow asks this.
695    fn is_suspending(&self) -> bool {
696        self.kind.is_generator() || self.kind.is_async()
697    }
698
699    fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
700        FnState {
701            span: None,
702            name: name.into(),
703            kind,
704            strict: false,
705            args: Vec::new(),
706            vars: Vec::new(),
707            closure_vars: Vec::new(),
708            cpool: Vec::new(),
709            atoms: Vec::new(),
710            blocks: Vec::new(),
711            current_block: 0,
712            created_in_block: NO_PARENT,
713            var_block: Vec::new(),
714            no_value: false,
715            label_since_insn: false,
716            discard_value: false,
717            body_block: 0,
718            block_heads: Vec::new(),
719            jump_targets: Vec::new(),
720            insns: Vec::new(),
721            labels: Vec::new(),
722            var_ref_count: 0,
723            line: 1,
724            column: 1,
725            is_script: false,
726            is_module: false,
727            is_arrow: false,
728            defined_args: 0,
729            param_prologue: Vec::new(),
730            ctor_kind: CtorKind::None,
731            class_ctor_pending: None,
732            needs_this_local: false,
733            needs_arguments_local: false,
734            needs_new_target_local: false,
735            has_this_prologue: false,
736            needs_home_object_local: false,
737            no_arguments_binding: false,
738            needs_active_func_local: false,
739            with_names: Vec::new(),
740            inherited_with_names: 0,
741            emitting_with_guard: false,
742            self_name: None,
743            has_direct_eval: false,
744            body_start: (0, 0),
745            has_parameter_expressions: false,
746            simple_parameter_list: true,
747            in_params: false,
748            needs_param_arguments: false,
749            created_in_params: false,
750            eval_sites: Vec::new(),
751            pending_eval_sites: Vec::new(),
752            has_await: false,
753            module: None,
754            self_name_initialized: false,
755            leaves_value: false,
756            stmt_depth: 0,
757            hoisted: Vec::new(),
758            deferred_funcs: Vec::new(),
759            cur_pos: None,
760            insn_pos: Vec::new(),
761        }
762    }
763
764    /// The scope a declaration lands in: a script's top-level declarations are
765    /// globals, everything else gets a slot.
766    /// Whether a binding declared *now* becomes a property of the global object.
767    ///
768    /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
769    /// The `var` case is decided by the keyword rather than by the cursor position:
770    /// `var` is function-scoped, so a `var i` in a `for` head is still the same
771    /// binding as a `var i` in the body, even though the head has its own block.
772    fn declares_globally(&self, def: &VarDef) -> bool {
773        // A module's top-level declarations are *module*-scoped: they live in the module
774        // record, never on the global object. Two modules can both declare `var x`
775        // without seeing each other, which is the whole point.
776        if self.is_module {
777            return false;
778        }
779        self.is_script && (!def.is_lexical || self.current_block == self.body_block)
780    }
781}
782
783/// The compiler's entry point.
784pub struct Compiler {
785    /// The text being compiled, kept so each function can record its own slice for
786    /// `Function.prototype.toString`.
787    source: Option<String>,
788    module: bool,
789    /// Whether the program itself is the body of an `async` function.
790    ///
791    /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
792    /// completion value is wrapped so a returned promise is not adopted.
793    async_body: bool,
794    /// Enclosing functions, outermost first. The last entry is the current one.
795    stack: Vec<FnState>,
796    /// The private names visible at this point, innermost class body last.
797    ///
798    /// A stack rather than a field of `FnState` because a private name is *lexically* scoped
799    /// to the class body: a method, an arrow inside it and a class nested inside that arrow
800    /// all resolve against the same entries, and the parser accepts exactly that set
801    /// (`self.private` in `parser.rs`). `FnState` is per-function, so it would lose the outer
802    /// class's names the moment a method started.
803    private_scopes: Vec<std::collections::HashMap<String, PrivateUse>>,
804    /// Whether the expression [`Compiler::expr`] is about to compile is the one its
805    /// statement asked to discard.
806    ///
807    /// `FnState::discard_value` says "the statement's value is thrown away", which is only
808    /// ever true of the statement's own expression — an assignment nested inside it, as in
809    /// `f(x = 1)`, has a value that is very much used. Clearing the flag on the way in and
810    /// keeping the answer here is what tells the two apart; without it the nested store
811    /// consumed its value, `call` took the callee as its argument, and `f(x = 1)` inside a
812    /// function threw `undefined is not a function`.
813    discard_root: bool,
814}
815
816/// How a use site of a private name compiles.
817///
818/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
819/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
820/// of a setter-only accessor pair.
821#[derive(Clone, Copy, PartialEq, Eq)]
822enum PrivateKind {
823    /// `#x = 1`: an own property keyed by the symbol in the binding.
824    Field,
825    /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
826    Method,
827    /// `get #a() {}`: the binding holds the getter, and a read calls it.
828    Getter,
829    /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
830    /// the same `TypeError` as reading an uninitialised `const`.
831    Setter,
832}
833
834/// What the compiler knows about one `#name` where it is used.
835#[derive(Clone)]
836struct PrivateUse {
837    kind: PrivateKind,
838    /// `#a<set>` when the class defines a setter for this name.
839    ///
840    /// A second binding, not a second field of the first: the reference stores the setter
841    /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
842    setter: Option<String>,
843}
844
845/// The class-scope bindings one class body needs, in declaration order.
846#[derive(Default)]
847struct ClassPlan {
848    /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
849    /// at class entry, in member order.
850    bindings: Vec<String>,
851    /// The private names, for the use sites inside the body.
852    uses: std::collections::HashMap<String, PrivateUse>,
853    /// Computed field keys, by element index, so the emission pass does not have to redo the
854    /// per-half counter that names them.
855    computed: std::collections::HashMap<usize, String>,
856    /// Whether the instance initialiser has to add the brand to `this`.
857    instance_brand: bool,
858    /// Whether the constructor itself has to carry the brand.
859    static_brand: bool,
860}
861
862impl ClassPlan {
863    /// Walk a class body once and decide every class-scope binding it needs.
864    ///
865    /// Order is the reference's: a member's binding is created when the member is parsed, so
866    /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
867    /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
868    /// the disassembly stops matching even when every instruction is right.
869    fn build(class: &Class) -> ClassPlan {
870        let mut plan = ClassPlan::default();
871        let mut instance_keys = 0usize;
872        let mut static_keys = 0usize;
873        for (index, element) in class.elements.iter().enumerate() {
874            match element {
875                ClassElement::Method {
876                    key: PropName::Private(ident),
877                    kind,
878                    is_static,
879                    ..
880                } => {
881                    let name = format!("#{}", ident.name);
882                    let first = !plan.uses.contains_key(&name);
883                    if first {
884                        plan.bindings.push(name.clone());
885                        plan.uses.insert(
886                            name.clone(),
887                            PrivateUse {
888                                kind: match kind {
889                                    MethodKind::Get => PrivateKind::Getter,
890                                    MethodKind::Set => PrivateKind::Setter,
891                                    _ => PrivateKind::Method,
892                                },
893                                setter: None,
894                            },
895                        );
896                    }
897                    match kind {
898                        MethodKind::Set => {
899                            let binding = format!("{name}<set>");
900                            plan.bindings.push(binding.clone());
901                            if let Some(use_) = plan.uses.get_mut(&name) {
902                                use_.setter = Some(binding);
903                            }
904                        }
905                        // A getter is what makes the name readable, so a pair that started
906                        // as a setter becomes readable once the getter arrives.
907                        MethodKind::Get => {
908                            if let Some(use_) = plan.uses.get_mut(&name) {
909                                use_.kind = PrivateKind::Getter;
910                            }
911                        }
912                        _ => {}
913                    }
914                    if *is_static {
915                        plan.static_brand = true;
916                    } else {
917                        plan.instance_brand = true;
918                    }
919                }
920                ClassElement::Method {
921                    key: PropName::Computed(_),
922                    ..
923                } => {}
924                ClassElement::Method { .. } => {}
925                ClassElement::Field {
926                    key: PropName::Private(ident),
927                    ..
928                } => {
929                    let name = format!("#{}", ident.name);
930                    if !plan.uses.contains_key(&name) {
931                        plan.bindings.push(name.clone());
932                        plan.uses.insert(
933                            name,
934                            PrivateUse {
935                                kind: PrivateKind::Field,
936                                setter: None,
937                            },
938                        );
939                    }
940                }
941                ClassElement::Field {
942                    key: PropName::Computed(_),
943                    is_static,
944                    ..
945                } => {
946                    let index_in_half = if *is_static {
947                        static_keys += 1;
948                        static_keys - 1
949                    } else {
950                        instance_keys += 1;
951                        instance_keys - 1
952                    };
953                    let binding = computed_field_binding(index_in_half, *is_static);
954                    plan.bindings.push(binding.clone());
955                    plan.computed.insert(index, binding);
956                }
957                ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
958            }
959        }
960        plan
961    }
962
963    /// How a private name used inside the body compiles, or `None` if no enclosing class
964    /// declares it.
965    fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
966        compiler
967            .private_scopes
968            .iter()
969            .rev()
970            .find_map(|scope| scope.get(name))
971    }
972}
973
974impl Compiler {
975    /// The exact source text of a function, for `Function.prototype.toString`.
976    ///
977    /// §20.2.3.5 requires the *original* text: a function must stringify back to what
978    /// was written, comments and odd spacing included. Slicing the recorded span out of
979    /// the whole source is the only way to get that — rebuilding it from the AST would
980    /// normalise the text, and answering `[native code]` for a script function (which is
981    /// what this engine used to do) makes the result useless for feature detection and
982    /// for libraries that read their own source.
983    ///
984    /// Top-level bodies have no single expression span, so their `source` stays `None`
985    /// and `toString` falls back to the calling convention the spec allows.
986    fn function_source(
987        &self,
988        span: Option<(usize, usize)>,
989        line: u32,
990        column: u32,
991    ) -> Option<String> {
992        let source = self.source.as_ref()?;
993        let span = span?;
994        let bytes = source.as_bytes();
995        let start = span.0;
996        let end = span.1;
997        if start >= bytes.len() || end > bytes.len() || start >= end {
998            let _ = (line, column);
999            return None;
1000        }
1001        Some(source.get(start..end)?.to_string())
1002    }
1003}
1004
1005/// Compile a script.
1006pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1007    Compiler::new(false).compile(program)
1008}
1009
1010/// Compile a script, keeping its text so `Function.prototype.toString` can answer with
1011/// the original source.
1012///
1013/// The separate entry point rather than a parameter on [`compile_script`] because the
1014/// tests and the disassembler compile from an AST they built themselves and have no
1015/// source to give; they keep the `None` behaviour they already relied on.
1016pub fn compile_script_with_source(
1017    program: &Program,
1018    source: &str,
1019) -> Result<CompiledFunction, SyntaxError> {
1020    let mut compiler = Compiler::new(false);
1021    compiler.source = Some(source.to_string());
1022    compiler.compile(program)
1023}
1024
1025/// [`compile_script_with_source`] for a module.
1026pub fn compile_module_with_source(
1027    program: &Program,
1028    source: &str,
1029) -> Result<CompiledFunction, SyntaxError> {
1030    let mut compiler = Compiler::new(true);
1031    compiler.source = Some(source.to_string());
1032    compiler.compile(program)
1033}
1034
1035/// Compile a script whose top level is the body of an `async` function.
1036/// The body is an ordinary script in every other way — it still reports a completion value
1037/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
1038/// it answers a promise instead of a value. The wrapper is what keeps that promise from
1039/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
1040/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
1041/// documents.
1042pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1043    Compiler::for_suspensible_script().compile(program)
1044}
1045
1046/// Compile a module.
1047pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1048    Compiler::new(true).compile(program)
1049}
1050
1051/// Compile a direct `eval` body that inherits private names from its caller.
1052///
1053/// `class C { #m = 44; f() { return eval("this.#m") } }` is legal — private names are
1054/// lexically scoped and the eval runs inside the caller's scope — but the names live in the
1055/// *call site's* compilation unit, so they have to be handed over. Seeding them as the
1056/// outermost private scope is what lets the eval resolve `#m` to the caller's binding: the
1057/// read compiles as an ordinary name lookup of `#m`, which at run time finds the caller's
1058/// slot through the same `eval`-scope machinery every other inherited name uses.
1059///
1060/// `suspensible` selects the `{async: true}` form (`std.evalScript(s, {async: true})`), whose
1061/// body may `await`.
1062pub fn compile_eval_with_private(
1063    program: &Program,
1064    private: &[EvalPrivate],
1065    suspensible: bool,
1066) -> Result<CompiledFunction, SyntaxError> {
1067    let mut compiler = if suspensible {
1068        Compiler::for_suspensible_script()
1069    } else {
1070        Compiler::new(false)
1071    };
1072    if !private.is_empty() {
1073        let scope: std::collections::HashMap<String, PrivateUse> = private
1074            .iter()
1075            .map(|entry| {
1076                (
1077                    entry.name.clone(),
1078                    PrivateUse {
1079                        kind: match entry.kind {
1080                            EvalPrivateKind::Field => PrivateKind::Field,
1081                            EvalPrivateKind::Method => PrivateKind::Method,
1082                            EvalPrivateKind::Getter => PrivateKind::Getter,
1083                            EvalPrivateKind::Setter => PrivateKind::Setter,
1084                        },
1085                        setter: entry.setter.clone(),
1086                    },
1087                )
1088            })
1089            .collect();
1090        compiler.private_scopes.push(scope);
1091    }
1092    compiler.compile(program)
1093}
1094
1095impl Compiler {
1096    /// Create a compiler.
1097    pub fn new(module: bool) -> Compiler {
1098        Compiler {
1099            source: None,
1100            module,
1101            async_body: false,
1102            stack: Vec::new(),
1103            private_scopes: Vec::new(),
1104            discard_root: false,
1105        }
1106    }
1107
1108    /// Create a compiler for a script whose top level is an `async` function body.
1109    fn for_suspensible_script() -> Compiler {
1110        Compiler {
1111            source: None,
1112            module: false,
1113            async_body: true,
1114            stack: Vec::new(),
1115            private_scopes: Vec::new(),
1116            discard_root: false,
1117        }
1118    }
1119
1120    /// Compile a whole program into its top-level function.
1121    pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
1122        let mut state = FnState::new("<eval>", FunctionKind::Normal);
1123        // A module body is *not* a script: it has no completion value, so no hidden
1124        // `<ret>` local and no `put_loc0` before each statement. What it shares with one
1125        // is having no `arguments` of its own and no receiver — see `is_module`.
1126        state.is_script = !self.module;
1127        state.is_module = self.module;
1128        if self.module {
1129            state.module = Some(ModuleMeta::default());
1130        }
1131        state.strict = program.strict || self.module;
1132        state.line = program.span.start.line;
1133        state.column = program.span.start.column;
1134        // Locals are numbered in declaration order; `<ret>` is always slot 0.
1135        //
1136        // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
1137        // slot that only appears in one of the two arrays shifts every later
1138        // binding's block and silently loses the temporal-dead-zone marking for
1139        // the script's own blocks. A function frame has no `<ret>`, which is why
1140        // the misalignment only showed up at the top level.
1141        if !self.module {
1142            state.vars.push(VarDef::var("<ret>"));
1143            state.var_block.push(FUNCTION_SCOPE);
1144        }
1145        self.stack.push(state);
1146        // The body is its own scope, keyed by the position of the program.
1147        // The script body needs a key no statement can produce. Statement keys are
1148        // source offsets, and the program's own start offset is `0` — which is also
1149        // the offset of the first statement, so a top-level `{ let x }` or
1150        // `for (let i …)` used to share the body's block and lose its scope.
1151        let body_key = SCRIPT_BODY;
1152        self.push_block(body_key, NO_PARENT);
1153        self.state().body_block = body_key;
1154        // A module body opens with a re-entry guard. The host evaluates a module exactly
1155        // once, so the guard never fires in practice — but the reference emits it, and a
1156        // module function called a second time (through `eval` of its own source, say)
1157        // must not run its body again.
1158        let module_guard = self.module.then(|| self.new_label());
1159        if let Some(body) = module_guard {
1160            // The guard wraps the *hoisting* too: a second evaluation of the same module
1161            // body must not even re-create its function declarations.
1162            self.emit(Opcode::PushThis, &[]);
1163            self.emit_jump(Opcode::IfFalse, body, &[]);
1164        }
1165        self.hoist(&program.body, body_key)?;
1166        // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
1167        // come before the guard's `return_undef`: the reference's jump target sits past
1168        // both, and a second evaluation therefore re-creates nothing.
1169        self.emit_scope_enter(body_key);
1170        if let Some(body) = module_guard {
1171            self.emit(Opcode::ReturnUndef, &[]);
1172            self.place_label(body);
1173        }
1174        // Through `stmts` rather than the loop, so a `using` region at the top level of an
1175        // eval'd body or a module gets its disposal epilogue like any other block.
1176        self.stmts(&program.body)?;
1177        if self.module {
1178            // A module has no completion value; its body simply ends.
1179            self.emit(Opcode::Undefined, &[]);
1180            self.emit(Opcode::ReturnAsync, &[]);
1181            // Top-level `await` makes the body an async function, so the host runs it as
1182            // a coroutine and waits. Without this the `await` opcode would suspend in a
1183            // body that nothing knows how to resume — which is what "a generator body ran
1184            // as an ordinary call" was reporting.
1185            if self.cur().has_await {
1186                self.state().kind = FunctionKind::Async;
1187            }
1188        } else if self.async_body {
1189            // An async body reports its completion value the same way, but through an
1190            // object: the function answers a promise, and resolving that promise *with*
1191            // the completion value would adopt a promise completion instead of reporting
1192            // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
1193            // resolve to `{value: <promise>}` rather than to `7`.
1194            //
1195            // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
1196            // value in an object so that promises can be safely returned").
1197            self.emit(Opcode::Object, &[]);
1198            self.emit(Opcode::Dup, &[]);
1199            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1200            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
1201            self.emit(Opcode::Return, &[]);
1202            self.state().kind = FunctionKind::Async;
1203        } else {
1204            // The program's value is whatever the last expression statement stored in
1205            // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
1206            // case into a single `set_loc0`.
1207            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1208            self.emit(Opcode::Return, &[]);
1209        }
1210        Ok(self.finish_current())
1211    }
1212
1213    // -- emitting ----------------------------------------------------------
1214
1215    fn state(&mut self) -> &mut FnState {
1216        self.stack.last_mut().expect("a function is being compiled")
1217    }
1218
1219    fn cur(&self) -> &FnState {
1220        self.stack.last().expect("a function is being compiled")
1221    }
1222
1223    fn emit(&mut self, op: Opcode, operands: &[Op]) {
1224        self.state().label_since_insn = false;
1225        let pos = self.cur().cur_pos;
1226        self.state().insns.push(Insn::Fixed {
1227            op,
1228            operands: operands.to_vec(),
1229        });
1230        self.state().insn_pos.push(pos);
1231    }
1232
1233    /// Reset the script's hidden return value to `undefined`.
1234    ///
1235    /// Called at the start of every statement that does not itself produce the
1236    /// program's value, which is how the reference keeps `if`/loop results from
1237    /// leaking into an eval result.
1238    fn reset_value(&mut self) {
1239        if !self.cur().is_script {
1240            return;
1241        }
1242        self.emit(Opcode::Undefined, &[]);
1243        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1244        self.state().leaves_value = false;
1245    }
1246
1247    /// Whether `name` is a local or argument slot rather than a global.
1248    fn is_slot(&self, name: &str) -> bool {
1249        self.cur().vars.iter().any(|v| v.name == name)
1250            || self.cur().args.iter().any(|a| a.name == name)
1251    }
1252
1253    /// `with (object) body`
1254    ///
1255    /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
1256    /// what makes the object reachable from a closure created inside the block, and it
1257    /// is also what lets an `eval` find it: the runtime collects the active `With`
1258    /// locals of every frame and resolves names against them before the realm.
1259    ///
1260    /// Inside the block every name reference is spelled as "look in the with objects
1261    /// first", innermost outwards, and falls through to the ordinary access. The test is
1262    /// `in`, which is `HasProperty` — the same question the spec's Object Environment
1263    /// Record asks.
1264    fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
1265        // `with (e) s` completes with `UpdateEmpty(s, undefined)` — an *empty* body still
1266        // produces `undefined`, it does not inherit the previous statement's value. So
1267        // `eval("1; with({}){}")` is `undefined` while `eval("1; with({}){2;}")` is `2`.
1268        // Without this the sticky `<ret>` local leaked the `1` through, the same way it
1269        // would for an `if` or a loop.
1270        self.reset_value();
1271        let name = self.next_with_name();
1272        // The object expression is evaluated *outside* the scope it introduces, so no
1273        // wrapper may be emitted for the names it mentions.
1274        let saved = std::mem::take(&mut self.state().with_names);
1275        self.expr(object)?;
1276        self.state().with_names = saved;
1277        self.emit(Opcode::ToObject, &[]);
1278        self.declare_hidden_local(&name, VarKind::With);
1279        // Pushed before the store so the store itself is not guarded by an *outer*
1280        // `with` — the object being stored is the new one, not something to look up.
1281        self.state().with_names.push(name.clone());
1282        self.emit_var(VarAction::Put, &name);
1283        let result = self.stmt(body);
1284        self.state().with_names.pop();
1285        result
1286    }
1287
1288    /// A hidden-local name for one `with` block, distinct from every enclosing one.
1289    fn next_with_name(&self) -> String {
1290        let depth = self.cur().with_names.len();
1291        if depth == 0 {
1292            "<with>".to_string()
1293        } else {
1294            format!("<with{depth}>")
1295        }
1296    }
1297
1298    /// Declare a hidden local that must stay a *local* even in a script.
1299    ///
1300    /// A script's `var` is a property of the global object, but the `with` object is not
1301    /// part of the source program's name space at all — it only exists for the compiler
1302    /// and the runtime — so it goes straight into the frame's slot list.
1303    fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
1304        let state = self.state();
1305        if state.vars.iter().any(|v| v.name == name) {
1306            return;
1307        }
1308        state.var_block.push(FUNCTION_SCOPE);
1309        state.vars.push(VarDef {
1310            kind,
1311            ..VarDef::var(name)
1312        });
1313    }
1314
1315    /// Emit a name access, guarded by every active `with` object.
1316    ///
1317    /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
1318    /// the read itself; the outer guards and the plain access are what the `if_false`
1319    /// jumps to, so the innermost object wins.
1320    fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
1321        let names = self.visible_with_names(name);
1322        let done = self.new_label();
1323        let mut starts = Vec::new();
1324        // Innermost object first: the last `with` opened is the one that shadows the
1325        // others, so its guard has to be the first chance to satisfy the name.
1326        for with_name in names.iter().rev() {
1327            let next = self.new_label();
1328            // `with_has_var` takes the object and carries the name as an atom. It is not
1329            // `in`: an Object Environment Record also consults `Symbol.unscopables`, so
1330            // `globalThis[Symbol.unscopables] = {v: true}` leaves `v` to the outer scope.
1331            self.emit_var(VarAction::Get, with_name);
1332            self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1333            self.emit_jump(Opcode::IfFalse, next, &[]);
1334            starts.push(next);
1335            // The operation is `with_get_var`/`with_put_var`, not a plain property access:
1336            // `GetBindingValue`/`SetMutableBinding` ask `HasProperty` **again** before
1337            // getting or setting. That second question is observable — a proxy's `has`
1338            // trap runs one more time (`get-binding-value-call-with-proxy-env` logs
1339            // `has, get unscopables, has, get`) and an `unscopables` getter that deletes
1340            // the property leaves a binding that has gone, which strict code must report
1341            // as a `ReferenceError` rather than write to.
1342            match action {
1343                // A store already has its value on the stack, and `with_put_var` takes the
1344                // pair in `put_field`'s order: object first, then the value.
1345                VarAction::Put | VarAction::PutInit => {
1346                    self.emit_var(VarAction::Get, with_name);
1347                    self.emit(Opcode::Swap, &[]);
1348                    self.emit(Opcode::WithPutVar, &[Op::Atom(Atom::from_text(name))]);
1349                }
1350                _ => {
1351                    self.emit_var(VarAction::Get, with_name);
1352                    self.emit(Opcode::WithGetVar, &[Op::Atom(Atom::from_text(name))]);
1353                }
1354            }
1355            self.emit_jump(Opcode::Goto, done, &[]);
1356            self.place_label(next);
1357        }
1358        self.emit_var(action, name);
1359        self.place_label(done);
1360    }
1361
1362    /// The `with` blocks that can shadow `name`, innermost last.
1363    ///
1364    /// A parameter or a local of this function is *inside* every `with` this function
1365    /// opened, so those shadow it; a `with` that was already open when this function was
1366    /// created is outside the function's own environment, so the local wins and that
1367    /// block is skipped. See [`FnState::inherited_with_names`].
1368    fn visible_with_names(&self, name: &str) -> Vec<String> {
1369        let state = self.cur();
1370        // The hidden `<with…>` locals are how the guard reaches its own objects, so they
1371        // must never be guarded themselves — not by their own block (which would recurse)
1372        // and not by an enclosing one (which would ask a `with` object whether it has a
1373        // property called `<with>`, always answer no, and waste the chain). Source can
1374        // never spell these names, so exempting all of them changes nothing else.
1375        if state.with_names.iter().any(|hidden| hidden == name) {
1376            return Vec::new();
1377        }
1378        let start = if self.is_slot(name) {
1379            state.inherited_with_names
1380        } else {
1381            0
1382        };
1383        state.with_names[start..]
1384            .iter()
1385            .filter(|hidden| hidden.as_str() != name)
1386            .cloned()
1387            .collect()
1388    }
1389
1390    /// Compile `x` as a **reference** to the with object's property, resolving the object
1391    /// once for the whole read-modify-write.
1392    ///
1393    /// `x += 1`, `x++` and `x ||= v` read and then write the same name. Two independent
1394    /// guards get that wrong the moment the read changes the answer: with
1395    /// `{ get x(){ delete this.x; return 2 } }`, `with (o) { x++ }` reads through the
1396    /// getter — which removes the property — and then the write's own guard no longer
1397    /// finds it, so the store landed on the *global* `x` and `o.x` stayed `undefined`. The
1398    /// reference resolves the base once (`with_make_ref`) and reuses it for both halves.
1399    ///
1400    /// The same shape comes out of compiling the name as a **member** of the with object:
1401    /// `get_field2`/`put_field` already evaluate their receiver once, and the hidden
1402    /// `<with>` local holds exactly the object the guard just tested. So each candidate
1403    /// object gets `if the name is bound here, compile as `this.name`; otherwise fall
1404    /// through to the next object`, and the last fallback is the ordinary name.
1405    fn with_reference(
1406        &mut self,
1407        name: &str,
1408        guarded: &mut dyn FnMut(&mut Self, &str) -> Result<(), SyntaxError>,
1409        plain: &mut dyn FnMut(&mut Self) -> Result<(), SyntaxError>,
1410    ) -> Result<(), SyntaxError> {
1411        let targets = self.visible_with_names(name);
1412        if targets.is_empty() {
1413            return plain(self);
1414        }
1415        let done = self.new_label();
1416        let result = self.with_reference_inner(name, &targets, guarded, plain, done);
1417        self.place_label(done);
1418        result
1419    }
1420
1421    fn with_reference_inner(
1422        &mut self,
1423        name: &str,
1424        targets: &[String],
1425        guarded: &mut dyn FnMut(&mut Self, &str) -> Result<(), SyntaxError>,
1426        plain: &mut dyn FnMut(&mut Self) -> Result<(), SyntaxError>,
1427        done: Label,
1428    ) -> Result<(), SyntaxError> {
1429        let Some((innermost, outer)) = targets.split_last() else {
1430            return plain(self);
1431        };
1432        let next = self.new_label();
1433        self.emit_var(VarAction::Get, innermost);
1434        self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1435        self.emit_jump(Opcode::IfFalse, next, &[]);
1436        guarded(self, innermost)?;
1437        self.emit_jump(Opcode::Goto, done, &[]);
1438        self.place_label(next);
1439        self.with_reference_inner(name, outer, guarded, plain, done)
1440    }
1441
1442    /// `delete name`, honouring any enclosing `with`.
1443    ///
1444    /// Inside a `with` the name may be a property of the with object, and then `delete`
1445    /// removes *that* property instead of touching the outer binding —
1446    /// `with (o) { delete p }` answers `true` and leaves `o` without `p` even when a
1447    /// global `p` exists. Left to the resolver it deleted the global instead, so the
1448    /// `statements/with/S12.10_A1.*` family then saw a `ReferenceError` on every later
1449    /// `p`.
1450    ///
1451    /// Emitted as a sequence here rather than during resolution because a resolution slot
1452    /// holds one instruction, and this is a loop over the with objects plus a fallback.
1453    fn delete_ident(&mut self, name: &str) {
1454        let names = self.cur().with_names.clone();
1455        let done = self.new_label();
1456        let mut starts = Vec::new();
1457        if !names.is_empty() {
1458            self.state().emitting_with_guard = true;
1459            // Innermost object first, like the read/write guard: the last `with` opened is
1460            // the one that shadows the others.
1461            for with_name in names.iter().rev() {
1462                let next = self.new_label();
1463                self.emit_var(VarAction::Get, with_name);
1464                self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1465                self.emit_jump(Opcode::IfFalse, next, &[]);
1466                // `delete` takes the receiver then the key.
1467                self.emit_var(VarAction::Get, with_name);
1468                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1469                self.emit(Opcode::Delete, &[]);
1470                self.emit_jump(Opcode::Goto, done, &[]);
1471                self.place_label(next);
1472                starts.push(next);
1473            }
1474            self.state().emitting_with_guard = false;
1475        }
1476        // The fallback: not a property of any with object, so the ordinary rule applies.
1477        let pos = self.cur().cur_pos;
1478        self.state().insns.push(Insn::DeleteVar {
1479            name: name.to_string(),
1480        });
1481        self.state().insn_pos.push(pos);
1482        if !names.is_empty() {
1483            self.place_label(done);
1484        }
1485    }
1486
1487    fn emit_var(&mut self, action: VarAction, name: &str) {
1488        // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
1489        // stores and keeps the value in one instruction. The reference does this
1490        // in a post-pass; folding it at emit time keeps instruction indices
1491        // stable, which matters because labels are recorded as indices.
1492        //
1493        // Only slots have a `set_` form: a global is stored with `put_var` and
1494        // read with `get_var`, and the reference does not fold those.
1495        //
1496        // A label between the two cancels the fold. `set_x v` leaves the value on
1497        // the stack, which is only equivalent when the read immediately follows the
1498        // store; when a jump target sits in between, the store must *consume* the
1499        // value and the read must fetch it afresh. A loop head is exactly that
1500        // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
1501        // condition re-reads it — and folding across the label would make the
1502        // condition compare whatever the previous iteration left on the stack.
1503        if action == VarAction::Get {
1504            let is_slot = self.is_slot(name);
1505            let at_label = std::mem::take(&mut self.state().label_since_insn);
1506            //
1507            // `arguments` is excluded because the reference treats it as a special
1508            // binding: it is initialised once and read many times, and folding its
1509            // initialisation into a `set_` would leave the object on the stack where
1510            // the reference leaves nothing.
1511            if is_slot
1512                && name != "arguments"
1513                && !at_label
1514                && let Some(Insn::Var {
1515                    action: previous,
1516                    name: previous_name,
1517                    ..
1518                }) = self.state().insns.last_mut()
1519                && *previous == VarAction::Put
1520                && previous_name == name
1521            {
1522                *previous = VarAction::Set;
1523                return;
1524            }
1525        }
1526        // Inside a `with`, every name lookup consults the with objects first. Two names
1527        // are exempt:
1528        //
1529        // * the hidden `<with…>` locals themselves, or the guard would recurse;
1530        // * a name this function **declares** — a parameter, a `var`, or a `let` of the
1531        //   current body. `with` sits *outside* the function's own environment, so a
1532        //   function declared inside a `with` still resolves its own bindings first:
1533        //   `with (o) { function f(){ var value = "x" } }` writes `f`'s local `value`, not
1534        //   `o.value`. Guarding it anyway wrote through to the with object whenever it
1535        //   happened to have the name, which is why
1536        //   `statements/with/S12.10_A1.7` saw `myObj.value` change. The runtime's
1537        //   `eval_binding_value` already models the same order.
1538        let guarded = !self.visible_with_names(name).is_empty()
1539            && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1540            && !self.state().emitting_with_guard;
1541        if guarded {
1542            self.state().emitting_with_guard = true;
1543            self.emit_with_guarded(action, name);
1544            self.state().emitting_with_guard = false;
1545            return;
1546        }
1547        let block = self.cur().current_block;
1548        self.state().label_since_insn = false;
1549        let pos = self.cur().cur_pos;
1550        let in_params = self.cur().in_params;
1551        self.state().insns.push(Insn::Var {
1552            action,
1553            name: name.to_string(),
1554            block,
1555            in_params,
1556        });
1557        self.state().insn_pos.push(pos);
1558    }
1559
1560    fn new_label(&mut self) -> Label {
1561        let state = self.state();
1562        state.labels.push(None);
1563        Label(state.labels.len() as u32 - 1)
1564    }
1565
1566    fn place_label(&mut self, label: Label) {
1567        let index = self.cur().insns.len();
1568        self.state().label_since_insn = true;
1569        self.state().labels[label.0 as usize] = Some(index);
1570    }
1571
1572    fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1573        let mut operands = vec![Op::Label(label)];
1574        operands.extend_from_slice(extra);
1575        self.emit(op, &operands);
1576    }
1577
1578    // -- scopes ------------------------------------------------------------
1579
1580    /// Start a new lexical scope inside `parent`.
1581    fn push_block(&mut self, key: u64, parent: u64) {
1582        let state = self.state();
1583        if !state.blocks.iter().any(|b| b.key == key) {
1584            state.blocks.push(Block { key, parent });
1585        }
1586        state.current_block = key;
1587    }
1588
1589    /// Emit the code that runs when a lexical scope is entered.
1590    ///
1591    /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1592    /// so entering its block marks it uninitialised. Hoisted function
1593    /// declarations are created here instead, which is why a call before the
1594    /// declaration still works.
1595    ///
1596    /// The order is not obvious: bindings are emitted in *reverse* declaration
1597    /// order, because the reference walks its scope chain, which is built by
1598    /// prepending.
1599    fn emit_scope_enter(&mut self, block: u64) {
1600        // Only *this* scope's hoisted declarations are consumed here; the rest stay in the
1601        // list for the scope that owns them. `std::mem::take` used to empty the whole list,
1602        // so entering an outer scope threw away every nested block's function
1603        // declarations: `function h(){ { function k(){} } return k; }` answered
1604        // `undefined`, and `{ function g(){} }` was `undefined` even *inside* the block.
1605        // That is one Annex B rule the engine otherwise implements (a sloppy-mode function
1606        // in a block is also a `var` of the enclosing function), and it is what makes the
1607        // `for (const ctor of ctors) { function f(){} … }` shape in test262 work.
1608        let mut hoisted = std::mem::take(&mut self.state().hoisted);
1609        let mut rest = Vec::with_capacity(hoisted.len());
1610        let mut mine: Vec<(HoistTarget, u32)> = Vec::new();
1611        for (owner, target, pool_index) in hoisted.drain(..) {
1612            if owner == block {
1613                mine.push((target, pool_index));
1614            } else {
1615                rest.push((owner, target, pool_index));
1616            }
1617        }
1618        self.state().hoisted = rest;
1619        mine.sort_by_key(|(target, _)| match target {
1620            HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1621            HoistTarget::Global(_) => u32::MAX,
1622        });
1623        for (target, pool_index) in mine {
1624            self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1625            match target {
1626                HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1627                HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1628                HoistTarget::Global(name) => {
1629                    // A global binding lives in a reference cell, so the store
1630                    // goes through `put_var_ref` while reads use `get_var`.
1631                    let block = self.cur().current_block;
1632                    let pos = self.cur().cur_pos;
1633                    let in_params = self.cur().in_params;
1634                    self.state().insns.push(Insn::Var {
1635                        action: VarAction::PutRef,
1636                        name,
1637                        block,
1638                        in_params,
1639                    });
1640                    self.state().insn_pos.push(pos);
1641                }
1642            }
1643        }
1644        for index in self.block_vars_reversed(block) {
1645            self.emit(
1646                Opcode::SetLocUninitialized,
1647                &[Op::Slot(Slot::Loc(index as u32))],
1648            );
1649        }
1650    }
1651
1652    /// Emit the code that runs when a lexical scope is exited.
1653    ///
1654    /// A captured binding has to be closed: detaching its reference cell freezes
1655    /// the value the binding had when the block ended, which is what a closure
1656    /// created inside the block must keep seeing.
1657    fn emit_scope_leave(&mut self, block: u64) {
1658        for index in self.block_vars_reversed(block) {
1659            if self.cur().vars[index].is_captured {
1660                self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1661            }
1662        }
1663    }
1664
1665    /// Locals declared in `block`, in reverse declaration order.
1666    fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1667        let state = self.cur();
1668        let mut out: Vec<usize> = (0..state.vars.len())
1669            .filter(|index| {
1670                state.var_block.get(*index).copied() == Some(block)
1671                    && state.vars[*index].is_lexical
1672                    // A derived constructor's `this` is lexical but is not initialised by
1673                    // entering the scope: `check_ctor` proves it, so its dead-zone marker
1674                    // was emitted with the constructor's own prologue.
1675                    && state.vars[*index].name != "this"
1676            })
1677            .collect();
1678        out.reverse();
1679        out
1680    }
1681
1682    /// Declare a local, even at the top level of a script.
1683    ///
1684    /// A `catch` parameter is always a local: the reference puts it in the
1685    /// function's own variable list (`1: catch e`), never in the global object,
1686    /// because it only exists while the handler runs.
1687    fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1688        let state = self.state();
1689        let index = state.vars.len() as u32;
1690        // A `catch` parameter belongs to a scope even though it is not lexical: the
1691        // runtime instantiates it per handler entry, but it never sits in the
1692        // temporal dead zone.
1693        let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1694            state.current_block
1695        } else {
1696            0
1697        };
1698        state.var_block.push(block);
1699        state.vars.push(def);
1700        index
1701    }
1702
1703    fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1704        if self.cur().is_module
1705            && self.cur().current_block == self.cur().body_block
1706            && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1707        {
1708            // Only the body's own block: a `let` inside a module-level `{}` is still an
1709            // ordinary local of that block, not a module variable.
1710            //
1711            // A `using` binding is excluded on purpose, and the reference excludes it in
1712            // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1713            // "'using' variables are currently not exported in modules"): a module-level
1714            // `using` is an ordinary *local* of the module body function, not a module
1715            // cell. Two things follow, and both are what the reference does — `export {a}`
1716            // of a `using` binding is "exported variable 'a' does not exist", and
1717            // disposal works, because the disposal epilogue addresses locals by slot.
1718            //
1719            // The hidden dispose-method variable is excluded for a stronger reason: it is
1720            // *always* a local (`add_scope_var` in the reference), and it must sit
1721            // immediately after its value so `using_dispose` can find it at `slot + 1`.
1722            return self.declare_module(name, &def);
1723        }
1724        if self.cur().declares_globally(&def) {
1725            self.declare_global(name, &def);
1726            return 0;
1727        }
1728        let state = self.state();
1729        let index = state.vars.len() as u32;
1730        let block = if def.is_lexical {
1731            state.current_block
1732        } else {
1733            0
1734        };
1735        state.var_block.push(block);
1736        state.vars.push(def);
1737        index
1738    }
1739
1740    /// Declare a `using` binding and its cached dispose method, returning both slots.
1741    ///
1742    /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1743    /// `(value, value + 1)` — the reference does the same and documents the constraint.
1744    fn declare_using(&mut self, name: &str) -> (u32, u32) {
1745        let mut def = VarDef::lexical(name);
1746        def.kind = VarKind::Using;
1747        // A `using` binding is immutable, exactly like a `const`: assigning to one is a
1748        // `TypeError` at run time, which is what `using-invalid-assignment-*-for` assert.
1749        // `VarDef::lexical` leaves `is_const` false, so the store would have landed.
1750        def.is_const = true;
1751        let value = self.declare(name, def);
1752        let mut method = VarDef::lexical(using_method_name(name));
1753        method.kind = VarKind::UsingMethod;
1754        let method_slot = self.declare(&using_method_name(name), method);
1755        (value, method_slot)
1756    }
1757
1758    /// The slot a `using` binding's dispose method lives in.
1759    fn using_method_slot(&self, name: &str) -> Option<u32> {
1760        let hidden = using_method_name(name);
1761        self.cur()
1762            .vars
1763            .iter()
1764            .position(|var| var.name == hidden)
1765            .map(|index| index as u32)
1766    }
1767
1768    // -- statements --------------------------------------------------------
1769
1770    fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1771        self.stmt_labelled(stmt, &[])
1772    }
1773
1774    /// Compile a statement that a chain of labels names.
1775    ///
1776    /// Only a loop consumes `labels`; every other statement ignores them (the
1777    /// parser has already rejected a label on a statement that cannot use it).
1778    fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1779        // Only a *top-level* expression statement supplies the program's value.
1780        let saved = self.cur().leaves_value;
1781        self.state().leaves_value =
1782            matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1783        self.state().stmt_depth += 1;
1784        let result = self.stmt_inner(stmt, labels);
1785        self.state().stmt_depth -= 1;
1786        // A nested statement never contributes the program's value, so the flag
1787        // the wrapper set above is what survives.
1788        let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1789        self.state().leaves_value = produced;
1790        let _ = saved;
1791        result
1792    }
1793
1794    fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1795        match &stmt.kind {
1796            StmtKind::Empty | StmtKind::Debugger => {}
1797            StmtKind::Expr(expr) => {
1798                // The statement's first token is a position the reference records: an
1799                // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1800                // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1801                // is why an error from a construct with no position of its own (`[...it]`
1802                // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1803                let saved = self.cur().cur_pos;
1804                self.state().cur_pos = Some(expr.span.start);
1805                // An expression statement's value is thrown away — except in a
1806                // script, where it becomes the program's result. `assign` reads this
1807                // and clears it, so a nested assignment still produces a value.
1808                self.state().discard_value = !self.cur().is_script;
1809                let result = self.expr(expr);
1810                self.state().discard_value = false;
1811                result?;
1812                if std::mem::take(&mut self.state().no_value) {
1813                    // A store whose value was discarded left nothing to drop.
1814                } else if self.cur().is_script {
1815                    // The program's value lands in the hidden `<ret>` local.
1816                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1817                } else {
1818                    self.emit(Opcode::Drop, &[]);
1819                }
1820                // Restored last: the trailing `drop` is part of the statement, and in the
1821                // reference it simply inherits whatever the expression last recorded.
1822                self.state().cur_pos = saved;
1823            }
1824            StmtKind::Block(body) => {
1825                // The block's declarations were hoisted with its enclosing
1826                // statement list, so there is nothing left to declare here.
1827                let key = stmt.span.start.offset as u64;
1828                let parent = self.cur().current_block;
1829                self.push_block(key, parent);
1830                self.emit_scope_enter(key);
1831                // A block is where a `using` region lives, so its statements have to go
1832                // through `stmts`: that is what emits the disposal epilogue.
1833                self.stmts(body)?;
1834                self.emit_scope_leave(key);
1835                self.state().current_block = parent;
1836            }
1837            StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1838            // A function declaration was already instantiated when its scope was
1839            // entered, so the statement itself emits nothing.
1840            StmtKind::FuncDecl(_) => {}
1841            StmtKind::If { test, cons, alt } => {
1842                self.reset_value();
1843                let else_label = self.new_label();
1844                let end_label = self.new_label();
1845                self.expr(test)?;
1846                self.emit_jump(Opcode::IfFalse, else_label, &[]);
1847                self.stmt(cons)?;
1848                if alt.is_some() {
1849                    self.emit_jump(Opcode::Goto, end_label, &[]);
1850                }
1851                self.place_label(else_label);
1852                if let Some(alt) = alt {
1853                    self.stmt(alt)?;
1854                    self.place_label(end_label);
1855                }
1856            }
1857            StmtKind::While { test, body } => {
1858                self.reset_value();
1859                let top = self.new_label();
1860                let end = self.new_label();
1861                self.place_label(top);
1862                self.expr(test)?;
1863                // The condition's false branch and `break` share one target,
1864                // which is why a `while` loop needs only one end label.
1865                self.emit_jump(Opcode::IfFalse, end, &[]);
1866                self.loop_body(body, labels, top, end)?;
1867                self.emit_jump(Opcode::Goto, top, &[]);
1868                self.place_label(end);
1869            }
1870            StmtKind::DoWhile { body, test } => {
1871                self.reset_value();
1872                let top = self.new_label();
1873                let cont = self.new_label();
1874                let end = self.new_label();
1875                self.place_label(top);
1876                // `continue` in a `do…while` runs the test, so it lands on `cont`
1877                // rather than on the loop head.
1878                self.loop_body(body, labels, cont, end)?;
1879                self.place_label(cont);
1880                self.expr(test)?;
1881                self.emit_jump(Opcode::IfTrue, top, &[]);
1882                self.place_label(end);
1883            }
1884            StmtKind::For {
1885                init,
1886                test,
1887                update,
1888                body,
1889            } => {
1890                self.reset_value();
1891                let for_key = stmt.span.start.offset as u64;
1892                let for_parent = self.cur().current_block;
1893                self.push_block(for_key, for_parent);
1894                self.emit_scope_enter(for_key);
1895                let mut using_head = None;
1896                if let Some(init) = init {
1897                    match init {
1898                        ForInit::VarDecl(decl) if decl.kind.is_using() => {
1899                            // A `using` resource declared in the head lives until the whole
1900                            // statement ends, not one iteration, so the disposal region has
1901                            // to wrap the loop — and there may be several of them, each
1902                            // needing its own region so that a later initialiser that
1903                            // throws still disposes the earlier resources
1904                            // (`initializer-disposed-if-subsequent-initializer-throws-in-forstatement-head`).
1905                            using_head = Some(decl);
1906                        }
1907                        ForInit::VarDecl(decl) => {
1908                            self.var_decl(decl)?;
1909                        }
1910                        ForInit::Expr(expr) => {
1911                            // The head's value is discarded. Saying so lets an
1912                            // assignment store with `put` instead of `dup`+`put`, which
1913                            // is what the reference emits — and the difference matters:
1914                            // a `dup`/`drop` pair around the store gives the peephole a
1915                            // chance to fold the store into the *condition's* read.
1916                            self.state().discard_value = true;
1917                            let result = self.expr(expr);
1918                            self.state().discard_value = false;
1919                            result?;
1920                            if !std::mem::take(&mut self.state().no_value) {
1921                                self.emit(Opcode::Drop, &[]);
1922                            }
1923                        }
1924                    }
1925                }
1926                // A `using` head's resource is disposed when the statement ends, on every
1927                // way out: `break`, `return`, an exception, and reaching the end.
1928                let flow = match using_head {
1929                    Some(decl) => self.for_using_head(
1930                        decl, 0, init, test, update, body, labels, for_key, for_parent,
1931                    ),
1932                    None => {
1933                        self.for_loop_tail(init, test, update, body, labels, for_key, for_parent)
1934                    }
1935                };
1936                flow?;
1937            }
1938            StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1939            StmtKind::Throw(expr) => {
1940                self.expr(expr)?;
1941                self.emit(Opcode::Throw, &[]);
1942            }
1943            StmtKind::Break(_) | StmtKind::Continue(_) => {
1944                // Labels and loops are wired up in a later milestone; a bare
1945                // break/continue jumps to the innermost enclosing target, which
1946                // the loop helpers register.
1947                self.control_transfer(stmt)?;
1948            }
1949            StmtKind::Labeled { label, body } => {
1950                self.labeled(label, body, stmt)?;
1951            }
1952            StmtKind::Switch {
1953                discriminant,
1954                cases,
1955            } => {
1956                self.switch(discriminant, cases, stmt)?;
1957            }
1958            StmtKind::Try {
1959                block,
1960                handler,
1961                finalizer,
1962            } => {
1963                self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
1964            }
1965            StmtKind::ForIn { left, right, body } => {
1966                self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
1967            }
1968            StmtKind::ForOf {
1969                left,
1970                right,
1971                body,
1972                is_await,
1973            } => {
1974                let kind = if *is_await {
1975                    ForLoopKind::AwaitOf
1976                } else {
1977                    ForLoopKind::Of
1978                };
1979                self.for_in_of(stmt, left, right, body, kind, labels)?;
1980            }
1981            StmtKind::With { object, body } => self.with_stmt(object, body)?,
1982            StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
1983            // `import` emits nothing: hoisting already bound its names, and the host
1984            // fills their cells before the body runs.
1985            StmtKind::Import(_) => {}
1986            StmtKind::Export(decl) => self.export_stmt(decl)?,
1987        }
1988        Ok(())
1989    }
1990
1991    /// Compile `return`, running every enclosing finalizer on the way out.
1992    ///
1993    /// `nip_catch` is what makes this possible: it discards everything on the stack
1994    /// down to and including the `catch` offset while keeping the return value on
1995    /// top, so the frame the finalizer sees has the same shape as on the normal
1996    /// path.
1997    fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
1998        let mut has_value = value.is_some();
1999        if let Some(expr) = value {
2000            // `return f(x)` is a tail call *only* when nothing has to happen to the
2001            // value afterwards. A `finally` or an open iterator in scope forces the
2002            // normal path, because the cleanup has to run after the call returns —
2003            // which is exactly what a tail call refuses to do.
2004            //
2005            // A **generator or async function** never tail-calls either: its `return` is
2006            // not a return to the caller but `return_async`, which reads the value off the
2007            // stack and finishes the coroutine. A tail call replaces the frame and hands
2008            // the callee's result straight to whoever resumed us, so the value vanished and
2009            // `it.next(42)` answered `{done: true, value: undefined}` for
2010            // `function* g(){ return f(yield) }`. The reference emits `call1` plus
2011            // `return_async` there and has no tail form for a suspending body at all.
2012            let plain = !self.cur().is_suspending()
2013                // A derived constructor's return is not just the value: a non-object answer
2014                // becomes `this`, so the frame has to survive to run that.
2015                && self.cur().ctor_kind != CtorKind::Derived
2016                && self
2017                    .cur()
2018                    .jump_targets
2019                    .iter()
2020                    .all(|target| target.finally_label.is_none() && !target.has_iterator);
2021            if plain && self.expr_if_tail_call(expr)? {
2022                // A tail call never reaches `expr`, so the direct-eval bookkeeping has to
2023                // happen here as well.
2024                self.note_direct_eval(expr);
2025                return Ok(());
2026            }
2027            self.expr(expr)?;
2028        }
2029        // `return v` in an *async generator* awaits `v` before anything else happens —
2030        // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
2031        // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
2032        // exactly that reason ("the await must be done before handling the finally in case
2033        // it raises an exception").
2034        if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
2035            self.emit(Opcode::Await, &[]);
2036            self.state().has_await = true;
2037        }
2038        has_value = self.emit_unwind_for_return(has_value);
2039        // A generator or async function does not return to its caller: it either
2040        // finishes, and the value becomes `{value, done: true}`, or it suspends.
2041        // `return_async` is the "finished" half, and it reads the value off the stack
2042        // rather than carrying it, which is what the resume machinery expects.
2043        if self.cur().is_suspending() {
2044            if !has_value {
2045                self.emit(Opcode::Undefined, &[]);
2046            }
2047            self.emit(Opcode::ReturnAsync, &[]);
2048            return Ok(());
2049        }
2050        // A derived constructor's result is `this` whenever the body does not answer an
2051        // object, and `this` is a local in the dead zone until `super()` returns — which is
2052        // why reading it here is also what turns `constructor(){ return; }` into the
2053        // ReferenceError the reference reports. The interpreter could not do this on its
2054        // own: by the time it sees `undefined` come back, the frame that held `this` is
2055        // gone, and `construct`'s own idea of `this` is the placeholder it made before the
2056        // body ran (`derived-class-return-override-with-{undefined,empty}`).
2057        if self.cur().ctor_kind == CtorKind::Derived {
2058            if !has_value {
2059                self.emit_var(VarAction::Get, "this");
2060                self.emit(Opcode::Return, &[]);
2061                return Ok(());
2062            }
2063            // `return <expr>` is only *sometimes* `this`: `undefined` is, any other
2064            // primitive is a `TypeError` (raised by `construct`), and an object replaces
2065            // `this` outright. Which one it is can only be known at run time.
2066            let keep = self.new_label();
2067            self.emit(Opcode::Dup, &[]);
2068            self.emit(Opcode::IsUndefined, &[]);
2069            self.emit_jump(Opcode::IfFalse, keep, &[]);
2070            self.emit(Opcode::Drop, &[]);
2071            self.emit_var(VarAction::Get, "this");
2072            self.place_label(keep);
2073            self.emit(Opcode::Return, &[]);
2074            return Ok(());
2075        }
2076        if has_value {
2077            self.emit(Opcode::Return, &[]);
2078        } else {
2079            self.emit(Opcode::ReturnUndef, &[]);
2080        }
2081        Ok(())
2082    }
2083
2084    /// Close an iterator: the reference's `emit_iterator_close`.
2085    ///
2086    /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
2087    /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
2088    /// sequence, and three details in it are load-bearing:
2089    ///
2090    /// * the iterator object is compared against `undefined` first, because a loop that
2091    ///   ran to completion clears that slot rather than closing an exhausted iterator;
2092    /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
2093    /// * `preserve_completion` keeps whatever was underneath (the return value of the
2094    ///   function being left), which is why one branch ends on `nip` and the other on `drop`.
2095    fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
2096        if !is_async {
2097            if preserve_completion {
2098                self.emit(Opcode::Rot3r, &[]);
2099                self.emit(Opcode::Undefined, &[]);
2100            }
2101            self.emit(Opcode::IteratorClose, &[]);
2102            return;
2103        }
2104        if preserve_completion {
2105            // `iter next completion -> completion iter`
2106            self.emit(Opcode::Nip, &[]);
2107            self.emit(Opcode::Swap, &[]);
2108        } else {
2109            // `iter next catch_offset -> iter`
2110            self.emit(Opcode::Drop, &[]);
2111            self.emit(Opcode::Drop, &[]);
2112        }
2113        let done = self.new_label();
2114        let no_return = self.new_label();
2115        self.emit(Opcode::Dup, &[]);
2116        self.emit(Opcode::IsUndefined, &[]);
2117        self.emit_jump(Opcode::IfTrue, done, &[]);
2118        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
2119        self.emit(Opcode::Dup, &[]);
2120        self.emit(Opcode::IsUndefinedOrNull, &[]);
2121        self.emit_jump(Opcode::IfTrue, no_return, &[]);
2122        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
2123        self.emit(Opcode::Await, &[]);
2124        self.state().has_await = true;
2125        self.emit_jump(Opcode::Goto, done, &[]);
2126        self.place_label(no_return);
2127        self.emit(Opcode::Drop, &[]);
2128        self.place_label(done);
2129        self.emit(Opcode::Drop, &[]);
2130    }
2131
2132    /// Emit the finalizer/iterator cleanup for leaving the current position with a
2133    /// return, and report whether a value is now on the stack for it to carry.
2134    ///
2135    /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
2136    /// enclosing `finally` at once, and the two used to be separate — the `yield` path
2137    /// simply emitted `return_async`, so `it.return()` ended the generator without ever
2138    /// running `finally` blocks the body was sitting inside.
2139    fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
2140        let targets = self.cur().jump_targets.clone();
2141        for target in targets.iter().rev() {
2142            if target.finally_label.is_none() && !target.has_iterator {
2143                continue;
2144            }
2145            if !has_value {
2146                // The cleanup expects a value to pass through; with nothing to
2147                // return, `undefined` stands in.
2148                self.emit(Opcode::Undefined, &[]);
2149                has_value = true;
2150            }
2151            self.emit(Opcode::NipCatch, &[]);
2152            if target.has_iterator {
2153                // Rewind to the loop's own slots and hand the close a dummy catch offset:
2154                // the loop is being abandoned, so there is nothing left to catch.
2155                self.emit_iterator_close(target.is_async_iterator, true);
2156            } else if let Some(finally) = target.finally_label {
2157                self.emit_jump(Opcode::Gosub, finally, &[]);
2158            }
2159        }
2160        has_value
2161    }
2162
2163    /// Compile a statement list, stopping at the first statement that cannot
2164    /// fall through.
2165    fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2166        for (index, stmt) in body.iter().enumerate() {
2167            // A `using` declaration is not just a binding: everything after it, to the end
2168            // of the list, runs inside its disposal region. Compiling the rest of the list
2169            // recursively is what gives nested regions their innermost-first order.
2170            if Self::using_declaration(stmt).is_some() {
2171                return self.using_region(stmt, &body[index + 1..]);
2172            }
2173            self.stmt(stmt)?;
2174            if Self::terminates(stmt) {
2175                break;
2176            }
2177        }
2178        Ok(())
2179    }
2180
2181    /// The declaration a `using` statement carries, if it is one.
2182    fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
2183        match &stmt.kind {
2184            StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
2185            _ => None,
2186        }
2187    }
2188
2189    /// Compile `decl` and then the rest of its block, disposing when the block ends.
2190    ///
2191    /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
2192    /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
2193    /// exception — and this engine already funnels all of those through `catch` plus
2194    /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
2195    /// `return` and `break` dispose without knowing anything about `using`.
2196    ///
2197    /// ```text
2198    ///   <declaration>              value -> x, method -> x+1
2199    ///   catch CATCH                <- an exception in the rest lands here
2200    /// REST:
2201    ///   <the rest of the block>
2202    ///   drop                       <- the catch offset, on the fall-through path
2203    ///   undefined; gosub DISPOSE; drop
2204    ///   goto END
2205    /// CATCH:
2206    ///   using_dispose x            <- merges the failure into the pending exception
2207    ///   throw
2208    /// DISPOSE:
2209    ///   using_dispose_init
2210    ///   using_dispose x
2211    ///   using_dispose_end          <- rethrows if a dispose failed
2212    ///   ret
2213    /// END:
2214    /// ```
2215    fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
2216        let Some(decl) = Self::using_declaration(stmt) else {
2217            unreachable!("using_region is only called for a using declaration");
2218        };
2219        self.using_declarator(stmt, decl, 0, rest)
2220    }
2221
2222    /// One declarator of a `using` declaration, plus the region around everything after it.
2223    ///
2224    /// A `using` may list several resources — `using a = x, b = y;` — and each one is
2225    /// disposed when the block ends, in **reverse** order: §14.3.1.4 pushes them onto
2226    /// `DisposableResourceStack` in source order and §9.5.5 disposes from the top. Nesting
2227    /// one region per declarator gives exactly that, because the inner region ends first
2228    /// (`multiple-resources-disposed-in-reverse-order`). Compiling only the first left the
2229    /// rest undisposed.
2230    fn using_declarator(
2231        &mut self,
2232        stmt: &Stmt,
2233        decl: &VarDecl,
2234        index: usize,
2235        rest: &[Stmt],
2236    ) -> Result<(), SyntaxError> {
2237        let Some(declarator) = decl.declarators.get(index) else {
2238            return self.stmts(rest);
2239        };
2240        // `using` binds a plain identifier and has no pattern form, which the parser
2241        // enforces; the region still has to know *which* slot to dispose.
2242        let name = match &declarator.target.kind {
2243            PatternKind::Ident(ident) => Some(ident.name.clone()),
2244            _ => None,
2245        };
2246        let single = Stmt {
2247            kind: StmtKind::VarDecl(VarDecl {
2248                kind: decl.kind,
2249                declarators: vec![declarator.clone()],
2250                span: declarator.span,
2251            }),
2252            span: declarator.span,
2253        };
2254        self.stmt(&single)?;
2255        let Some(name) = name else {
2256            // Unreachable for a well-formed `using`, but a bare `using` with no declarator
2257            // must not make the compiler panic.
2258            return self.using_declarator(stmt, decl, index + 1, rest);
2259        };
2260        let Some(value_slot) = self.using_value_slot(&name) else {
2261            // Declared globally, which the parser rules out for a script; a module's
2262            // top level is a scope, and there the disposal stays a known gap.
2263            return self.using_declarator(stmt, decl, index + 1, rest);
2264        };
2265        // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
2266        // exit path already disposed.
2267        let live = !rest.last().is_some_and(Self::terminates);
2268        let _ = stmt;
2269        self.using_region_around(
2270            value_slot,
2271            live,
2272            decl.kind == VarDeclKind::AwaitUsing,
2273            |compiler| compiler.using_declarator(stmt, decl, index + 1, rest),
2274        )
2275    }
2276
2277    /// One `using` declarator of a `for` head, wrapped in its disposal region, and then the
2278    /// next — so the resources nest inside-out and dispose in reverse order.
2279    #[allow(clippy::too_many_arguments)]
2280    fn for_using_head(
2281        &mut self,
2282        decl: &VarDecl,
2283        index: usize,
2284        init: &Option<ForInit>,
2285        test: &Option<Box<Expr>>,
2286        update: &Option<Box<Expr>>,
2287        body: &Stmt,
2288        labels: &[String],
2289        for_key: u64,
2290        for_parent: u64,
2291    ) -> Result<(), SyntaxError> {
2292        let Some(declarator) = decl.declarators.get(index) else {
2293            return self.for_loop_tail(init, test, update, body, labels, for_key, for_parent);
2294        };
2295        let name = match &declarator.target.kind {
2296            PatternKind::Ident(ident) => Some(ident.name.clone()),
2297            _ => None,
2298        };
2299        self.var_decl(&VarDecl {
2300            kind: decl.kind,
2301            declarators: vec![declarator.clone()],
2302            span: declarator.span,
2303        })?;
2304        let Some(slot) = name.and_then(|name| self.using_value_slot(&name)) else {
2305            return self.for_using_head(
2306                decl,
2307                index + 1,
2308                init,
2309                test,
2310                update,
2311                body,
2312                labels,
2313                for_key,
2314                for_parent,
2315            );
2316        };
2317        self.using_region_around(
2318            slot,
2319            true,
2320            decl.kind == VarDeclKind::AwaitUsing,
2321            |compiler| {
2322                compiler.for_using_head(
2323                    decl,
2324                    index + 1,
2325                    init,
2326                    test,
2327                    update,
2328                    body,
2329                    labels,
2330                    for_key,
2331                    for_parent,
2332                )
2333            },
2334        )
2335    }
2336
2337    /// The half of a `for` statement that runs inside its head's disposal region: the
2338    /// per-iteration bindings, the test, the body and the update.
2339    ///
2340    /// Split out so that a `using` head can wrap exactly this much — see the
2341    /// `StmtKind::For` arm — because the resource lives as long as the statement.
2342    #[allow(clippy::too_many_arguments)]
2343    fn for_loop_tail(
2344        &mut self,
2345        init: &Option<ForInit>,
2346        test: &Option<Box<Expr>>,
2347        update: &Option<Box<Expr>>,
2348        body: &Stmt,
2349        labels: &[String],
2350        for_key: u64,
2351        for_parent: u64,
2352    ) -> Result<(), SyntaxError> {
2353        // A `let`/`const` in the head gets a *fresh binding per iteration*,
2354        // so a closure made in the body captures that iteration's value
2355        // instead of sharing one. The reference expresses this with
2356        // `close_loc`, which swaps in a new reference cell holding the
2357        // current value; the three points below are the ones it uses — after
2358        // the initialiser, before the update, and after the loop.
2359        let loop_bindings = match init {
2360            Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
2361                let mut names: Vec<String> = Vec::new();
2362                for declarator in &decl.declarators {
2363                    let mut idents = Vec::new();
2364                    declarator.target.bound_names(&mut idents);
2365                    names.extend(idents.into_iter().map(|ident| ident.name));
2366                }
2367                names
2368            }
2369            _ => Vec::new(),
2370        };
2371        // The reference also closes right after the initialiser, so the first
2372        // iteration's closures get their own cell rather than sharing the one
2373        // the initialiser wrote into.
2374        for name in &loop_bindings {
2375            let pos = self.cur().cur_pos;
2376            self.state().insns.push(Insn::CloseCaptured {
2377                name: name.clone(),
2378                block: for_key,
2379            });
2380            self.state().insn_pos.push(pos);
2381        }
2382        let top = self.new_label();
2383        let cont = self.new_label();
2384        let end = self.new_label();
2385        self.place_label(top);
2386        if let Some(test) = test {
2387            self.expr(test)?;
2388            self.emit_jump(Opcode::IfFalse, end, &[]);
2389        }
2390        // `continue` runs the update expression first, so it lands on
2391        // `cont`, which sits just before the update.
2392        self.loop_body(body, labels, cont, end)?;
2393        self.place_label(cont);
2394        // Each iteration ends with a fresh cell, so the closures the body just
2395        // created keep the cell they captured and the update writes to a new
2396        // one. Without this every closure in the loop shares one binding.
2397        let binding_block = for_key;
2398        for name in &loop_bindings {
2399            let pos = self.cur().cur_pos;
2400            self.state().insns.push(Insn::CloseCaptured {
2401                name: name.clone(),
2402                block: binding_block,
2403            });
2404            self.state().insn_pos.push(pos);
2405        }
2406        if let Some(update) = update {
2407            self.state().discard_value = true;
2408            let result = self.expr(update);
2409            self.state().discard_value = false;
2410            result?;
2411            if !std::mem::take(&mut self.state().no_value) {
2412                self.emit(Opcode::Drop, &[]);
2413            }
2414        }
2415        self.emit_jump(Opcode::Goto, top, &[]);
2416        self.place_label(end);
2417        self.emit_scope_leave(for_key);
2418        self.state().current_block = for_parent;
2419        Ok(())
2420    }
2421
2422    /// The slot a `using` binding's value lives in.
2423    fn using_value_slot(&self, name: &str) -> Option<u32> {
2424        self.cur()
2425            .vars
2426            .iter()
2427            .position(|var| var.name == name && var.kind == VarKind::Using)
2428            .map(|index| index as u32)
2429    }
2430
2431    /// Wrap `inside` in a disposal region for the resource in `value_slot`.
2432    ///
2433    /// Shared between a `using` statement — which owns the rest of its block — and a
2434    /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
2435    /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
2436    /// the end, `return`, `break`, `continue`, and an exception — and this engine already
2437    /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
2438    /// target with a `finally_label` is what makes `return` and `break` dispose without
2439    /// knowing anything about `using`.
2440    ///
2441    /// ```text
2442    ///   catch CATCH                <- an exception inside lands here
2443    ///   <inside>
2444    ///   drop                       <- the catch offset, on the fall-through path
2445    ///   undefined; gosub DISPOSE; drop
2446    ///   goto END
2447    /// CATCH:
2448    ///   using_dispose slot         <- merges the failure into the pending exception
2449    ///   throw
2450    /// DISPOSE:
2451    ///   using_dispose_init
2452    ///   using_dispose slot
2453    ///   using_dispose_end          <- rethrows if a dispose failed
2454    ///   ret
2455    /// END:
2456    /// ```
2457    fn using_region_around(
2458        &mut self,
2459        value_slot: u32,
2460        live: bool,
2461        is_await_using: bool,
2462        inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
2463    ) -> Result<(), SyntaxError> {
2464        let catch_label = self.new_label();
2465        let end_label = self.new_label();
2466        let dispose_label = self.new_label();
2467
2468        self.emit_jump(Opcode::Catch, catch_label, &[]);
2469        self.push_jump_target(JumpTarget {
2470            names: Vec::new(),
2471            break_label: None,
2472            continue_label: None,
2473            // The catch offset is the one thing on the stack that leaving has to remove.
2474            drop_count: 1,
2475            finally_label: Some(dispose_label),
2476            is_regular_stmt: false,
2477            has_iterator: false,
2478            is_async_iterator: false,
2479        });
2480        inside(self)?;
2481        self.pop_jump_target();
2482
2483        if live {
2484            self.emit(Opcode::Drop, &[]);
2485            self.emit(Opcode::Undefined, &[]);
2486            self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2487            self.emit(Opcode::Drop, &[]);
2488            self.emit_jump(Opcode::Goto, end_label, &[]);
2489        }
2490
2491        // An exception unwinds to here with the thrown value on the stack, which is exactly
2492        // the shape `using_dispose` expects as its error state.
2493        self.place_label(catch_label);
2494        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2495        self.emit(Opcode::Throw, &[]);
2496
2497        self.place_label(dispose_label);
2498        // Inside the subroutine the return value and the `gosub` return address are both
2499        // live, and neither an outer finalizer nor another region may run before this one
2500        // has finished.
2501        self.push_jump_target(JumpTarget {
2502            names: Vec::new(),
2503            break_label: None,
2504            continue_label: None,
2505            drop_count: 2,
2506            finally_label: None,
2507            is_regular_stmt: false,
2508            has_iterator: false,
2509            is_async_iterator: false,
2510        });
2511        self.emit(Opcode::UsingDisposeInit, &[]);
2512        if is_await_using {
2513            // `AsyncDisposableStack`'s order: call the method, **await** its result, and
2514            // fold a rejection into the error state. The catch is what turns that
2515            // rejection — which arrives as an exception from `await` — into the merged
2516            // error, so one failure is rethrown as itself and two become a
2517            // `SuppressedError` (§27.1.3.3's `DisposeResources` steps 5–6).
2518            //
2519            // The shape is the reference's `js_emit_dispose_scope`, adapted to this
2520            // engine's error-state protocol: `using_dispose_init` pushed the state and
2521            // `using_dispose_end` will consume it, so both arms have to leave it in place.
2522            let catch_label = self.new_label();
2523            let merged_label = self.new_label();
2524            self.emit_jump(Opcode::Catch, catch_label, &[]);
2525            self.emit(
2526                Opcode::UsingDisposeAsync,
2527                &[Op::Slot(Slot::Loc(value_slot))],
2528            );
2529            self.emit(Opcode::Await, &[]);
2530            // The awaited value, and the catch offset the successful path still holds.
2531            self.emit(Opcode::Drop, &[]);
2532            self.emit(Opcode::Drop, &[]);
2533            self.emit_jump(Opcode::Goto, merged_label, &[]);
2534            self.place_label(catch_label);
2535            self.emit(Opcode::UsingDisposeMerge, &[]);
2536            self.place_label(merged_label);
2537            self.state().has_await = true;
2538        } else {
2539            self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2540        }
2541        self.emit(Opcode::UsingDisposeEnd, &[]);
2542        self.pop_jump_target();
2543        self.emit(Opcode::Ret, &[]);
2544        self.place_label(end_label);
2545        Ok(())
2546    }
2547
2548    /// Declare every name a statement list introduces, before compiling any of
2549    /// it, so a reference that appears textually before a declaration still
2550    /// resolves.
2551    ///
2552    /// Declarations are walked in source order because that is the order the
2553    /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2554    /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2555    /// declarations hoist out to the function scope; lexical names belong to the
2556    /// block they were written in, which `block` records.
2557    fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2558        let saved = self.cur().current_block;
2559        self.state().current_block = block;
2560        let result = self.hoist_list(body);
2561        // Only now is every binding of this scope known, so the deferred function
2562        // bodies can be compiled against the finished list. Compiled at its own
2563        // declaration instead, a body that names a `var` written further down would
2564        // have resolved that name as a global.
2565        if result.is_ok() {
2566            let deferred = std::mem::take(&mut self.state().deferred_funcs);
2567            let mut outcome = Ok(());
2568            for (owner, func) in deferred {
2569                let previous = self.cur().current_block;
2570                self.state().current_block = owner;
2571                outcome = self.func_decl(&func);
2572                self.state().current_block = previous;
2573                if outcome.is_err() {
2574                    break;
2575                }
2576            }
2577            self.state().current_block = saved;
2578            return outcome;
2579        }
2580        // `current_block` is restored by the caller for a block statement, since
2581        // it needs it set while compiling; only clean up on the hoist path.
2582        self.state().current_block = saved;
2583        result
2584    }
2585
2586    fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2587        for stmt in body {
2588            self.hoist_stmt(stmt)?;
2589        }
2590        Ok(())
2591    }
2592
2593    /// Whether a statement always transfers control away, making everything after
2594    /// it in the same list unreachable.
2595    ///
2596    /// The reference drops such statements in `skip_dead_code`, so `return 1;
2597    /// let x = 2;` compiles to the same bytecode as `return 1;`.
2598    fn terminates(stmt: &Stmt) -> bool {
2599        matches!(
2600            stmt.kind,
2601            StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2602        )
2603    }
2604
2605    fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2606        match &stmt.kind {
2607            StmtKind::VarDecl(decl) => {
2608                for declarator in &decl.declarators {
2609                    let mut names = Vec::new();
2610                    declarator.target.bound_names(&mut names);
2611                    for name in names {
2612                        let text = name.name.clone();
2613                        if decl.kind == VarDeclKind::Var {
2614                            let def = VarDef::var(text.clone());
2615                            self.declare_var(&text, def);
2616                        } else if decl.kind.is_using() {
2617                            // Two adjacent slots: the resource, then the dispose method
2618                            // snapshotted at declaration. `using_dispose` reads them as a
2619                            // pair `(slot, slot + 1)`, so nothing may be declared between
2620                            // them — which is why both are declared here, in one step,
2621                            // rather than the method being added at emission time.
2622                            self.declare_using(&text);
2623                        } else {
2624                            let def = if decl.kind == VarDeclKind::Const {
2625                                VarDef::constant(text.clone())
2626                            } else {
2627                                VarDef::lexical(text.clone())
2628                            };
2629                            self.declare(&text, def);
2630                        }
2631                    }
2632                }
2633            }
2634            StmtKind::FuncDecl(func) => {
2635                if let Some(name) = &func.name {
2636                    // A function declaration is a `var` binding that happens to
2637                    // hold a function, not a lexical one.
2638                    let def = VarDef::var(name.name.clone());
2639                    self.declare_var(&name.name.clone(), def);
2640                }
2641                // The function object is created when the scope is entered, so it
2642                // exists before the declaration is reached. Its body is compiled
2643                // *after* this scope's hoisting finishes, so a name it uses resolves
2644                // even when the `var` that declares it comes later in the source.
2645                let owner = self.cur().current_block;
2646                self.state().deferred_funcs.push((owner, func.clone()));
2647            }
2648            StmtKind::ClassDecl(class) => {
2649                if let Some(name) = &class.name {
2650                    self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2651                }
2652            }
2653            // A module's imports are bound before any of its code runs, and its exports
2654            // declare the very bindings they export — so both hoist the declarations
2655            // their `StmtKind` arm will later emit code for.
2656            StmtKind::Import(decl) => self.hoist_import(decl)?,
2657            StmtKind::Export(decl) => self.hoist_export(decl)?,
2658            StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2659            StmtKind::If { cons, alt, .. } => {
2660                self.hoist_stmt(cons)?;
2661                if let Some(alt) = alt {
2662                    self.hoist_stmt(alt)?;
2663                }
2664            }
2665            StmtKind::While { body, .. }
2666            | StmtKind::DoWhile { body, .. }
2667            | StmtKind::Labeled { body, .. }
2668            | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2669            StmtKind::For { init, body, .. } => {
2670                // A `for` head gets its own scope even when it declares nothing,
2671                // because `let` in the head is scoped to the loop.
2672                let key = stmt.span.start.offset as u64;
2673                let parent = self.cur().current_block;
2674                self.push_block(key, parent);
2675                if let Some(init) = init
2676                    && let ForInit::VarDecl(decl) = init
2677                {
2678                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2679                }
2680                self.hoist_stmt(body)?;
2681                self.state().current_block = parent;
2682            }
2683            StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
2684                let key = stmt.span.start.offset as u64;
2685                let parent = self.cur().current_block;
2686                self.push_block(key, parent);
2687                if let ForHead::VarDecl(decl) = left {
2688                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2689                }
2690                self.hoist_stmt(body)?;
2691                self.state().current_block = parent;
2692            }
2693            StmtKind::Try {
2694                block,
2695                handler,
2696                finalizer,
2697            } => {
2698                self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2699                let try_parent = self.cur().current_block;
2700                if let Some(handler) = handler {
2701                    // The catch parameter belongs to the function scope, not to a
2702                    // block: it is a `catch` binding rather than a `let`, so it is
2703                    // never in the temporal dead zone and `emit_scope_enter` must
2704                    // not mark it uninitialised. It still has to be declared before
2705                    // the handler body is hoisted, so it takes the slot the
2706                    // reference gives it (bindings are numbered in source order).
2707                    if let Some(pattern) = &handler.param {
2708                        // The parameter gets its own scope, so entering the handler
2709                        // does not have to re-declare it. It is not lexical, so it
2710                        // is never marked uninitialised.
2711                        let key = Self::try_block_key(stmt, TryPart::Param);
2712                        let parent = self.cur().current_block;
2713                        self.push_block(key, parent);
2714                        // A destructuring parameter binds several names, one slot each,
2715                        // in the order they are written. The reference declares those as
2716                        // `let`s rather than as one `catch` binding — its dump prints
2717                        // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2718                        // so the kind follows the shape of the parameter.
2719                        //
2720                        // Neither form is in the dead zone: the stores run as the handler
2721                        // is entered, so both use the unchecked `put_loc`.
2722                        let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2723                        let mut names = Vec::new();
2724                        pattern.bound_names(&mut names);
2725                        for name in names {
2726                            let def = VarDef {
2727                                name: name.name.clone(),
2728                                is_const: false,
2729                                is_lexical: destructures,
2730                                kind: if destructures {
2731                                    crate::bytecode::VarKind::LexicalCatch
2732                                } else {
2733                                    crate::bytecode::VarKind::Catch
2734                                },
2735                                is_captured: false,
2736                                scope_level: 0,
2737                                scope_next: None,
2738                            };
2739                            self.declare_local(&name.name.clone(), def);
2740                        }
2741                        // The handler body nests inside the parameter's scope, so the
2742                        // body's bindings chain on to the parameter (the reference
2743                        // prints `let y [next:1]`, pointing at `e`).
2744                        self.state().current_block = key;
2745                    }
2746                    self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2747                    // Back to the block the `try` itself lives in, so the finalizer
2748                    // is a sibling of the handler rather than nested in it.
2749                    self.state().current_block = try_parent;
2750                }
2751                if let Some(finalizer) = finalizer {
2752                    self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2753                }
2754            }
2755            StmtKind::Switch { cases, .. } => {
2756                let key = stmt.span.start.offset as u64;
2757                let parent = self.cur().current_block;
2758                self.push_block(key, parent);
2759                for case in cases {
2760                    self.hoist_list(&case.body)?;
2761                }
2762                self.state().current_block = parent;
2763            }
2764            _ => {}
2765        }
2766        Ok(())
2767    }
2768
2769    /// Hoist a nested statement list, which is its own lexical scope.
2770    fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2771        let parent = self.cur().current_block;
2772        self.push_block(key, parent);
2773        self.hoist_list(body)?;
2774        self.state().current_block = parent;
2775        Ok(())
2776    }
2777
2778    /// A block key for one part of a `try` statement.
2779    ///
2780    /// The three parts are three separate scopes, so they cannot share the key a
2781    /// statement's own offset would give them: the try block, the handler body and
2782    /// the finalizer would then look like one scope, and their `let` bindings would
2783    /// be marked uninitialised only on entering the first of them.
2784    fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2785        (stmt.span.start.offset as u64) * 4 + part as u64
2786    }
2787
2788    /// Declare a `var`: it lives in the function's own scope, not the block's.
2789    fn declare_var(&mut self, name: &str, def: VarDef) {
2790        if self.cur().is_module {
2791            self.declare_module(name, &def);
2792            return;
2793        }
2794        if self.cur().declares_globally(&def) {
2795            self.declare_global(name, &def);
2796            return;
2797        }
2798        let state = self.state();
2799        // A binding of the *parameter* scope does not count: the body's `var` of the
2800        // same name is a different binding and needs a slot of its own.
2801        if state.vars.iter().enumerate().any(|(index, v)| {
2802            v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
2803        }) {
2804            return;
2805        }
2806        // A `var` belongs to the function scope, never to the enclosing block.
2807        state.var_block.push(FUNCTION_SCOPE);
2808        state.vars.push(def);
2809    }
2810
2811    /// Declare `name` as a binding of the parameter scope, returning its slot.
2812    fn declare_param_var(&mut self, name: &str) -> u32 {
2813        declare_param_var_at(self.state(), name)
2814    }
2815
2816    /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2817    ///
2818    /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2819    /// so each points at the one declared before it and the oldest ends the chain with
2820    /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2821    /// runtime walks when it instantiates them.
2822    fn declare_param_binding(&mut self, name: &str) -> u32 {
2823        let state = self.state();
2824        let previous = state
2825            .vars
2826            .iter()
2827            .enumerate()
2828            .rev()
2829            .find(|(index, var)| {
2830                state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2831            })
2832            .map(|(index, _)| index as i32);
2833        let index = state.vars.len() as u32;
2834        state.var_block.push(PARAM_SCOPE);
2835        let mut def = VarDef::lexical(name);
2836        // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2837        // the function's, and its bindings are initialised one by one rather than all at
2838        // once — which is exactly what the dead zone needs.
2839        def.scope_level = 1;
2840        def.scope_next = Some(previous.unwrap_or(-2));
2841        state.vars.push(def);
2842        index
2843    }
2844
2845    /// The slot of a parameter-list binding, if the list has one by that name.
2846    fn param_binding_slot(&self, name: &str) -> Option<u32> {
2847        let state = self.cur();
2848        state
2849            .vars
2850            .iter()
2851            .enumerate()
2852            .position(|(index, var)| {
2853                var.name == name
2854                    && var.is_lexical
2855                    && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2856            })
2857            .map(|index| index as u32)
2858    }
2859
2860    /// Every parameter-list binding, in declaration order.
2861    fn param_binding_names(&self) -> Vec<String> {
2862        let state = self.cur();
2863        state
2864            .vars
2865            .iter()
2866            .enumerate()
2867            .filter(|(index, var)| {
2868                var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2869            })
2870            .map(|(_, var)| var.name.clone())
2871            .collect()
2872    }
2873
2874    /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2875    fn body_var_slot(&self, name: &str) -> Option<u32> {
2876        let state = self.cur();
2877        state
2878            .vars
2879            .iter()
2880            .enumerate()
2881            .find(|(index, var)| {
2882                var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2883            })
2884            .map(|(index, _)| index as u32)
2885    }
2886
2887    /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2888    /// one.
2889    ///
2890    /// With parameter expressions the reference creates two: an unmapped one in the
2891    /// argument scope, for the defaults and anything they close over, and the body's own.
2892    /// They are separate bindings, which is what makes
2893    /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2894    /// report 1 from `p` and 2 from the body.
2895    fn provide_param_arguments(&mut self) {
2896        if !self.cur().has_parameter_expressions {
2897            return;
2898        }
2899        let mentioned = self.cur().needs_param_arguments
2900            || self
2901                .cur()
2902                .insns
2903                .iter()
2904                .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2905        if !mentioned {
2906            return;
2907        }
2908        let slot = self.declare_param_var("arguments");
2909        let magic = if self.cur().strict || !self.cur().simple_parameter_list {
2910            0
2911        } else {
2912            1
2913        };
2914        self.prepend_initialiser_to(
2915            slot,
2916            Insn::Fixed {
2917                op: Opcode::SpecialObject,
2918                operands: vec![Op::Int(magic)],
2919            },
2920        );
2921    }
2922
2923    /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2924    fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2925        let current = self.stack.len() - 1;
2926        let init = [
2927            producer,
2928            Insn::Fixed {
2929                op: Opcode::PutLoc,
2930                operands: vec![Op::Slot(Slot::Loc(slot))],
2931            },
2932        ];
2933        let inserted = init.len();
2934        for (index, instruction) in init.into_iter().enumerate() {
2935            self.stack[current].insns.insert(index, instruction);
2936        }
2937        for placed in self.stack[current].labels.iter_mut().flatten() {
2938            *placed += inserted;
2939        }
2940        self.state().label_since_insn = false;
2941    }
2942
2943    /// Give the function an `arguments` binding if its body mentions one.
2944    ///
2945    /// The check runs on the *instruction* stream rather than the AST: by this point
2946    /// every reference has become an `Insn::Var`, so scanning is exact and needs no
2947    /// AST walker. Declaring lazily matters for more than tidiness — always declaring
2948    /// would renumber every later local slot and stop the bytecode matching the
2949    /// reference, which only adds the binding when the body uses it.
2950    ///
2951    /// `arguments` is a local, initialised at the top of the body by
2952    /// `special_object`; that is the reference's shape, so the disassembly agrees.
2953    fn provide_arguments(&mut self) {
2954        let current = self.stack.len() - 1;
2955        if self.stack[current].is_script || self.stack[current].is_module {
2956            // A module has no `arguments` binding; referring to it is a ReferenceError,
2957            // which is exactly what an unbound name produces.
2958            return;
2959        }
2960        // An arrow has no `arguments` of its own: the binding belongs to the enclosing
2961        // function, which is why `() => arguments` sees the caller's arguments.
2962        if self.stack[current].is_arrow {
2963            if self.mentions("arguments") {
2964                self.ensure_enclosing_arguments();
2965            }
2966            return;
2967        }
2968        // Only a *body* mention needs the body's binding: the parameter list has one of
2969        // its own (see [`Compiler::provide_param_arguments`]).
2970        //
2971        // `delete arguments` counts too: it compiles to `DeleteVar`, which is not a
2972        // `Var`, so without this the body got no binding at all — the name resolved to
2973        // the global object and `delete` answered `true` for a binding that cannot be
2974        // deleted. The reference answers `false`.
2975        let mentioned = self.cur().insns.iter().any(|insn| match insn {
2976            Insn::Var {
2977                name, in_params, ..
2978            } => name == "arguments" && !*in_params,
2979            Insn::DeleteVar { name } => name == "arguments",
2980            _ => false,
2981        });
2982        // A mention that resolves to the body's *own* lexical `arguments` is not a request
2983        // for the implicit one — `function f(p = 1) { let arguments; }` shadows it, and the
2984        // implicit binding is not created at all. Providing it anyway was worse than useless:
2985        // its prologue store resolved past the shadowing `let` and landed on the **global**,
2986        // so `function f(p = eval("var arguments")) { let arguments; }` defined
2987        // `globalThis.arguments` as a side effect (`globalThis.arguments unchanged` in
2988        // test262's `fn-body-cntns-arguments-lex-bind` family).
2989        //
2990        // Lexical only. `var arguments = 1` in the body is a different thing entirely: the
2991        // var *is* the binding, and the implicit arguments object is initialised into it at
2992        // entry, which is why `function f(){ return typeof arguments; var arguments = 1 }`
2993        // answers `"object"` (`S13_A15_T4`). Suppressing the prologue for those two made
2994        // `typeof arguments` `"undefined"`.
2995        if self
2996            .cur()
2997            .vars
2998            .iter()
2999            .any(|var| var.name == "arguments" && var.needs_check())
3000        {
3001            return;
3002        }
3003        if !mentioned && !self.cur().needs_arguments_local {
3004            return;
3005        }
3006        // The request may have come only from a parameter-list arrow, in which case the
3007        // parameter scope's binding already answers for it and the body needs none.
3008        if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
3009            return;
3010        }
3011        // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`.
3012        //
3013        // With parameter expressions the list and the body are separate environments, so
3014        // an assignment to a parameter cannot be reflected into `arguments` at all — the
3015        // arguments object is unmapped whatever the mode, which is why the reference emits
3016        // `special_object 0` here even in sloppy code.
3017        // A non-simple parameter list (`[a]`, `...rest`, `a = 1`) makes the arguments
3018        // object unmapped whatever the mode — §10.4.4 keys the decision on
3019        // `IsSimpleParameterList`, not on strictness alone.
3020        let magic = if self.stack[current].strict || !self.stack[current].simple_parameter_list {
3021            0
3022        } else {
3023            1
3024        };
3025        // A mapped `arguments` shares storage with the parameters: `arguments[0] = 2`
3026        // has to be visible as `a`, and assigning `a` has to be visible as `arguments[0]`.
3027        // The only storage both sides can see is a reference cell, so every parameter the
3028        // object maps gets one — even a parameter no closure captured. Without this the
3029        // slot holds a plain copy and the mapping has nothing to write through.
3030        if magic == 1 {
3031            for arg in &mut self.stack[current].args {
3032                arg.is_captured = true;
3033            }
3034        }
3035        self.prepend_binding("arguments", magic);
3036    }
3037
3038    /// Whether a *body* instruction refers to `arguments`.
3039    fn body_mentions_arguments(&self) -> bool {
3040        self.cur()
3041            .insns
3042            .iter()
3043            .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
3044    }
3045
3046    /// Whether the function body's instruction stream refers to `name`.
3047    fn mentions(&self, name: &str) -> bool {
3048        let current = self.stack.len() - 1;
3049        // A binding of the parameter scope does not answer for the body: the body's own
3050        // `arguments` (or self-name) still has to be provided for it.
3051        if self.stack[current]
3052            .vars
3053            .iter()
3054            .enumerate()
3055            .any(|(index, v)| {
3056                v.name == name
3057                    && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
3058            })
3059        {
3060            return false;
3061        }
3062        self.stack[current]
3063            .insns
3064            .iter()
3065            .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
3066    }
3067
3068    /// Bind the name a named function expression uses to refer to itself.
3069    ///
3070    /// The value is `special_object 2`, the function currently running, so the binding
3071    /// is the closure itself and not a copy. It is a local of this function, which is
3072    /// what keeps `g` out of the enclosing scope.
3073    /// Give the function a local `this`, for an arrow inside it to capture.
3074    fn provide_this_local(&mut self) {
3075        let current = self.stack.len() - 1;
3076        if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
3077            return;
3078        }
3079        if !self.stack[current]
3080            .vars
3081            .iter()
3082            .any(|var| var.name == "this")
3083        {
3084            self.declare_hidden_local("this", VarKind::Normal);
3085        }
3086        self.prepend_initialiser(
3087            "this",
3088            Insn::Fixed {
3089                op: Opcode::PushThis,
3090                operands: vec![],
3091            },
3092        );
3093    }
3094
3095    /// Give the function a local `<home_object>`, for an arrow or a static block inside it
3096    /// to read through `super`.
3097    fn provide_home_object_local(&mut self) {
3098        let current = self.stack.len() - 1;
3099        if !self.stack[current].needs_home_object_local {
3100            return;
3101        }
3102        if !self.stack[current]
3103            .vars
3104            .iter()
3105            .any(|var| var.name == HOME_OBJECT)
3106        {
3107            self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
3108        }
3109        self.prepend_initialiser(
3110            HOME_OBJECT,
3111            Insn::Fixed {
3112                op: Opcode::SpecialObject,
3113                operands: vec![Op::Int(4)],
3114            },
3115        );
3116    }
3117
3118    fn provide_self_name(&mut self) {
3119        let current = self.stack.len() - 1;
3120        let Some(name) = self.stack[current].self_name.clone() else {
3121            return;
3122        };
3123        if self.stack[current].self_name_initialized {
3124            return;
3125        }
3126        // Either the body refers to the name, or a nested function already forced the
3127        // binding into existence while being resolved. A direct `eval` can name it
3128        // without mentioning it, so its presence is a third reason: in strict mode
3129        // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
3130        // that only happens if the binding exists.
3131        let declared = self.stack[current].vars.iter().any(|v| v.name == name);
3132        if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
3133            return;
3134        }
3135        self.stack[current].self_name_initialized = true;
3136        self.prepend_binding_with(&name, 2, VarKind::FunctionName);
3137    }
3138
3139    /// Insert `special_object magic` plus the store to `name` at the top of the body.
3140    ///
3141    /// Prepending shifts every label that has been placed, so they are all moved by
3142    /// the number of instructions inserted.
3143    fn prepend_binding(&mut self, name: &str, magic: i32) {
3144        self.prepend_binding_with(name, magic, VarKind::Normal);
3145    }
3146
3147    /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
3148    fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
3149        let current = self.stack.len() - 1;
3150        // A function-expression's own name is immutable in strict mode, which is what
3151        // makes `f = 1` inside a strict body throw instead of being dropped.
3152        let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
3153        self.declare_var(
3154            name,
3155            VarDef {
3156                kind,
3157                is_const,
3158                ..VarDef::var(name)
3159            },
3160        );
3161        let init = [
3162            Insn::Fixed {
3163                op: Opcode::SpecialObject,
3164                operands: vec![Op::Int(magic)],
3165            },
3166            Insn::Var {
3167                // An initialisation, not an assignment: sloppy mode drops stores to a
3168                // function-expression's own name, and the prologue is what puts the
3169                // value there in the first place.
3170                action: if kind == VarKind::FunctionName {
3171                    VarAction::PutInit
3172                } else {
3173                    VarAction::Put
3174                },
3175                name: name.to_string(),
3176                block: 0,
3177                in_params: false,
3178            },
3179        ];
3180        let inserted = init.len();
3181        for (index, instruction) in init.into_iter().enumerate() {
3182            self.stack[current].insns.insert(index, instruction);
3183        }
3184        for placed in self.stack[current].labels.iter_mut().flatten() {
3185            *placed += inserted;
3186        }
3187        // A store sits at the insertion point now, so the `put`/`get` fold must not
3188        // reach across it.
3189        self.stack[current].label_since_insn = true;
3190    }
3191
3192    /// Record a top-level script declaration as a global.
3193    ///
3194    /// A script's top-level `var`/`let`/`function` create properties of the
3195    /// global object, not slots in the script's frame, so they show up as closure
3196    /// variables instead.
3197    fn declare_global(&mut self, name: &str, def: &VarDef) {
3198        let state = self.state();
3199        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
3200            // The name was already referenced, from a function compiled before this
3201            // declaration was reached — `function a(){ b() } function b(){}` resolves
3202            // `b` while `b` is still unknown, and that guess has to be corrected here.
3203            // Leaving it as a plain global meant the declaration was never registered,
3204            // so the binding did not exist at run time and `a()` threw
3205            // `b is not defined`.
3206            if matches!(existing.closure_type, ClosureType::Global) {
3207                existing.closure_type = ClosureType::GlobalDecl;
3208                existing.is_const = def.is_const;
3209                existing.is_lexical = def.is_lexical;
3210            }
3211            return;
3212        }
3213        state.closure_vars.push(ClosureVar {
3214            name: name.to_string(),
3215            is_const: def.is_const,
3216            is_lexical: def.is_lexical,
3217            closure_type: ClosureType::GlobalDecl,
3218            var_idx: 0,
3219        });
3220    }
3221
3222    /// Record a module-level declaration as a module variable.
3223    ///
3224    /// The binding is a closure variable of the module body, so reads and writes are
3225    /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
3226    /// *who fills the cell*: the module record does, before the body runs, and an import
3227    /// points its cell at the exporting module's, which is what makes bindings live and
3228    /// cycles work.
3229    fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
3230        let state = self.state();
3231        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
3232            // The name may have been referenced before this declaration was hoisted,
3233            // which resolved it as a plain global. Correct that here, the way
3234            // `declare_global` does.
3235            if matches!(existing.closure_type, ClosureType::Global) {
3236                existing.closure_type = ClosureType::ModuleDecl;
3237                existing.is_const = def.is_const;
3238                existing.is_lexical = def.is_lexical;
3239            }
3240            return 0;
3241        }
3242        state.closure_vars.push(ClosureVar {
3243            name: name.to_string(),
3244            is_const: def.is_const,
3245            is_lexical: def.is_lexical,
3246            closure_type: ClosureType::ModuleDecl,
3247            var_idx: 0,
3248        });
3249        0
3250    }
3251
3252    /// Declare a module variable and answer its closure-variable index.
3253    ///
3254    /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
3255    /// module variable is not one. The import table needs the real index instead, because
3256    /// that is the position the host writes the cell into.
3257    fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
3258        self.declare_module(name, def);
3259        self.cur()
3260            .closure_vars
3261            .iter()
3262            .position(|c| c.name == name)
3263            .map(|index| index as u32)
3264            .unwrap_or(0)
3265    }
3266
3267    /// Declare one imported binding as a module variable.
3268    ///
3269    /// Returns the closure-variable index, which is what the import table records: the
3270    /// host writes the exporter's cell into that slot before the body runs.
3271    fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
3272        let state = self.state();
3273        if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
3274            // Keep the slot, fix the kind: the name may already have been referenced.
3275            state.closure_vars[index].closure_type = ClosureType::ModuleImport;
3276            state.closure_vars[index].is_const = is_const;
3277            return index as u32;
3278        }
3279        state.closure_vars.push(ClosureVar {
3280            name: name.to_string(),
3281            // An imported binding cannot be assigned: `x = 1` on an import is a
3282            // `TypeError` at run time, which the const flag is what produces.
3283            is_const: true,
3284            // Lexical, so reads go through `get_var_ref_check`: before linking has filled
3285            // the cell an import is in its dead zone, and reading it there must say so
3286            // rather than answer `undefined`.
3287            is_lexical: true,
3288            closure_type: ClosureType::ModuleImport,
3289            var_idx: 0,
3290        });
3291        state.closure_vars.len() as u32 - 1
3292    }
3293
3294    /// Emit the code an `export` needs.
3295    ///
3296    /// Only `export default <expr>` has any: everything else is a table entry whose
3297    /// binding is declared elsewhere. The expression is stored into the hidden
3298    /// `*default*` variable rather than returned, because the module body has no value
3299    /// to speak of.
3300    fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3301        match &decl.kind {
3302            ExportKind::Declaration(stmt) => self.stmt(stmt),
3303            ExportKind::Default(expr) => {
3304                // `export default class Foo {}`: evaluate the declaration (which binds
3305                // `Foo`), then copy its value into the hidden `*default*` binding, because a
3306                // class declaration is a *statement* and `expr` cannot be compiled as one.
3307                if let ExprKind::Class(class) = &expr.kind
3308                    && class.name.is_some()
3309                {
3310                    self.stmt(&Stmt {
3311                        kind: StmtKind::ClassDecl(class.clone()),
3312                        span: expr.span,
3313                    })?;
3314                    let Some(name) = &class.name else {
3315                        return Ok(());
3316                    };
3317                    self.emit_var(VarAction::Get, &name.name);
3318                    let index = self.declare_export_default();
3319                    self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3320                    return Ok(());
3321                }
3322                // A named default function/class is already a module binding; the export
3323                // points at it and there is nothing to evaluate.
3324                if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some()) {
3325                    return Ok(());
3326                }
3327                self.expr(expr)?;
3328                // §16.2.1.10 step 1.b: an *anonymous* default export is named `"default"`
3329                // by `SetFunctionName`, exactly as `var f = function(){}` is named `f`. The
3330                // name is observable — `imported.default.name` — and without this an
3331                // anonymous `export default class {}` arrived with the empty name.
3332                self.set_name_if_anonymous(expr, &Wtf8::new("default"));
3333                let index = self.declare_export_default();
3334                self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3335                Ok(())
3336            }
3337            ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
3338        }
3339    }
3340
3341    /// A module name as the string it denotes.
3342    fn module_name_text(name: &ModuleName) -> &str {
3343        match name {
3344            ModuleName::Ident(ident) => &ident.name,
3345            ModuleName::Str(text) => text,
3346        }
3347    }
3348
3349    /// Bind `import`'s local names and record where each one comes from.
3350    ///
3351    /// Nothing is emitted: an import is not an instruction, it is a promise that the
3352    /// binding's cell will be filled before the body runs. The cell lands in the module's
3353    /// environment at a fixed index, and the host fills it from the exporter's cell —
3354    /// which is why a cyclic import can bind before the other module has evaluated.
3355    fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
3356        let request = self.module_request(&decl.source, &decl.attributes);
3357        for specifier in &decl.specifiers {
3358            let (local, name, is_star) = match specifier {
3359                ImportSpecifier::Default(ident) => {
3360                    (ident.name.clone(), "default".to_string(), false)
3361                }
3362                ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
3363                ImportSpecifier::Named { imported, local } => (
3364                    local.name.clone(),
3365                    Self::module_name_text(imported).to_string(),
3366                    false,
3367                ),
3368            };
3369            // `import * as ns` is *not* a live binding of another module's variable —
3370            // it is a value of its own, which is why the reference declares it like a
3371            // module variable and the host stores the namespace object in that cell.
3372            let var_idx = if is_star {
3373                // `const`: a namespace object is a value, and the binding is immutable.
3374                self.declare_module_var(&local, &VarDef::constant(local.clone()))
3375            } else {
3376                self.declare_import(&local, true)
3377            };
3378            self.module_meta().imports.push(ImportEntry {
3379                module: request,
3380                name,
3381                var_idx,
3382                is_star,
3383            });
3384        }
3385        Ok(())
3386    }
3387
3388    /// Record what an `export` offers, declaring the binding it exports.
3389    ///
3390    /// `export var x = 1` is a declaration like any other; only the table entry is extra.
3391    fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3392        match &decl.kind {
3393            ExportKind::Declaration(stmt) => {
3394                // The inner declaration keeps its own hoisting, then every name it binds
3395                // becomes an export of the same name.
3396                self.hoist_stmt(stmt)?;
3397                let mut names = Vec::new();
3398                Self::declared_names(stmt, &mut names);
3399                for name in names {
3400                    let var_idx = self.module_binding_index(&name);
3401                    self.exports_local(&name, var_idx);
3402                }
3403            }
3404            ExportKind::Default(expr) => {
3405                // The reference puts a default export in a hidden `*default*` variable,
3406                // so `export default function f(){}` can export a *value* while `f` stays
3407                // a binding of the module.
3408                if let ExprKind::Function(func) = &expr.kind
3409                    && let Some(name) = &func.name
3410                {
3411                    let text = name.name.clone();
3412                    self.hoist_stmt(&Stmt {
3413                        kind: StmtKind::FuncDecl(func.clone()),
3414                        span: expr.span,
3415                    })?;
3416                    let var_idx = self.module_binding_index(&text);
3417                    self.module_meta().exports.push(ExportEntry::Local {
3418                        export_name: "default".to_string(),
3419                        var_idx,
3420                    });
3421                    return Ok(());
3422                }
3423                if let ExprKind::Class(class) = &expr.kind
3424                    && class.name.is_some()
3425                {
3426                    // `export default class Foo {}` binds `Foo` in the module scope **and**
3427                    // stores the class into the hidden `*default*` binding — it is a
3428                    // declaration *and* a value, unlike `export default class {}` which is
3429                    // only a value.
3430                    //
3431                    // Pointing the `default` export straight at `Foo` looked simpler and was
3432                    // wrong twice over: `module_binding_index` did not find the lexical
3433                    // binding the hoist had just made, so it declared a second one that
3434                    // nothing ever wrote, and `export_stmt` then had no code to emit for the
3435                    // declaration either. `imported.default` came out `undefined` and `Foo`
3436                    // was not in scope inside its own module.
3437                    self.hoist_stmt(&Stmt {
3438                        kind: StmtKind::ClassDecl(class.clone()),
3439                        span: expr.span,
3440                    })?;
3441                    let var_idx = self.declare_export_default();
3442                    self.exports_local("default", var_idx);
3443                    return Ok(());
3444                }
3445                let var_idx = self.declare_export_default();
3446                self.module_meta().exports.push(ExportEntry::Local {
3447                    export_name: "default".to_string(),
3448                    var_idx,
3449                });
3450            }
3451            ExportKind::Named {
3452                specifiers,
3453                source,
3454                attributes,
3455            } => match source {
3456                Some(source) => {
3457                    let request = self.module_request(source, attributes);
3458                    for specifier in specifiers {
3459                        self.module_meta().exports.push(ExportEntry::Indirect {
3460                            export_name: Self::module_name_text(&specifier.exported).to_string(),
3461                            module: request,
3462                            import_name: Self::module_name_text(&specifier.local).to_string(),
3463                        });
3464                    }
3465                }
3466                None => {
3467                    for specifier in specifiers {
3468                        let local = Self::module_name_text(&specifier.local).to_string();
3469                        let export_name = Self::module_name_text(&specifier.exported).to_string();
3470                        // `export { x }` where `x` is itself an **import** re-exports the
3471                        // binding the import names, not a binding of this module
3472                        // (§16.2.1.6.3: a local export whose local name is imported resolves
3473                        // through the imported module). Recording it as a local made two
3474                        // modules that both forward one import look like two different
3475                        // bindings, and the name was reported ambiguous
3476                        // (`import-and-export-propagates-binding`;
3477                        // `namespace-unambiguous-if-import-star-as-and-export`).
3478                        let closure_names: Vec<String> = self
3479                            .cur()
3480                            .closure_vars
3481                            .iter()
3482                            .map(|var| var.name.clone())
3483                            .collect();
3484                        let forwarded = self
3485                            .module_meta()
3486                            .imports
3487                            .iter()
3488                            .filter(|entry| {
3489                                closure_names
3490                                    .get(entry.var_idx as usize)
3491                                    .is_some_and(|name| *name == local)
3492                            })
3493                            .map(|entry| (entry.module, entry.name.clone(), entry.is_star))
3494                            .find(|(_, name, is_star)| !is_star || name.is_empty());
3495                        if let Some((request, name, is_star)) = forwarded {
3496                            // A namespace import has no export *name* of its own; the
3497                            // resolution is `{ [[Module]]: m, [[BindingName]]: namespace }`,
3498                            // which is what the marker below records.
3499                            let import_name = if is_star {
3500                                "*namespace*".to_string()
3501                            } else {
3502                                name
3503                            };
3504                            self.module_meta().exports.push(ExportEntry::Indirect {
3505                                export_name,
3506                                module: request,
3507                                import_name,
3508                            });
3509                            continue;
3510                        }
3511                        let var_idx = self.module_binding_index(&local);
3512                        self.module_meta().exports.push(ExportEntry::Local {
3513                            export_name,
3514                            var_idx,
3515                        });
3516                    }
3517                }
3518            },
3519            ExportKind::All {
3520                source,
3521                exported,
3522                attributes,
3523            } => {
3524                let request = self.module_request(source, attributes);
3525                match exported {
3526                    Some(name) => {
3527                        self.module_meta().exports.push(ExportEntry::StarAs {
3528                            export_name: Self::module_name_text(name).to_string(),
3529                            module: request,
3530                        });
3531                    }
3532                    None => {
3533                        self.module_meta()
3534                            .exports
3535                            .push(ExportEntry::Star { module: request });
3536                    }
3537                }
3538            }
3539        }
3540        Ok(())
3541    }
3542
3543    /// The names a declaration binds, which is what `export <decl>` exports.
3544    fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
3545        match &stmt.kind {
3546            StmtKind::VarDecl(decl) => {
3547                for declarator in &decl.declarators {
3548                    let mut names = Vec::new();
3549                    declarator.target.bound_names(&mut names);
3550                    out.extend(names.into_iter().map(|name| name.name));
3551                }
3552            }
3553            StmtKind::FuncDecl(func) => {
3554                if let Some(name) = &func.name {
3555                    out.push(name.name.clone());
3556                }
3557            }
3558            StmtKind::ClassDecl(class) => {
3559                if let Some(name) = &class.name {
3560                    out.push(name.name.clone());
3561                }
3562            }
3563            _ => {}
3564        }
3565    }
3566
3567    /// The closure-variable index of a module binding, declaring it if the name was
3568    /// exported without being declared here.
3569    ///
3570    /// `export { x }` where `x` is not declared in the module is a link-time
3571    /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
3572    fn module_binding_index(&mut self, name: &str) -> u32 {
3573        if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
3574            return index as u32;
3575        }
3576        self.declare_module_var(name, &VarDef::lexical(name.to_string()))
3577    }
3578
3579    fn exports_local(&mut self, export_name: &str, var_idx: u32) {
3580        self.module_meta().exports.push(ExportEntry::Local {
3581            export_name: export_name.to_string(),
3582            var_idx,
3583        });
3584    }
3585
3586    /// The hidden `*default*` binding `export default <expr>` stores into.
3587    fn declare_export_default(&mut self) -> u32 {
3588        const DEFAULT: &str = "*default*";
3589        if let Some(index) = self
3590            .cur()
3591            .closure_vars
3592            .iter()
3593            .position(|c| c.name == DEFAULT)
3594        {
3595            return index as u32;
3596        }
3597        self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
3598    }
3599
3600    /// The module tables, which only the top-level state has.
3601    fn module_meta(&mut self) -> &mut ModuleMeta {
3602        self.state()
3603            .module
3604            .as_mut()
3605            .expect("module tables are only touched while compiling a module")
3606    }
3607
3608    /// The index of `specifier`'s request, adding it if it is new.
3609    ///
3610    /// Deduplicated on the specifier *and* its attributes: the same file imported once as
3611    /// JSON and once as text is two modules with two different contents, which is exactly
3612    /// what `hello_module.js` does.
3613    fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
3614        let attributes: Vec<(String, String)> = attributes
3615            .iter()
3616            .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
3617            .collect();
3618        let meta = self.module_meta();
3619        if let Some(index) = meta
3620            .requests
3621            .iter()
3622            .position(|request| request.specifier == specifier && request.attributes == attributes)
3623        {
3624            return index as u32;
3625        }
3626        meta.requests.push(ModuleRequest {
3627            specifier: specifier.to_string(),
3628            attributes,
3629        });
3630        meta.requests.len() as u32 - 1
3631    }
3632
3633    /// Compile a loop body with a `break`/`continue` target pushed for it.
3634    fn loop_body(
3635        &mut self,
3636        body: &Stmt,
3637        labels: &[String],
3638        continue_label: Label,
3639        break_label: Label,
3640    ) -> Result<(), SyntaxError> {
3641        self.push_jump_target(JumpTarget {
3642            names: labels.to_vec(),
3643            break_label: Some(break_label),
3644            continue_label: Some(continue_label),
3645            // A loop leaves nothing of its own on the value stack.
3646            drop_count: 0,
3647            finally_label: None,
3648            is_regular_stmt: false,
3649            has_iterator: false,
3650            is_async_iterator: false,
3651        });
3652        let result = self.stmt(body);
3653        self.pop_jump_target();
3654        result
3655    }
3656
3657    fn push_jump_target(&mut self, target: JumpTarget) {
3658        self.state().jump_targets.push(target);
3659    }
3660
3661    fn pop_jump_target(&mut self) {
3662        self.state().jump_targets.pop();
3663    }
3664
3665    fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3666        let (label, is_break) = match &stmt.kind {
3667            StmtKind::Break(label) => (label.as_ref(), true),
3668            StmtKind::Continue(label) => (label.as_ref(), false),
3669            _ => unreachable!("control_transfer is only called for break and continue"),
3670        };
3671
3672        // Walk outward from the innermost construct. Everything considered before
3673        // the match is a construct control is leaving, and leaving it has a cost:
3674        // its stack slots go, and its finalizer runs.
3675        let targets = self.cur().jump_targets.clone();
3676        for target in targets.iter().rev() {
3677            let destination = match (label, is_break) {
3678                // An unlabelled `break` skips a labelled non-loop statement: `break`
3679                // may name one, but the bare form only means "leave the loop".
3680                (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3681                (None, false) => target.continue_label,
3682                (Some(name), true) => target
3683                    .break_label
3684                    .filter(|_| target.names.contains(&name.name)),
3685                (Some(name), false) => target
3686                    .continue_label
3687                    .filter(|_| target.names.contains(&name.name)),
3688            };
3689
3690            if let Some(destination) = destination {
3691                self.emit_jump(Opcode::Goto, destination, &[]);
3692                return Ok(());
3693            }
3694
3695            // Closing the iterator consumes the three slots the loop keeps on the
3696            // stack (iterator, next method, catch offset), so those are not dropped
3697            // again below.
3698            let mut remaining = target.drop_count;
3699            if target.has_iterator {
3700                self.emit_iterator_close(target.is_async_iterator, false);
3701                remaining = remaining.saturating_sub(3);
3702            }
3703            for _ in 0..remaining {
3704                self.emit(Opcode::Drop, &[]);
3705            }
3706            if let Some(finally) = target.finally_label {
3707                // The finalizer runs as a subroutine and is handed a dummy return
3708                // value, which is dropped afterwards to keep the stack the depth it
3709                // had before.
3710                self.emit(Opcode::Undefined, &[]);
3711                self.emit_jump(Opcode::Gosub, finally, &[]);
3712                self.emit(Opcode::Drop, &[]);
3713            }
3714        }
3715
3716        // The parser rejects a break/continue with no target, so reaching here
3717        // means the compiler's own bookkeeping is wrong.
3718        Err(SyntaxError::new(
3719            if is_break {
3720                "break has no enclosing loop or switch"
3721            } else {
3722                "continue has no enclosing loop"
3723            },
3724            stmt.span,
3725        ))
3726    }
3727
3728    /// Compile a labelled statement.
3729    ///
3730    /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3731    /// that loop's targets, so the chain is collected and handed to the loop. A
3732    /// label on a non-loop statement only provides a `break` target, because
3733    /// `continue` may not target it.
3734    fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3735        let mut names = vec![label.name.clone()];
3736        let mut inner = body;
3737        while let StmtKind::Labeled {
3738            label: next,
3739            body: deeper,
3740        } = &inner.kind
3741        {
3742            names.push(next.name.clone());
3743            inner = deeper;
3744        }
3745        if Self::is_loop(inner) {
3746            return self.stmt_labelled(inner, &names);
3747        }
3748        let end = self.new_label();
3749        self.push_jump_target(JumpTarget {
3750            names,
3751            break_label: Some(end),
3752            continue_label: None,
3753            drop_count: 0,
3754            finally_label: None,
3755            is_regular_stmt: true,
3756            has_iterator: false,
3757            is_async_iterator: false,
3758        });
3759        let result = self.stmt(inner);
3760        self.pop_jump_target();
3761        result?;
3762        self.place_label(end);
3763        let _ = stmt;
3764        Ok(())
3765    }
3766
3767    /// Whether a statement is a loop, i.e. a valid target for `continue`.
3768    fn is_loop(stmt: &Stmt) -> bool {
3769        matches!(
3770            stmt.kind,
3771            StmtKind::While { .. }
3772                | StmtKind::DoWhile { .. }
3773                | StmtKind::For { .. }
3774                | StmtKind::ForIn { .. }
3775                | StmtKind::ForOf { .. }
3776        )
3777    }
3778
3779    /// Compile `switch`.
3780    ///
3781    /// The discriminant is evaluated once and stays on the value stack while the
3782    /// clauses compare against copies of it, so it is dropped at the end — which is
3783    /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3784    /// clause's body jumps over the *next* clause's tests straight into its body.
3785    ///
3786    /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3787    /// the next run's tests. Only the last run's miss reaches the `default` body, or
3788    /// the end of the switch when there is no `default`. That failure path can point
3789    /// backwards (`default` written first), so the runs and their labels are worked
3790    /// out before any code is emitted.
3791    fn switch(
3792        &mut self,
3793        discriminant: &Expr,
3794        cases: &[SwitchCase],
3795        stmt: &Stmt,
3796    ) -> Result<(), SyntaxError> {
3797        self.reset_value();
3798        // The discriminant is evaluated outside the switch's block scope, before
3799        // any `case` clause exists.
3800        self.expr(discriminant)?;
3801
3802        let switch_key = stmt.span.start.offset as u64;
3803        let switch_parent = self.cur().current_block;
3804        self.push_block(switch_key, switch_parent);
3805        self.emit_scope_enter(switch_key);
3806
3807        let break_label = self.new_label();
3808        self.push_jump_target(JumpTarget {
3809            names: Vec::new(),
3810            break_label: Some(break_label),
3811            // `switch` is a valid `break` target but not a `continue` target.
3812            continue_label: None,
3813            // The discriminant stays on the value stack for the whole statement, so
3814            // a `break` aimed further out has to discard it.
3815            drop_count: 1,
3816            finally_label: None,
3817            is_regular_stmt: false,
3818            has_iterator: false,
3819            is_async_iterator: false,
3820        });
3821
3822        // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3823        // its label to the clause after it, so both tests reach the same body.
3824        let mut runs: Vec<(usize, usize)> = Vec::new();
3825        let mut scan = 0;
3826        while scan < cases.len() {
3827            if cases[scan].test.is_some() {
3828                let mut last = scan;
3829                while last + 1 < cases.len()
3830                    && cases[last].test.is_some()
3831                    && cases[last].body.is_empty()
3832                    && cases[last + 1].test.is_some()
3833                {
3834                    last += 1;
3835                }
3836                runs.push((scan, last));
3837                scan = last + 1;
3838            } else {
3839                scan += 1;
3840            }
3841        }
3842
3843        let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3844        let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3845        let default_at = cases.iter().position(|case| case.test.is_none());
3846        // Where the last run sends control when nothing matched.
3847        let miss_target = match default_at {
3848            Some(index) => body_labels[index],
3849            None => break_label,
3850        };
3851
3852        // When `default` comes first, control has to jump over it to reach the
3853        // tests. It only needs to when some clause actually has a test; otherwise
3854        // the default body is the entry point.
3855        let mut entry = None;
3856        if default_at == Some(0) && !runs.is_empty() {
3857            self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3858            entry = Some(run_labels[0]);
3859        }
3860
3861        let mut index = 0;
3862        let mut run = 0;
3863        let result = (|| -> Result<(), SyntaxError> {
3864            while index < cases.len() {
3865                if cases[index].test.is_some() {
3866                    let (first, last) = runs[run];
3867                    // Reaching these tests from the preceding body is a
3868                    // fallthrough, which continues inside the body and skips them.
3869                    if index > 0 {
3870                        self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3871                    }
3872                    if let Some(label) = entry.take() {
3873                        self.place_label(label);
3874                    }
3875                    self.place_label(run_labels[run]);
3876
3877                    for (offset, case) in cases[first..=last].iter().enumerate() {
3878                        let test = case.test.as_ref().unwrap();
3879                        self.emit(Opcode::Dup, &[]);
3880                        self.expr(test)?;
3881                        self.emit(Opcode::StrictEq, &[]);
3882                        if first + offset < last {
3883                            self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3884                        } else {
3885                            // Hand over to the next run's tests, or give up.
3886                            let next = match runs.get(run + 1) {
3887                                Some(_) => run_labels[run + 1],
3888                                None => miss_target,
3889                            };
3890                            self.emit_jump(Opcode::IfFalse, next, &[]);
3891                        }
3892                    }
3893
3894                    self.place_label(body_labels[index]);
3895                    for case in &cases[first..=last] {
3896                        self.stmts(&case.body)?;
3897                    }
3898                    index = last + 1;
3899                    run += 1;
3900                } else {
3901                    // `default`: control arrives here either by falling through or
3902                    // because every test missed.
3903                    self.place_label(body_labels[index]);
3904                    self.stmts(&cases[index].body)?;
3905                    index += 1;
3906                }
3907            }
3908            Ok(())
3909        })();
3910
3911        if result.is_ok() {
3912            self.place_label(break_label);
3913            // Discard the discriminant now that no test needs it.
3914            self.emit(Opcode::Drop, &[]);
3915        }
3916
3917        self.pop_jump_target();
3918        self.emit_scope_leave(switch_key);
3919        self.state().current_block = switch_parent;
3920        result
3921    }
3922
3923    /// Compile `try`/`catch`/`finally`.
3924    ///
3925    /// The shape is an exception table built out of `catch` instructions, each of
3926    /// which records where control goes if the instructions that follow raise:
3927    ///
3928    /// ```text
3929    /// catch HANDLER            <- if the guarded block throws, jump to HANDLER
3930    ///   <guarded block>
3931    ///   drop                   <- discard the catch offset
3932    ///   undefined; gosub FINALLY; drop
3933    ///   goto END
3934    /// HANDLER:
3935    ///   <bind the catch parameter>
3936    ///   catch CATCH2           <- if the handler itself throws, go to CATCH2
3937    ///   <handler body>
3938    ///   drop; undefined; gosub FINALLY; drop; goto END
3939    /// CATCH2:
3940    ///   gosub FINALLY; throw   <- run the finalizer, then let the error out
3941    /// FINALLY:
3942    ///   <finalizer>
3943    ///   ret                    <- return to the `gosub`
3944    /// END:
3945    /// ```
3946    ///
3947    /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
3948    /// of the finalizer serves the normal path, the handler path and the
3949    /// propagating-exception path.
3950    ///
3951    /// The `undefined` before each `gosub` is a dummy return value: the finalizer
3952    /// runs with `ret_value` on the stack, and the normal path has no value to
3953    /// keep, so it pushes one to keep the stack depth identical on every path.
3954    fn try_stmt(
3955        &mut self,
3956        stmt: &Stmt,
3957        block: &[Stmt],
3958        handler: &Option<CatchClause>,
3959        finalizer: Option<&[Stmt]>,
3960    ) -> Result<(), SyntaxError> {
3961        self.reset_value();
3962
3963        let catch_label = self.new_label();
3964        let catch2_label = self.new_label();
3965        let finally_label = self.new_label();
3966        let end_label = self.new_label();
3967
3968        self.emit_jump(Opcode::Catch, catch_label, &[]);
3969
3970        // The guarded block. `break` may not target it, so its entry exists purely
3971        // to unwind: a jump out has to discard the catch offset and run the
3972        // finalizer.
3973        self.push_jump_target(JumpTarget {
3974            names: Vec::new(),
3975            break_label: None,
3976            continue_label: None,
3977            drop_count: 1,
3978            finally_label: Some(finally_label),
3979            is_regular_stmt: false,
3980            has_iterator: false,
3981            is_async_iterator: false,
3982        });
3983
3984        let block_key = Self::try_block_key(stmt, TryPart::Block);
3985        let block_parent = self.cur().current_block;
3986        self.push_block(block_key, block_parent);
3987        self.emit_scope_enter(block_key);
3988        self.stmts(block)?;
3989        self.emit_scope_leave(block_key);
3990        self.state().current_block = block_parent;
3991        // A guarded block that ends in a `return`/`throw` never reaches the
3992        // epilogue, so the reference does not emit one.
3993        self.pop_jump_target();
3994        let block_live = !block.last().is_some_and(Self::terminates);
3995
3996        if block_live {
3997            self.emit(Opcode::Drop, &[]);
3998            self.emit(Opcode::Undefined, &[]);
3999            self.emit_jump(Opcode::Gosub, finally_label, &[]);
4000            self.emit(Opcode::Drop, &[]);
4001            self.emit_jump(Opcode::Goto, end_label, &[]);
4002        }
4003
4004        if let Some(handler) = handler {
4005            self.place_label(catch_label);
4006            // The thrown value is on top of the stack: bind it, or discard it for
4007            // `catch { }`.
4008            match &handler.param {
4009                Some(pattern) => {
4010                    // The stores resolve the names, so they have to run inside the
4011                    // parameter's own scope; otherwise a same-named `catch` further out
4012                    // could win. A `catch` binding is never in the dead zone, so the store
4013                    // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
4014                    let param_key = Self::try_block_key(stmt, TryPart::Param);
4015                    let param_parent = self.cur().current_block;
4016                    self.push_block(param_key, param_parent);
4017                    self.destructure(pattern, Some(VarDeclKind::Var))?;
4018                    self.state().current_block = param_parent;
4019                }
4020                None => self.emit(Opcode::Drop, &[]),
4021            }
4022            self.emit_jump(Opcode::Catch, catch2_label, &[]);
4023
4024            self.push_jump_target(JumpTarget {
4025                names: Vec::new(),
4026                break_label: None,
4027                continue_label: None,
4028                drop_count: 1,
4029                finally_label: Some(finally_label),
4030                is_regular_stmt: false,
4031                has_iterator: false,
4032                is_async_iterator: false,
4033            });
4034            let catch_key = Self::try_block_key(stmt, TryPart::Catch);
4035            let catch_parent = self.cur().current_block;
4036            self.push_block(catch_key, catch_parent);
4037            self.emit_scope_enter(catch_key);
4038            self.stmts(&handler.body)?;
4039            self.emit_scope_leave(catch_key);
4040            self.state().current_block = catch_parent;
4041            self.pop_jump_target();
4042            let handler_live = !handler.body.last().is_some_and(Self::terminates);
4043
4044            if handler_live {
4045                self.emit(Opcode::Drop, &[]);
4046                self.emit(Opcode::Undefined, &[]);
4047                self.emit_jump(Opcode::Gosub, finally_label, &[]);
4048                self.emit(Opcode::Drop, &[]);
4049                self.emit_jump(Opcode::Goto, end_label, &[]);
4050            }
4051
4052            // An error raised inside the handler still has to run the finalizer.
4053            self.place_label(catch2_label);
4054            self.emit_jump(Opcode::Gosub, finally_label, &[]);
4055            self.emit(Opcode::Throw, &[]);
4056        } else {
4057            // `try`/`finally` with no handler: the finalizer runs, then the error
4058            // keeps propagating.
4059            self.place_label(catch_label);
4060            self.emit_jump(Opcode::Gosub, finally_label, &[]);
4061            self.emit(Opcode::Throw, &[]);
4062        }
4063
4064        self.place_label(finally_label);
4065        // Inside the finalizer, leaving has a different cost: the return value and
4066        // the `gosub` return address are both on the stack, and neither finalizer nor
4067        // any outer one may run before the block has finished.
4068        self.push_jump_target(JumpTarget {
4069            names: Vec::new(),
4070            break_label: None,
4071            continue_label: None,
4072            drop_count: 2,
4073            finally_label: None,
4074            is_regular_stmt: false,
4075            has_iterator: false,
4076            is_async_iterator: false,
4077        });
4078        if let Some(finalizer) = finalizer {
4079            let finally_key = Self::try_block_key(stmt, TryPart::Finally);
4080            let finally_parent = self.cur().current_block;
4081            self.push_block(finally_key, finally_parent);
4082            self.emit_scope_enter(finally_key);
4083            self.stmts(finalizer)?;
4084            self.emit_scope_leave(finally_key);
4085            self.state().current_block = finally_parent;
4086        }
4087        self.pop_jump_target();
4088        self.emit(Opcode::Ret, &[]);
4089        self.place_label(end_label);
4090        Ok(())
4091    }
4092
4093    /// Compile `for`/`in` and `for`/`of`.
4094    ///
4095    /// Both keep an enumeration record on the value stack for the whole loop, which
4096    /// is what makes leaving early expensive: the record has to be dropped, or the
4097    /// iterator closed. The layout is
4098    ///
4099    /// ```text
4100    ///   <iterated expression>
4101    ///   for_in_start | for_of_start      <- pushes the record
4102    ///   goto TEST
4103    /// NEXT:
4104    ///   <bind the loop variable>
4105    ///   <body>
4106    /// TEST:
4107    ///   for_in_next | for_of_next 0
4108    ///   if_false NEXT                    <- not finished: next iteration
4109    ///   drop                             <- finished: discard the leftover value
4110    /// BREAK:
4111    ///   drop | iterator_close            <- the one cleanup `break` also uses
4112    /// ```
4113    ///
4114    /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
4115    /// normal exit share one copy — which is why `break` inside the loop emits nothing
4116    /// of its own, and only a jump that passes *through* the loop pays for its record.
4117    fn for_in_of(
4118        &mut self,
4119        stmt: &Stmt,
4120        left: &ForHead,
4121        right: &Expr,
4122        body: &Stmt,
4123        kind: ForLoopKind,
4124        labels: &[String],
4125    ) -> Result<(), SyntaxError> {
4126        self.reset_value();
4127
4128        let loop_key = stmt.span.start.offset as u64;
4129        let loop_parent = self.cur().current_block;
4130        self.push_block(loop_key, loop_parent);
4131        self.emit_scope_enter(loop_key);
4132
4133        // The iterated expression is evaluated inside the loop's scope, after the
4134        // bindings exist in the temporal dead zone.
4135        self.expr(right)?;
4136
4137        let next = self.new_label();
4138        let test = self.new_label();
4139        let break_target = self.new_label();
4140
4141        let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
4142        match kind {
4143            ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
4144            ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
4145            ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
4146        }
4147        self.emit_jump(Opcode::Goto, test, &[]);
4148
4149        self.push_jump_target(JumpTarget {
4150            // `outer: for (x of xs) … break outer` needs the name here. Without it the
4151            // loop had no label to break to, and the compiler reported "break has no
4152            // enclosing loop" for a loop that was plainly enclosing it.
4153            names: labels.to_vec(),
4154            break_label: Some(break_target),
4155            continue_label: Some(test),
4156            // Passing through the loop has to dispose of its record. A `for`/`of`
4157            // record is three slots, and closing the iterator consumes all of them.
4158            drop_count: if has_iterator { 3 } else { 1 },
4159            finally_label: None,
4160            is_regular_stmt: false,
4161            has_iterator,
4162            is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
4163        });
4164
4165        self.place_label(next);
4166        self.bind_loop_variable(left)?;
4167
4168        // The reference marks the body with its own label here. Nothing jumps to it
4169        // once the loop is laid out, but it is not decoration: a label between the
4170        // store and the body is why `put_loc v; get_loc v` does *not* fold into
4171        // `set_loc v` when the body starts by reading the loop variable.
4172        let body_label = self.new_label();
4173        self.place_label(body_label);
4174        // `for (using x of …)` disposes once per iteration, so the body is a disposal
4175        // region rather than the whole loop: the resource is the element that this
4176        // iteration produced.
4177        let using_head = match left {
4178            ForHead::VarDecl(decl) if decl.kind.is_using() => {
4179                let slot =
4180                    decl.declarators
4181                        .first()
4182                        .and_then(|declarator| match &declarator.target.kind {
4183                            PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
4184                            _ => None,
4185                        });
4186                slot.map(|slot| (slot, decl.kind == VarDeclKind::AwaitUsing))
4187            }
4188            _ => None,
4189        };
4190        match using_head {
4191            Some((slot, awaited)) => {
4192                let live = !Self::terminates(body);
4193                self.using_region_around(slot, live, awaited, |compiler| compiler.stmt(body))?;
4194            }
4195            None => self.stmt(body)?,
4196        }
4197
4198        // §14.7.5.6 `ForIn/OfBodyEvaluation` step 6: a `let`/`const` head gets a **fresh
4199        // binding each iteration**, so a closure the body creates keeps that iteration's
4200        // value. `CloseCaptured` is the same instruction the C-style `for` uses: it swaps in
4201        // a new reference cell holding the current value.
4202        //
4203        // The position is the *end* of the body, not the start: closing before the body
4204        // would leave the closures pointing at the cell the next `put_loc` overwrites, and
4205        // `for (const x of [1,2,3]) fs.push(() => x)` answered `2,3,3` instead of `1,2,3`.
4206        for name in Self::loop_binding_names(left) {
4207            let pos = self.cur().cur_pos;
4208            self.state().insns.push(Insn::CloseCaptured {
4209                name,
4210                block: loop_key,
4211            });
4212            self.state().insn_pos.push(pos);
4213        }
4214        self.place_label(test);
4215        match kind {
4216            ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
4217            ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
4218            ForLoopKind::AwaitOf => {
4219                // The reference's shape: step, `await` the result, then unpack it.
4220                self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
4221                self.emit(Opcode::Await, &[]);
4222                self.state().has_await = true;
4223                self.emit(Opcode::IteratorGetValueDone, &[]);
4224            }
4225        }
4226        self.emit_jump(Opcode::IfFalse, next, &[]);
4227        // The loop is finished; `for_xx_next` left an `undefined` behind.
4228        self.emit(Opcode::Drop, &[]);
4229
4230        self.pop_jump_target();
4231        self.place_label(break_target);
4232        if has_iterator {
4233            // A loop that ran to completion finds its iterator slot already cleared (see
4234            // `iterator_get_value_done`), so this closes only an iterator abandoned by a
4235            // `break` that jumped here.
4236            self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
4237        } else {
4238            self.emit(Opcode::Drop, &[]);
4239        }
4240
4241        self.emit_scope_leave(loop_key);
4242        self.state().current_block = loop_parent;
4243        Ok(())
4244    }
4245
4246    /// The names a `for (let … of/in …)` head declares, which need a fresh cell per
4247    /// iteration. An assignment head (`for (x of …)`) declares nothing, so it is empty.
4248    fn loop_binding_names(left: &ForHead) -> Vec<String> {
4249        let ForHead::VarDecl(decl) = left else {
4250            return Vec::new();
4251        };
4252        if decl.kind == VarDeclKind::Var {
4253            return Vec::new();
4254        }
4255        let mut names = Vec::new();
4256        for declarator in &decl.declarators {
4257            let mut idents = Vec::new();
4258            declarator.target.bound_names(&mut idents);
4259            names.extend(idents.into_iter().map(|ident| ident.name));
4260        }
4261        names
4262    }
4263
4264    /// Store the value `for_xx_next` left on the stack into the loop variable.
4265    fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
4266        // A declaration *initialises* the binding, which is what takes a `let` out of
4267        // the temporal dead zone, so the store is the unchecked form. Assigning to a
4268        // binding declared elsewhere is an ordinary write and keeps its check.
4269        let (pattern, action) = match left {
4270            ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
4271            ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
4272        };
4273        match &pattern.kind {
4274            PatternKind::Ident(name) => {
4275                // `for (using x of …)` validates and snapshots each iteration's value
4276                // before the body runs, which is what makes a non-disposable element fail
4277                // on the iteration that produced it rather than at the end of the loop.
4278                if let ForHead::VarDecl(decl) = left
4279                    && decl.kind.is_using()
4280                {
4281                    let method_slot = self
4282                        .using_method_slot(&name.name)
4283                        .expect("a using binding was declared during hoisting");
4284                    self.emit(
4285                        Opcode::UsingCheck,
4286                        &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
4287                    );
4288                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
4289                }
4290                self.emit_var(action, &name.name);
4291                Ok(())
4292            }
4293            // Every other target stores through the same path an assignment pattern
4294            // uses, which is what makes `for (a[0] in obj)` write each key into the
4295            // property instead of refusing the loop outright.
4296            _ => self.destructure(
4297                pattern,
4298                match left {
4299                    ForHead::VarDecl(decl) => Some(decl.kind),
4300                    ForHead::Assign(_) => None,
4301                },
4302            ),
4303        }
4304    }
4305
4306    fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
4307        for declarator in &decl.declarators {
4308            let Some(init) = &declarator.init else {
4309                // `var x;` stays `undefined`. A lexical binding is different: it
4310                // has to be *initialised* to leave the temporal dead zone, so the
4311                // compiler supplies an explicit `undefined`.
4312                if decl.kind.is_lexical() {
4313                    // A lexical binding has to be *initialised* to leave the temporal
4314                    // dead zone, and a destructuring one is no different — `let {a}`
4315                    // with no initialiser is a syntax error, but `let [a] = []` still
4316                    // needs `a` to be initialised from an empty source, which the
4317                    // pattern does on its own.
4318                    self.emit(Opcode::Undefined, &[]);
4319                    self.destructure(&declarator.target, Some(decl.kind))?;
4320                }
4321                continue;
4322            };
4323            match &declarator.target.kind {
4324                PatternKind::Ident(name) => {
4325                    self.expr(init)?;
4326                    self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
4327                    if decl.kind.is_using() {
4328                        // `using_check` validates the value and snapshots its dispose
4329                        // method: `value -> value, method`. The snapshot is what makes a
4330                        // later change to `Symbol.dispose` irrelevant, and validating here
4331                        // is what keeps the body from running at all when the value is not
4332                        // disposable.
4333                        let method_slot = self
4334                            .using_method_slot(&name.name)
4335                            .expect("a using binding was declared during hoisting");
4336                        self.emit(
4337                            Opcode::UsingCheck,
4338                            &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
4339                        );
4340                        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
4341                        self.emit_var(VarAction::PutInit, &name.name);
4342                        continue;
4343                    }
4344                    // A declaration statement produces no value, so nothing is
4345                    // duplicated onto the stack.
4346                    match decl.kind {
4347                        VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
4348                        _ => self.emit_var(VarAction::PutInit, &name.name),
4349                    }
4350                }
4351                _ => {
4352                    // A destructuring declaration keeps nothing on the stack: the
4353                    // pattern consumes the initialiser.
4354                    self.expr(init)?;
4355                    self.destructure(&declarator.target, Some(decl.kind))?;
4356                }
4357            }
4358        }
4359        Ok(())
4360    }
4361
4362    /// Bind a destructuring pattern from the value on top of the stack.
4363    ///
4364    /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
4365    /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
4366    /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
4367    /// *assignment*, where a member expression is a legal target and the store is an
4368    /// ordinary property write.
4369    ///
4370    /// The value is consumed. An assignment expression's own result is the right-hand
4371    /// side, which the caller keeps separately — the spec does not make the pattern's
4372    /// last store produce it.
4373    fn destructure(
4374        &mut self,
4375        pattern: &Pattern,
4376        decl: Option<VarDeclKind>,
4377    ) -> Result<(), SyntaxError> {
4378        match &pattern.kind {
4379            PatternKind::Ident(name) => {
4380                match decl {
4381                    Some(VarDeclKind::Var) | None => {
4382                        self.emit_var(VarAction::Put, &name.name);
4383                    }
4384                    Some(_) => self.emit_var(VarAction::PutInit, &name.name),
4385                }
4386                Ok(())
4387            }
4388            PatternKind::Assign { target, default } => {
4389                // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
4390                // keeps `null`.
4391                //
4392                // The shape is the reference's: test for `undefined`, and when the value is
4393                // present fall **through** to a single store both paths share. The
4394                // alternatives — branching to the store on each side — need a second store
4395                // and a jump between them, which is what the dump used to show.
4396                let has_value = self.new_label();
4397                self.emit(Opcode::Dup, &[]);
4398                self.emit(Opcode::IsUndefined, &[]);
4399                self.emit_jump(Opcode::IfFalse, has_value, &[]);
4400                self.emit(Opcode::Drop, &[]);
4401                self.expr(default)?;
4402                // `var {f = function(){}} = {}` names the function `f`, like a plain
4403                // `var f = function(){}` does. Both pattern forms do it:
4404                // `BindingInitialization` names the value for a *binding* target, and since
4405                // ES2018 `DestructuringAssignmentEvaluation` does the same, so
4406                // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
4407                // no name to give, which is why only an identifier qualifies.
4408                if let PatternKind::Ident(name) = &target.kind {
4409                    self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
4410                }
4411                self.place_label(has_value);
4412                self.destructure(target, decl)
4413            }
4414            PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
4415            PatternKind::Object { properties, rest } => {
4416                self.destructure_object(properties, rest, decl, pattern)
4417            }
4418            PatternKind::Member(member) if decl.is_none() => {
4419                // An assignment pattern may store into a property. The value is on the
4420                // stack, so the receiver and the key go above it and `rot3l`/`swap2`
4421                // put the three in the order `put_array_el`/`put_field` expect.
4422                self.expr(&member.object)?;
4423                match &member.property {
4424                    MemberProp::Ident(name) => {
4425                        // `value obj` -> `obj value`, the order `put_field` takes.
4426                        // Nothing needs to be left behind: a pattern element's value is
4427                        // consumed by its own store.
4428                        self.emit(Opcode::Swap, &[]);
4429                        self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4430                    }
4431                    MemberProp::Computed(index) => {
4432                        self.expr(index)?;
4433                        // `value obj key` -> `obj key value`.
4434                        self.emit(Opcode::Rot3l, &[]);
4435                        self.emit(Opcode::PutArrayEl, &[]);
4436                    }
4437                    MemberProp::Private(name) => {
4438                        // `value obj` -> `obj value`, and the store half of the assignment is
4439                        // the same one `obj.#x = value` uses — only without `insert2`,
4440                        // because a pattern element's value is not wanted back.
4441                        let binding = format!("#{}", name.name);
4442                        let (kind, setter) = self.private_use(&binding, member.span)?;
4443                        self.emit(Opcode::Swap, &[]);
4444                        self.private_store(&binding, kind, setter.as_deref())?;
4445                    }
4446                }
4447                Ok(())
4448            }
4449            PatternKind::Rest(inner) => self.destructure(inner, decl),
4450            PatternKind::Invalid(expr) => {
4451                Err(SyntaxError::new("invalid assignment target", expr.span))
4452            }
4453            _ => Err(SyntaxError::new(
4454                "this destructuring target is not supported by the compiler yet",
4455                pattern.span,
4456            )),
4457        }
4458    }
4459
4460    /// `[…]` on the left: drain an iterator, binding one target per element.
4461    ///
4462    /// A target that stores into a **property** — `[o.p] = it` — has its reference worked
4463    /// out *before* the value is pulled. That ordering is observable twice over
4464    /// (`array-elem-iter-thrw-close`):
4465    ///
4466    /// * `next` must not have been called yet when the reference throws, so
4467    ///   `[ {}[thrower()] ] = iterable` reports `nextCount === 0`;
4468    /// * the iterator must still be closed, because the throw happens while the record is
4469    ///   live — which is `catch_here`'s `catch_offset 0` doing its work.
4470    ///
4471    /// Doing it the other way round — pull the value, then evaluate the reference — got
4472    /// both wrong: an extra `next` call, and, when the reference threw, an iterator that had
4473    /// already been drained past.
4474    fn destructure_array(
4475        &mut self,
4476        elements: &[Option<PatternElement>],
4477        rest: &Option<Box<RestElement>>,
4478        decl: Option<VarDeclKind>,
4479    ) -> Result<(), SyntaxError> {
4480        // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
4481        // pattern accepts any iterable and closes the iterator when the pattern ends
4482        // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
4483        // first because it is on top.
4484        //
4485        // It also counts as an open iterator for `return` and `break`: a pattern is not a
4486        // loop, but the record is live across everything the pattern evaluates, so
4487        // `function* g(){ [ {} = yield ] = it }` resumed with `return()` has to close it
4488        // (`array-elem-iter-rtrn-close`). `emit_unwind_for_return` finds it by this entry
4489        // and `nip_catch` uncovers exactly the `iter next` pairs it left behind.
4490        //
4491        // A `break`/`continue` cannot occur inside a pattern, so `names` and both labels
4492        // are empty and `drop_count` — read only by that unreachable path — keeps the
4493        // reference's 2.
4494        self.push_jump_target(JumpTarget {
4495            names: Vec::new(),
4496            break_label: None,
4497            continue_label: None,
4498            drop_count: 2,
4499            finally_label: None,
4500            is_regular_stmt: false,
4501            has_iterator: true,
4502            is_async_iterator: false,
4503        });
4504        self.emit(Opcode::ForOfStart, &[]);
4505        for element in elements {
4506            match element {
4507                Some(PatternElement::Pattern(pattern)) => {
4508                    match Self::member_element_target(pattern, decl) {
4509                        // A prepared reference sits above the record, so `for_of_next` is
4510                        // told how many values are in the way.
4511                        Some(member) => {
4512                            let extra = self.prepare_member_target(member)?;
4513                            self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4514                            self.emit(Opcode::Drop, &[]);
4515                            self.destructure_prepared(pattern, member)?;
4516                        }
4517                        None => {
4518                            self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4519                            self.emit(Opcode::Drop, &[]);
4520                            self.destructure(pattern, decl)?;
4521                        }
4522                    }
4523                }
4524                Some(PatternElement::Property { span, .. }) => {
4525                    return Err(SyntaxError::new(
4526                        "a property pattern is not a valid array element",
4527                        *span,
4528                    ));
4529                }
4530                // An elision skips the value, which is already on the stack.
4531                None => {
4532                    self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4533                    self.emit(Opcode::Drop, &[]);
4534                    self.emit(Opcode::Drop, &[]);
4535                }
4536            }
4537        }
4538        if let Some(rest) = rest {
4539            // The remaining values go into a fresh array. The target and its running
4540            // index stay on the stack above the iterator, which is what the operand of
4541            // `for_of_next` accounts for: two values sit above the iterator triple.
4542            let prepared = match decl {
4543                None => Self::member_rest_target(rest),
4544                // A binding pattern cannot store into a property.
4545                Some(_) => None,
4546            };
4547            let extra = match prepared {
4548                Some(member) => 2 + self.prepare_member_target(member)?,
4549                None => 2,
4550            };
4551            self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4552            self.emit(Opcode::Push0, &[]);
4553            let top = self.new_label();
4554            self.place_label(top);
4555            self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4556            let done = self.new_label();
4557            self.emit_jump(Opcode::IfTrue, done, &[]);
4558            self.emit(Opcode::DefineArrayEl, &[]);
4559            self.emit(Opcode::Inc, &[]);
4560            self.emit_jump(Opcode::Goto, top, &[]);
4561            self.place_label(done);
4562            self.emit(Opcode::Drop, &[]);
4563            self.emit(Opcode::Drop, &[]);
4564            match prepared {
4565                Some(member) => self.store_member_value(member)?,
4566                None => self.destructure_rest(rest, decl)?,
4567            }
4568        }
4569        self.emit(Opcode::IteratorClose, &[]);
4570        self.pop_jump_target();
4571        Ok(())
4572    }
4573
4574    /// The property an array element stores into, when it stores into one at all.
4575    ///
4576    /// `Assign` is peeled because `[o.p = d] = it` evaluates `o.p`'s reference at the same
4577    /// point `[o.p] = it` does; the default value is applied afterwards, on the pulled
4578    /// value. Nothing deeper is: a nested pattern's own targets are reached by recursing
4579    /// into `destructure`, and those never straddle a `for_of_next`.
4580    fn member_element_target(
4581        pattern: &Pattern,
4582        decl: Option<VarDeclKind>,
4583    ) -> Option<&ast::MemberPattern> {
4584        if decl.is_some() {
4585            return None;
4586        }
4587        match &pattern.kind {
4588            PatternKind::Member(member) => Some(member),
4589            PatternKind::Assign { target, .. } => Self::member_element_target(target, decl),
4590            _ => None,
4591        }
4592    }
4593
4594    /// The same, for a rest element.
4595    fn member_rest_target(rest: &RestElement) -> Option<&ast::MemberPattern> {
4596        match rest {
4597            RestElement::Member(member) => Some(member),
4598            RestElement::Pattern(pattern) => match &pattern.kind {
4599                PatternKind::Member(member) => Some(member),
4600                _ => None,
4601            },
4602        }
4603    }
4604
4605    /// Push a member target's reference — the object, and the key when the property is
4606    /// computed — and answer how many values that put above the iterator record.
4607    fn prepare_member_target(&mut self, member: &ast::MemberPattern) -> Result<i32, SyntaxError> {
4608        self.expr(&member.object)?;
4609        match &member.property {
4610            MemberProp::Ident(_) | MemberProp::Private(_) => Ok(1),
4611            MemberProp::Computed(index) => {
4612                self.expr(index)?;
4613                Ok(2)
4614            }
4615        }
4616    }
4617
4618    /// Store the value on top of the stack through a prepared member reference.
4619    ///
4620    /// `obj value` for a named property, `obj key value` for a computed one — the orders
4621    /// `put_field` and `put_array_el` take, so no reordering is needed here. The `swap` and
4622    /// `rot3l` in [`Compiler::destructure`]'s member case exist only because *it* starts
4623    /// with the value already on the stack.
4624    fn store_member_value(&mut self, member: &ast::MemberPattern) -> Result<(), SyntaxError> {
4625        match &member.property {
4626            MemberProp::Ident(name) => {
4627                self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4628            }
4629            MemberProp::Computed(_) => self.emit(Opcode::PutArrayEl, &[]),
4630            MemberProp::Private(name) => {
4631                let binding = format!("#{}", name.name);
4632                let (kind, setter) = self.private_use(&binding, member.span)?;
4633                self.private_store(&binding, kind, setter.as_deref())?;
4634            }
4635        }
4636        Ok(())
4637    }
4638
4639    /// The value of an array element whose member reference is already prepared.
4640    ///
4641    /// Only the default-value test differs from [`Compiler::destructure`]: the reference
4642    /// and the value are both on the stack while the test runs, which is why the object is
4643    /// evaluated before the default rather than after it.
4644    fn destructure_prepared(
4645        &mut self,
4646        pattern: &Pattern,
4647        member: &ast::MemberPattern,
4648    ) -> Result<(), SyntaxError> {
4649        if let PatternKind::Assign { default, .. } = &pattern.kind {
4650            let has_value = self.new_label();
4651            self.emit(Opcode::Dup, &[]);
4652            self.emit(Opcode::IsUndefined, &[]);
4653            self.emit_jump(Opcode::IfFalse, has_value, &[]);
4654            self.emit(Opcode::Drop, &[]);
4655            self.expr(default)?;
4656            self.place_label(has_value);
4657        }
4658        self.store_member_value(member)
4659    }
4660
4661    /// `{…}` on the left: read properties off one boxed source object.
4662    fn destructure_object(
4663        &mut self,
4664        properties: &[Option<PatternElement>],
4665        rest: &Option<Box<RestElement>>,
4666        decl: Option<VarDeclKind>,
4667        pattern: &Pattern,
4668    ) -> Result<(), SyntaxError> {
4669        // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
4670        // aside for the rest element below.
4671        self.emit(Opcode::ToObject, &[]);
4672        let mut taken: Vec<Wtf8> = Vec::new();
4673        // A computed key's *value* is only known at run time, so with a rest element the
4674        // exclusion list cannot be an `ArrayFrom` over literal atoms. It becomes a hidden
4675        // local array that every key is written into as the pattern is walked — literal
4676        // keys by name, computed ones by the value the expression produced. Without this,
4677        // `let { [k]: a, ...rest } = o` was refused outright.
4678        let needs_key_log = rest.is_some() && computed_key_count(properties) > 0;
4679        let key_log = if needs_key_log {
4680            let name = "<rest_exclude>";
4681            self.declare_hidden_local(name, VarKind::Normal);
4682            self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4683            self.emit_var(VarAction::Put, name);
4684            Some(name)
4685        } else {
4686            None
4687        };
4688        for property in properties {
4689            let Some(PatternElement::Property {
4690                key, value, span, ..
4691            }) = property
4692            else {
4693                return Err(SyntaxError::new(
4694                    "a bare pattern is not a valid object property",
4695                    properties
4696                        .iter()
4697                        .flatten()
4698                        .map(|element| match element {
4699                            PatternElement::Pattern(pattern) => pattern.span,
4700                            PatternElement::Property { span, .. } => *span,
4701                        })
4702                        .next()
4703                        .unwrap_or(pattern.span),
4704                ));
4705            };
4706            // Every read needs the source twice: to read from, and to keep for the next
4707            // property. `get_field2` is that duplicate-and-read in one instruction, but it
4708            // leaves the copy *under* the value, so it is only usable when whatever
4709            // consumes the value tolerates that. See [`reads_with_get_field2`].
4710            let nested = reads_with_get_field2(decl, value);
4711            if !nested {
4712                self.emit(Opcode::Dup, &[]);
4713            }
4714            let slot = taken.len();
4715            match key {
4716                PropName::Literal(literal) => {
4717                    let name = self.property_key_text(literal, *span)?;
4718                    taken.push(name.clone());
4719                    if let Some(log) = &key_log {
4720                        // `arr index key -> arr`: the key is written into the log before
4721                        // the read, so the order of observable operations is unchanged.
4722                        self.emit_var(VarAction::Get, log);
4723                        self.push_number(slot as f64);
4724                        self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&name))]);
4725                        self.emit(Opcode::PutArrayEl, &[]);
4726                    }
4727                    self.emit(
4728                        if nested {
4729                            Opcode::GetField2
4730                        } else {
4731                            Opcode::GetField
4732                        },
4733                        &[Op::Atom(Atom::from_wtf8(&name))],
4734                    );
4735                }
4736                PropName::Computed(index) => {
4737                    self.expr(index)?;
4738                    // `key key`: one stays on the stack for the read, the other goes into
4739                    // the exclusion log. The index is a compile-time constant, so no counter
4740                    // local is needed.
4741                    if let Some(log) = &key_log {
4742                        taken.push(Wtf8::default());
4743                        self.emit(Opcode::Dup, &[]);
4744                        self.emit_var(VarAction::Get, log);
4745                        self.emit(Opcode::Swap, &[]);
4746                        self.push_number(slot as f64);
4747                        self.emit(Opcode::Swap, &[]);
4748                        self.emit(Opcode::PutArrayEl, &[]);
4749                    }
4750                    self.emit(Opcode::GetArrayEl, &[]);
4751                }
4752                PropName::Private(_) => {
4753                    return Err(SyntaxError::new(
4754                        "private fields are not supported by the compiler yet",
4755                        value.span,
4756                    ));
4757                }
4758            }
4759            self.destructure(value, decl)?;
4760        }
4761        match rest {
4762            Some(rest) => {
4763                // `target src exclude`: the exclusion list is an array of the keys the
4764                // literal part already took, so the rest object gets only the others.
4765                self.emit(Opcode::Object, &[]);
4766                self.emit(Opcode::Swap, &[]);
4767                match &key_log {
4768                    // Built while walking the pattern; see `needs_key_log`.
4769                    Some(log) => {
4770                        self.emit_var(VarAction::Get, log);
4771                    }
4772                    None => {
4773                        for name in &taken {
4774                            self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
4775                        }
4776                        self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
4777                    }
4778                }
4779                self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4780                self.emit(Opcode::Drop, &[]);
4781                self.emit(Opcode::Drop, &[]);
4782                self.destructure_rest(rest, decl)?;
4783            }
4784            // The source was only kept for a rest element.
4785            None => self.emit(Opcode::Drop, &[]),
4786        }
4787        Ok(())
4788    }
4789
4790    /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
4791    fn destructure_rest(
4792        &mut self,
4793        rest: &RestElement,
4794        decl: Option<VarDeclKind>,
4795    ) -> Result<(), SyntaxError> {
4796        match rest {
4797            RestElement::Pattern(pattern) => self.destructure(pattern, decl),
4798            // `[...a.b] = c` stores into a property.
4799            RestElement::Member(member) => {
4800                let pattern = Pattern {
4801                    kind: PatternKind::Member(member.clone()),
4802                    span: member.span,
4803                };
4804                self.destructure(&pattern, decl)
4805            }
4806        }
4807    }
4808
4809    /// Compile a function declaration and queue it for instantiation at scope
4810    /// entry.
4811    ///
4812    /// A declaration is visible before the statement that declares it, so the
4813    /// code that creates the function object belongs at the top of the enclosing
4814    /// scope, not at the declaration.
4815    fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
4816        let name = func.name.as_ref().expect("a declaration has a name");
4817        let function = self.compile_function(func)?;
4818        let pool_index = self.push_constant(Constant::Function(Box::new(function)));
4819        let target = self.hoist_target(&name.name);
4820        let block = self.cur().current_block;
4821        self.state().hoisted.push((block, target, pool_index));
4822        Ok(())
4823    }
4824
4825    /// Where a name lives, for a hoisted declaration.
4826    fn hoist_target(&self, name: &str) -> HoistTarget {
4827        let state = self.cur();
4828        if let Some(index) = state.args.iter().position(|a| a.name == name) {
4829            return HoistTarget::Arg(index as u32);
4830        }
4831        if let Some(index) = state.vars.iter().position(|v| v.name == name) {
4832            return HoistTarget::Loc(index as u32);
4833        }
4834        // A global function declaration is not a slot at all.
4835        HoistTarget::Global(name.to_string())
4836    }
4837
4838    // -- expressions -------------------------------------------------------
4839
4840    /// Compile one expression, recording where its instructions sit.
4841    ///
4842    /// The position is the node's operator when it has one and its first token
4843    /// otherwise, and it is restored on the way out so a parent's own instructions —
4844    /// which are emitted *after* its children — are blamed on the parent. Without the
4845    /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4846    fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4847        // `discard_value` belongs to the *statement* that is about to be compiled, so it
4848        // may only be honoured by that statement's own top-level expression. Taking it here
4849        // is what enforces that: `f(x = 1)` sets it for the call, and the assignment inside
4850        // the argument list is a different expression — it must still leave its value on the
4851        // stack. Without this the argument vanished, and `call` then consumed the callee as
4852        // its argument (`TypeError: undefined is not a function` from `f(x = 1)` inside any
4853        // function).
4854        self.discard_root = std::mem::take(&mut self.state().discard_value);
4855        let saved = self.cur().cur_pos;
4856        // Only the node kinds the reference calls `emit_source_pos` for record a position:
4857        // the operator a node exists for, and a variable *read*, which the reference
4858        // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4859        // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4860        // start, a parenthesised group, an anonymous function expression — leaves the
4861        // previous position in place, because a table entry the reference never writes is
4862        // one we must not write either: the instruction that inherits a position (the
4863        // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4864        // report a more recent token than the reference does.
4865        let pos = expr.op_pos.or(match &expr.kind {
4866            ExprKind::Ident(ident) => Some(ident.span.start),
4867            _ => None,
4868        });
4869        match pos {
4870            Some(pos) => self.state().cur_pos = Some(pos),
4871            // A node the reference records nothing for: its own instructions stay
4872            // unpositioned, so they inherit whatever was written last — which is what an
4873            // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4874            // enclosing position instead would blame them on a token the reference has not
4875            // reached yet: a spread's `iterator_open` reports the expression it follows, and
4876            // a template's `to_propkey` the interpolation.
4877            None => self.state().cur_pos = None,
4878        }
4879        // Note a direct `eval` call before compiling it, because the *whole* function
4880        // is affected: an eval can name any binding the function declares, so every one
4881        // of them has to live in a cell for a closure it creates to capture it.
4882        self.note_direct_eval(expr);
4883        let result = self.expr_inner(expr);
4884        self.discard_root = false;
4885        self.state().cur_pos = saved;
4886        result
4887    }
4888
4889    /// Record which bindings are in scope at a direct `eval` call.
4890    ///
4891    /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
4892    /// resolves names from a string at run time, so the only chance to pin down *which*
4893    /// slot a name means is here. Visibility is the lexical rule: a binding counts when
4894    /// its block is the current block, an enclosing one, or the function scope.
4895    fn materialize_eval_sites(&mut self) {
4896        let pending = std::mem::take(&mut self.state().pending_eval_sites);
4897        for (span, site_block, in_params, private, arguments_allowed) in pending {
4898            self.resolve_eval_site(span, site_block, in_params, private, arguments_allowed);
4899        }
4900    }
4901
4902    /// Resolve the bindings visible at one `eval` call.
4903    fn resolve_eval_site(
4904        &mut self,
4905        span: Span,
4906        site_block: u64,
4907        site_in_params: bool,
4908        private_names: Vec<EvalPrivate>,
4909        arguments_allowed: bool,
4910    ) {
4911        /// How near a binding is: function distance first, then block depth, then the
4912        /// later declaration (which shadows the earlier one in the same block).
4913        type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
4914
4915        // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
4916        // walked, innermost function first: a direct `eval` sees every enclosing
4917        // function's bindings, and none of them can be resolved at run time because the
4918        // runtime only has names to go on.
4919        let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
4920        let deepest = self.stack.len() - 1;
4921        for (level, state) in self.stack.iter().enumerate().rev() {
4922            let owner = (deepest - level) as u32;
4923            // The innermost function's block is the one the call sat in, which is not
4924            // the block the compiler is in now; the enclosing functions are still at
4925            // the point where this one was created.
4926            let here = if level == deepest {
4927                site_block
4928            } else {
4929                state.current_block
4930            };
4931            // The chain of live blocks, innermost first, with a depth for each. The walk
4932            // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
4933            // block can start at source offset zero.
4934            let mut live: Vec<(u64, usize)> = vec![(here, 0)];
4935            let mut block = here;
4936            while let Some(parent) = state
4937                .blocks
4938                .iter()
4939                .find(|candidate| candidate.key == block)
4940                .map(|candidate| candidate.parent)
4941                .filter(|parent| *parent != NO_PARENT)
4942                .filter(|parent| parent != &block)
4943            {
4944                live.push((parent, live.len()));
4945                block = parent;
4946            }
4947            let depth_of = |key: u64| {
4948                live.iter()
4949                    .find(|(candidate, _)| *candidate == key)
4950                    .map(|(_, depth)| *depth)
4951                    // The function scope is the outermost depth there is. A binding of a
4952                    // block this site is not inside lands here too, which pushes it
4953                    // behind every live one — the right answer: it is out of scope.
4954                    .unwrap_or(live.len())
4955            };
4956            for (index, arg) in state.args.iter().enumerate() {
4957                bindings.push((
4958                    (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
4959                    EvalVisible {
4960                        name: arg.name.clone(),
4961                        is_arg: true,
4962                        index: index as u32,
4963                        owner,
4964                    },
4965                ));
4966            }
4967            // A parameter list cannot see the body, so a body `var` is not a binding the
4968            // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
4969            // not let that eval write the body's `c`.
4970            let hides_body = if level == deepest {
4971                site_in_params
4972            } else {
4973                state.created_in_params
4974            };
4975            for (index, var) in state.vars.iter().enumerate() {
4976                let block = state
4977                    .var_block
4978                    .get(index)
4979                    .copied()
4980                    .unwrap_or(FUNCTION_SCOPE);
4981                if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
4982                    continue;
4983                }
4984                bindings.push((
4985                    (
4986                        owner as usize,
4987                        depth_of(block),
4988                        std::cmp::Reverse(index as u32),
4989                    ),
4990                    EvalVisible {
4991                        name: var.name.clone(),
4992                        is_arg: false,
4993                        index: index as u32,
4994                        owner,
4995                    },
4996                ));
4997            }
4998        }
4999        // Innermost function first, then innermost block, then the later declaration
5000        // (which shadows the earlier one within a block).
5001        bindings.sort_by_key(|(priority, _)| *priority);
5002        let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
5003        self.state().eval_sites.push(EvalSite {
5004            line: span.start.line,
5005            column: span.start.column,
5006            bindings,
5007            private_names,
5008            arguments_allowed,
5009        });
5010    }
5011
5012    /// The private names visible from the compiler's current position, innermost last.
5013    ///
5014    /// A direct `eval` inherits these because private names are lexically scoped
5015    /// (§15.10.2). Flattened with the **first** occurrence winning as the scopes are walked
5016    /// outermost-first, so a nested class's `#x` shadows an outer class's — the same
5017    /// shadowing `ClassPlan::find` gives a use site inside the body.
5018    fn visible_private_names(&self) -> Vec<EvalPrivate> {
5019        let mut out: Vec<EvalPrivate> = Vec::new();
5020        for scope in &self.private_scopes {
5021            for (name, use_) in scope {
5022                if out.iter().any(|entry| &entry.name == name) {
5023                    continue;
5024                }
5025                out.push(EvalPrivate {
5026                    name: name.clone(),
5027                    kind: match use_.kind {
5028                        PrivateKind::Field => EvalPrivateKind::Field,
5029                        PrivateKind::Method => EvalPrivateKind::Method,
5030                        PrivateKind::Getter => EvalPrivateKind::Getter,
5031                        PrivateKind::Setter => EvalPrivateKind::Setter,
5032                    },
5033                    setter: use_.setter.clone(),
5034                });
5035            }
5036        }
5037        out
5038    }
5039
5040    /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
5041    ///
5042    /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
5043    /// a bare identifier callee counts.
5044    /// Record everything a direct `eval` call site has to tell the runtime.
5045    ///
5046    /// Called from both places a call can be compiled: [`Compiler::expr`] for an ordinary
5047    /// one, and [`Compiler::expr_if_tail_call`] for a `return eval(…)`, which skips `expr`
5048    /// entirely. Missing the tail-call path is not hypothetical — it is why
5049    /// `class C { #m; f() { return eval("this.#m") } }` still failed after the private
5050    /// names were otherwise wired through.
5051    fn note_direct_eval(&mut self, expr: &Expr) {
5052        if !Self::is_direct_eval(expr) {
5053            return;
5054        }
5055        // Every enclosing function is affected too: the eval sees the whole scope chain,
5056        // and a closure it creates can capture a binding of any of them.
5057        // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a cell,
5058        // because the closure the eval builds outlives the loop iteration.
5059        for state in &mut self.stack {
5060            state.has_direct_eval = true;
5061        }
5062        let block = self.cur().current_block;
5063        let in_params = self.cur().in_params;
5064        // The private names are snapshotted **here**, at the call site, not when the sites
5065        // are materialised: materialisation happens once the whole function is compiled, by
5066        // which point every class scope has been popped and the answer would always be
5067        // empty.
5068        let private = self.visible_private_names();
5069        // An arrow has no `arguments` of its own and inherits the restriction from the
5070        // nearest real function: `x = () => { () => eval('arguments') }` is still a
5071        // class field initializer's arrow, and still has no `arguments` to see.
5072        let arguments_allowed = !self
5073            .stack
5074            .iter()
5075            .rev()
5076            .find(|state| !state.is_arrow)
5077            .is_some_and(|state| state.no_arguments_binding);
5078        self.state().pending_eval_sites.push((
5079            expr.span,
5080            block,
5081            in_params,
5082            private,
5083            arguments_allowed,
5084        ));
5085    }
5086
5087    fn is_direct_eval(expr: &Expr) -> bool {
5088        matches!(
5089            &expr.kind,
5090            ExprKind::Call { callee, .. }
5091                if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
5092        )
5093    }
5094
5095    fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
5096        match &expr.kind {
5097            ExprKind::Number(value) => self.push_number(*value),
5098            ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
5099            ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
5100            ExprKind::Null => self.emit(Opcode::Null, &[]),
5101            ExprKind::String(text) => self.push_string(text),
5102            ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
5103            ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
5104            ExprKind::This => self.this_expression(),
5105            ExprKind::NewTarget => self.new_target_expression(),
5106            ExprKind::Paren(inner) => self.expr(inner)?,
5107            ExprKind::Binary { op, left, right } => {
5108                self.expr(left)?;
5109                self.expr(right)?;
5110                self.emit(binary_opcode(*op), &[]);
5111            }
5112            ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
5113            ExprKind::Unary {
5114                op: UnaryOp::Minus,
5115                argument,
5116            } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
5117                let ExprKind::Number(value) = argument.unparen().kind else {
5118                    unreachable!("matched above")
5119                };
5120                // The reference folds a negative literal only when the negation is
5121                // exact in the integer range: `-1` becomes `push_minus1` and
5122                // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
5123                // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
5124                // `-Infinity`, not `Infinity` — and folding a fraction would change
5125                // which instruction the reference emits.
5126                let negated = -value;
5127                // `-2147483648` is deliberately excluded: its magnitude is one past
5128                // `i32::MAX`, so the reference sends it through the constant pool and
5129                // negates at run time instead.
5130                if value > 0.0
5131                    && negated == negated.trunc()
5132                    && negated >= -(i32::MAX as f64)
5133                    && negated < 0.0
5134                {
5135                    self.push_number(negated);
5136                } else {
5137                    self.push_number(value);
5138                    self.emit(Opcode::Neg, &[]);
5139                }
5140            }
5141            ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
5142            ExprKind::Conditional { test, cons, alt } => {
5143                let else_label = self.new_label();
5144                let end_label = self.new_label();
5145                self.expr(test)?;
5146                self.emit_jump(Opcode::IfFalse, else_label, &[]);
5147                self.expr(cons)?;
5148                self.emit_jump(Opcode::Goto, end_label, &[]);
5149                self.place_label(else_label);
5150                self.expr(alt)?;
5151                self.place_label(end_label);
5152            }
5153            ExprKind::Assign { op, target, value } => {
5154                let discard = std::mem::take(&mut self.discard_root);
5155                self.assign(*op, target, value, discard)?
5156            }
5157            ExprKind::Update {
5158                op,
5159                argument,
5160                prefix,
5161            } => self.update(*op, argument, *prefix)?,
5162            ExprKind::Sequence(items) => {
5163                for (index, item) in items.iter().enumerate() {
5164                    self.expr(item)?;
5165                    if index + 1 != items.len() {
5166                        self.emit(Opcode::Drop, &[]);
5167                    }
5168                }
5169            }
5170            ExprKind::Call { .. } => self.chain_link_top(expr)?,
5171            ExprKind::Member { .. } => self.chain_link_top(expr)?,
5172            ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
5173            ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
5174            ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
5175            ExprKind::Template(template) => self.template_literal(template)?,
5176            ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
5177            ExprKind::New { callee, arguments } => {
5178                // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
5179                // The `dup` is not redundant: `call_constructor` takes the
5180                // constructor twice, once as the target and once as `new.target`,
5181                // which is what makes `new.target === C` inside the body.
5182                self.expr(callee)?;
5183                self.emit(Opcode::Dup, &[]);
5184                let args = arguments.as_deref().unwrap_or(&[]);
5185                if Self::has_spread(args) {
5186                    // `C C array`: the duplicated callee is already both the target
5187                    // and `new.target`, so no reordering is needed before `apply 1`.
5188                    self.argument_array(args)?;
5189                    self.emit(Opcode::Apply, &[Op::Int(1)]);
5190                    return Ok(());
5191                }
5192                for argument in args {
5193                    self.expr(argument)?;
5194                }
5195                self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
5196            }
5197            ExprKind::Class(class) => self.class_definition(class, true)?,
5198            ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
5199            ExprKind::Yield { argument, delegate } => {
5200                self.yield_expression(argument.as_deref(), *delegate)?
5201            }
5202            ExprKind::Await(argument) => self.await_expression(argument)?,
5203            ExprKind::RegExp { pattern, flags } => {
5204                // A literal is compiled *here*, at parse time, not when the line runs. The
5205                // spec is explicit that an invalid pattern is an early error (§12.9.4:
5206                // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
5207                // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
5208                // also validates `\p{…}` names: 163 conformance cases are patterns that have
5209                // to be rejected before any code runs.
5210                //
5211                // This is the whole reason the engine lives in its own crate rather than
5212                // inside `quickjs-pure`: the compiler could not depend on the interpreter
5213                // (`pure` depends on `compile`), but both need this.
5214                // The lexer already rejected an unknown or repeated flag, so an unparsable
5215                // flag string here would be a bug in the lexer rather than in the script;
5216                // fall back to the default flags instead of inventing a second message.
5217                let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
5218                let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
5219                    SyntaxError::new(
5220                        format!("invalid regular expression: {}", error.message),
5221                        expr.span,
5222                    )
5223                })?;
5224                // The tree is thrown away and rebuilt when the literal first runs: keeping it
5225                // would mean serialising the syntax tree into the function's constant pool,
5226                // and a literal is created once per evaluation of its expression anyway.
5227                let _ = parsed;
5228                // The pattern and its flags travel as two string constants; `regexp` builds
5229                // the object. A dedicated opcode (rather than a call to the constructor) is
5230                // what the reference does too, so that a literal never goes through the
5231                // public `RegExp` function and its string-coercion rules.
5232                self.push_string(&Wtf8::new(pattern));
5233                self.push_string(&Wtf8::new(flags));
5234                self.emit(Opcode::Regexp, &[]);
5235            }
5236            ExprKind::Arrow(func) => {
5237                let function = self.compile_function(func)?;
5238                let index = self.push_constant(Constant::Function(Box::new(function)));
5239                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5240            }
5241            ExprKind::Function(func) => {
5242                let function = self.compile_function_with_name(func, true)?;
5243                let index = self.push_constant(Constant::Function(Box::new(function)));
5244                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5245            }
5246            // `import.meta`: the host fills a per-module object at link time.
5247            ExprKind::ImportMeta => {
5248                self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
5249            }
5250            // `import("x")` compiles to a two-slot push followed by one opcode: the
5251            // specifier, then the options object. Both are evaluated, in that order, because
5252            // §13.3.10.1 numbers them that way and their side effects are observable — the
5253            // absent second argument is a literal `undefined`, which evaluates to nothing.
5254            ExprKind::ImportCall(specifier, options) => {
5255                self.expr(specifier)?;
5256                match options {
5257                    Some(options) => self.expr(options)?,
5258                    None => {
5259                        self.emit(Opcode::Undefined, &[]);
5260                    }
5261                }
5262                self.emit(Opcode::Import, &[]);
5263            }
5264            ExprKind::PrivateIn { name, object } => {
5265                // `#x in o`: the object, then the binding, then one opcode which decides what
5266                // to do with the second operand. A field's binding holds a symbol and the
5267                // answer is an own-property test; a method's holds a function and the answer
5268                // is a brand check — both live in `private_in`, so the compiler emits the
5269                // same instruction for either.
5270                self.expr(object)?;
5271                self.emit_var(VarAction::Get, &format!("#{}", name.name));
5272                self.emit(Opcode::PrivateIn, &[]);
5273            }
5274            _ => {
5275                return Err(SyntaxError::new(
5276                    "this expression form is not supported by the compiler yet",
5277                    expr.span,
5278                ));
5279            }
5280        }
5281        Ok(())
5282    }
5283
5284    /// Build one array holding the evaluated call arguments, which is how a call
5285    /// containing a spread is compiled: the reference does the same, building the
5286    /// list on the stack and handing it to `apply`.
5287    fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5288        let elements: Vec<Option<ArrayElement>> = arguments
5289            .iter()
5290            .map(|argument| match &argument.unparen().kind {
5291                ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
5292                _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
5293            })
5294            .collect();
5295        self.array_literal(&elements, Span::default())
5296    }
5297
5298    /// Whether any argument is a spread, which is what selects the `apply` form.
5299    fn has_spread(arguments: &[Expr]) -> bool {
5300        arguments
5301            .iter()
5302            .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
5303    }
5304
5305    /// Compile `a${x}b`.
5306    ///
5307    /// A template is a `+` chain built left to right: the leading chunk (or an empty
5308    /// string when the template starts with a substitution), then for each
5309    /// substitution its value, `to_propkey` and `add`, then the following chunk when
5310    /// it is not empty. `to_propkey` is what makes a number or object substitute the
5311    /// way `ToString` would while leaving the result a string for `add` to
5312    /// concatenate.
5313    ///
5314    /// The chunk is an atom rather than a constant-pool string, because a non-empty
5315    /// chunk always lands where a value is pushed and `push_atom_value` is the
5316    /// instruction the reference uses for it; the empty first chunk has its own
5317    /// zero-byte form.
5318    fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
5319        let first = template.quasis.first();
5320        match first.and_then(|quasi| quasi.cooked.clone()) {
5321            Some(text) if !text.is_empty() => {
5322                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5323            }
5324            // Either the template begins with a substitution, or the chunk is
5325            // empty — in both cases the chain needs a string to start from.
5326            _ => self.emit(Opcode::PushEmptyString, &[]),
5327        }
5328        for (index, expression) in template.expressions.iter().enumerate() {
5329            self.expr(expression)?;
5330            self.emit(Opcode::ToPropkey, &[]);
5331            self.emit(Opcode::Add, &[]);
5332            if let Some(text) = template
5333                .quasis
5334                .get(index + 1)
5335                .and_then(|quasi| quasi.cooked.clone())
5336                && !text.is_empty()
5337            {
5338                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5339                self.emit(Opcode::Add, &[]);
5340            }
5341        }
5342        Ok(())
5343    }
5344
5345    /// Compile an object literal.
5346    ///
5347    /// The object is built in place: `object` pushes it, and each property leaves it
5348    /// on the stack with one field more, so no temporary is needed and later
5349    /// properties can overwrite earlier ones.
5350    ///
5351    /// The instruction depends on *how* the property was written, not on what kind
5352    /// of value it holds:
5353    ///
5354    /// | source | instruction |
5355    /// |---|---|
5356    /// | `{ a: v }` | `define_field a` |
5357    /// | `{ __proto__: v }` | `set_proto` |
5358    /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
5359    /// | `{ m() {} }` | `define_method m,4` |
5360    /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
5361    /// | `{ [k]() {} }` | `define_method_computed 4` |
5362    /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
5363    ///
5364    /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
5365    /// key itself, which is why the trailing `drop` is absent there too.
5366    /// `tag`…``: a call whose first argument is the call site's template object.
5367    ///
5368    /// The template object is a frozen array of the cooked chunks with a frozen `raw`
5369    /// array beside it, so `String.raw` can read the source text back. It is a constant
5370    /// because its contents never change; the reference builds one per call site and
5371    /// reuses it, while this builds one per evaluation, which only `tag` code that
5372    /// compares template objects across calls could tell apart.
5373    /// A fresh template site id. See [`Constant::Template`].
5374    fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
5375        let cooked = quasi
5376            .quasis
5377            .iter()
5378            .map(|chunk| chunk.cooked.clone())
5379            .collect();
5380        let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
5381        let index = self.push_constant(Constant::Template {
5382            site: next_template_site(),
5383            cooked,
5384            raw,
5385        });
5386        let count = quasi.expressions.len() + 1;
5387        // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
5388        if let ExprKind::Member {
5389            object, property, ..
5390        } = &tag.unparen().kind
5391        {
5392            self.expr(object)?;
5393            match property {
5394                MemberProp::Ident(name) => {
5395                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
5396                }
5397                MemberProp::Computed(key) => {
5398                    self.expr(key)?;
5399                    self.emit(Opcode::GetArrayEl2, &[]);
5400                }
5401                MemberProp::Private(name) => {
5402                    let binding = format!("#{}", name.name);
5403                    let (kind, _) = self.private_use(&binding, tag.span)?;
5404                    self.private_callee(&binding, kind)?;
5405                }
5406            }
5407            self.emit(Opcode::PushConst, &[Op::Const(index)]);
5408            for expression in &quasi.expressions {
5409                self.expr(expression)?;
5410            }
5411            self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
5412            return Ok(());
5413        }
5414        self.expr(tag)?;
5415        self.emit(Opcode::PushConst, &[Op::Const(index)]);
5416        for expression in &quasi.expressions {
5417            self.expr(expression)?;
5418        }
5419        self.emit(Opcode::Call, &[Op::Int(count as i32)]);
5420        Ok(())
5421    }
5422
5423    fn object_literal(
5424        &mut self,
5425        properties: &[ObjectProperty],
5426        span: Span,
5427    ) -> Result<(), SyntaxError> {
5428        self.emit(Opcode::Object, &[]);
5429        for property in properties {
5430            match property {
5431                ObjectProperty::Spread(value) => {
5432                    // `copy_data_properties` takes the target, the source and an
5433                    // exclusion list; a literal `null` means "exclude nothing".
5434                    // Flag bit 1 copies symbols, bits 2/5 pick the source and the
5435                    // exclusion list by stack offset.
5436                    self.expr(spread_argument(value))?;
5437                    self.emit(Opcode::Null, &[]);
5438                    self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
5439                    self.emit(Opcode::Drop, &[]);
5440                    self.emit(Opcode::Drop, &[]);
5441                }
5442                ObjectProperty::Property {
5443                    key,
5444                    value,
5445                    kind,
5446                    shorthand,
5447                    span: property_span,
5448                } => match key {
5449                    PropName::Computed(key_expr) => {
5450                        self.expr(key_expr)?;
5451                        match kind {
5452                            PropertyKind::Value => {
5453                                self.emit(Opcode::ToPropkey, &[]);
5454                                self.expr(value)?;
5455                                self.set_name_if_anonymous_computed(value);
5456                                self.emit(Opcode::DefineArrayEl, &[]);
5457                                // `define_array_el` leaves the object and the key;
5458                                // the key is no longer needed.
5459                                self.emit(Opcode::Drop, &[]);
5460                            }
5461                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5462                                self.emit_method_function(value)?;
5463                                self.emit(
5464                                    Opcode::DefineMethodComputed,
5465                                    &[Op::Int(define_method_flags(*kind))],
5466                                );
5467                            }
5468                        }
5469                    }
5470                    PropName::Literal(key) => {
5471                        let name = self.property_key_text(key, *property_span)?;
5472                        match kind {
5473                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5474                                self.emit_method_function(value)?;
5475                                self.emit(
5476                                    Opcode::DefineMethod,
5477                                    &[
5478                                        Op::Atom(Atom::from_wtf8(&name)),
5479                                        Op::Int(define_method_flags(*kind)),
5480                                    ],
5481                                );
5482                            }
5483                            PropertyKind::Value => {
5484                                self.expr(value)?;
5485                                // `{__proto__: x}` sets the prototype instead of
5486                                // creating a property; the shorthand `{__proto__}`
5487                                // is an ordinary property and does not.
5488                                if name == "__proto__" && !shorthand {
5489                                    self.emit(Opcode::SetProto, &[]);
5490                                } else {
5491                                    self.set_name_if_anonymous(value, &name);
5492                                    self.emit(
5493                                        Opcode::DefineField,
5494                                        &[Op::Atom(Atom::from_wtf8(&name))],
5495                                    );
5496                                }
5497                            }
5498                        }
5499                    }
5500                    PropName::Private(_) => {
5501                        return Err(SyntaxError::new(
5502                            "private names are not valid in object literals",
5503                            *property_span,
5504                        ));
5505                    }
5506                },
5507            }
5508        }
5509        let _ = span;
5510        Ok(())
5511    }
5512
5513    /// Emit the function a method/accessor property defines.
5514    fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
5515        self.expr(value)
5516    }
5517
5518    /// The name a literal property key contributes.
5519    ///
5520    /// String keys are used as written. A numeric key is converted the way
5521    /// `ToString` would convert it, because the atom is made from that spelling:
5522    /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
5523    fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
5524        match key {
5525            PropKey::Str(text) => Ok(text.clone()),
5526            PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
5527        }
5528    }
5529
5530    /// Compile an optional chain.
5531    ///
5532    /// `?.` short-circuits the *whole remaining spine*, not just its own link:
5533    /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
5534    /// `undefined`. So the chain is compiled with one end label and every guard
5535    /// jumps to it. The parser hands us the extent of that spine as an
5536    /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
5537    /// exactly the scope the label has to cover.
5538    fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
5539        let end = self.new_label();
5540        self.chain_link(inner, end)?;
5541        self.place_label(end);
5542        Ok(())
5543    }
5544
5545    /// A member access or call reached from outside any optional chain.
5546    ///
5547    /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
5548    /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
5549    /// still created because [`Self::chain_link`] takes it, and placing it at the
5550    /// end is a no-op that keeps a single code path.
5551    fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
5552        let end = self.new_label();
5553        self.chain_link(expr, end)?;
5554        self.place_label(end);
5555        Ok(())
5556    }
5557
5558    /// One link of a chain, where `end` is the label a `?.` guard jumps to.
5559    fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
5560        match &expr.kind {
5561            ExprKind::Member {
5562                object,
5563                property,
5564                optional,
5565            } => {
5566                // `super.x` is not a lookup on a value: it starts at the home object's
5567                // prototype and keeps `this` as the receiver, so it cannot go through
5568                // `chain_link` and the ordinary field read.
5569                if matches!(object.unparen().kind, ExprKind::SuperProp) {
5570                    self.super_base();
5571                    match property {
5572                        MemberProp::Ident(name) => self.emit(
5573                            Opcode::PushAtomValue,
5574                            &[Op::Atom(Atom::from_text(&name.name))],
5575                        ),
5576                        MemberProp::Computed(index) => self.expr(index)?,
5577                        MemberProp::Private(_) => {
5578                            return Err(SyntaxError::new(
5579                                "private fields are not supported by the compiler yet",
5580                                expr.span,
5581                            ));
5582                        }
5583                    }
5584                    self.emit(Opcode::GetSuperValue, &[]);
5585                    return Ok(());
5586                }
5587                self.chain_link(object, end)?;
5588                if *optional {
5589                    self.optional_guard(end);
5590                }
5591                match property {
5592                    // `.length` has its own opcode. The reference emits it for every
5593                    // object, not just arrays, so a name-based rule is right and
5594                    // cheaper than the generic field read.
5595                    MemberProp::Ident(name) if name.name == "length" => {
5596                        self.emit(Opcode::GetLength, &[]);
5597                    }
5598                    MemberProp::Ident(name) => {
5599                        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
5600                    }
5601                    MemberProp::Computed(index) => {
5602                        self.expr(index)?;
5603                        self.emit(Opcode::GetArrayEl, &[]);
5604                    }
5605                    MemberProp::Private(name) => {
5606                        // The binding comes from the class scope, so a read from outside the
5607                        // class cannot name it at all. `?.` checks the object, not the field:
5608                        // `o?.#x` guards on `o` being nullish.
5609                        let binding = format!("#{}", name.name);
5610                        let (kind, _) = self.private_use(&binding, expr.span)?;
5611                        self.private_load(&binding, kind, expr.span)?;
5612                    }
5613                }
5614                Ok(())
5615            }
5616            ExprKind::Call {
5617                callee,
5618                arguments,
5619                optional,
5620            } => {
5621                // `o.m(args)` has to pass `o` as `this`, which a plain `call`
5622                // cannot: it reads the function and then calls it with no
5623                // receiver at all. The reference's answer is to keep the object
5624                // under the function value — `get_field2` reads a field and leaves
5625                // its base in place — and to use `call_method`, which takes the
5626                // receiver from the stack. Missing this does not just cost an
5627                // instruction, it loses the `this` binding.
5628                if let ExprKind::Member {
5629                    object,
5630                    property,
5631                    optional: member_optional,
5632                } = &callee.unparen().kind
5633                {
5634                    // `super.m()` reads the method off the home object's prototype but
5635                    // calls it with `this`, so the receiver goes under the read instead of
5636                    // being replaced by it.
5637                    if matches!(object.unparen().kind, ExprKind::SuperProp) {
5638                        self.super_base();
5639                        match property {
5640                            MemberProp::Ident(name) => self.emit(
5641                                Opcode::PushAtomValue,
5642                                &[Op::Atom(Atom::from_text(&name.name))],
5643                            ),
5644                            MemberProp::Computed(index) => self.expr(index)?,
5645                            MemberProp::Private(_) => {
5646                                return Err(SyntaxError::new(
5647                                    "private fields are not supported by the compiler yet",
5648                                    expr.span,
5649                                ));
5650                            }
5651                        }
5652                        // The two-output form would drop the receiver; this one replaces
5653                        // the prototype and the key, leaving `this` underneath.
5654                        self.emit(Opcode::GetArrayEl, &[]);
5655                        if Self::has_spread(arguments) {
5656                            self.argument_array(arguments)?;
5657                            self.emit(Opcode::Perm3, &[]);
5658                            self.emit(Opcode::Apply, &[Op::Int(0)]);
5659                            return Ok(());
5660                        }
5661                        for argument in arguments {
5662                            self.expr(argument)?;
5663                        }
5664                        self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5665                        return Ok(());
5666                    }
5667                    self.chain_link(object, end)?;
5668                    if *member_optional {
5669                        self.optional_guard(end);
5670                    }
5671                    match property {
5672                        MemberProp::Ident(name) => {
5673                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5674                        }
5675                        MemberProp::Computed(index) => {
5676                            self.expr(index)?;
5677                            // The key is not needed after the read, so this is the
5678                            // two-output form: object, value.
5679                            self.emit(Opcode::GetArrayEl2, &[]);
5680                        }
5681                        MemberProp::Private(name) => {
5682                            // The receiver is already under the callee, which is exactly the
5683                            // shape `call_method` and `apply` want — so nothing is dropped.
5684                            let binding = format!("#{}", name.name);
5685                            let (kind, _) = self.private_use(&binding, expr.span)?;
5686                            self.private_callee(&binding, kind)?;
5687                        }
5688                    }
5689                    if Self::has_spread(arguments) {
5690                        // Stack is `obj func`; the array goes on top, then `perm3`
5691                        // reorders to the `func this array` that `apply` wants.
5692                        self.argument_array(arguments)?;
5693                        self.emit(Opcode::Perm3, &[]);
5694                        self.emit(Opcode::Apply, &[Op::Int(0)]);
5695                        return Ok(());
5696                    }
5697                    for argument in arguments {
5698                        self.expr(argument)?;
5699                    }
5700                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5701                    return Ok(());
5702                }
5703                // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
5704                // with `get_field2` so the base stays under it, and on the short-circuit
5705                // path pushes an extra `undefined` as a placeholder receiver — the call
5706                // then throws, which is what calling a missing optional chain should do.
5707                if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
5708                    && let ExprKind::Member {
5709                        object,
5710                        property,
5711                        optional: member_optional,
5712                    } = &inner.unparen().kind
5713                {
5714                    let call = self.new_label();
5715                    // A guard target of its own: the outer `end` skips the whole
5716                    // expression, and a short-circuited receiver still has to reach the
5717                    // call so that calling it throws.
5718                    let short = self.new_label();
5719                    self.chain_link(object, end)?;
5720                    if *member_optional {
5721                        self.optional_guard(short);
5722                    }
5723                    match property {
5724                        MemberProp::Ident(name) => {
5725                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5726                        }
5727                        MemberProp::Computed(index) => {
5728                            self.expr(index)?;
5729                            self.emit(Opcode::GetArrayEl2, &[]);
5730                        }
5731                        MemberProp::Private(name) => {
5732                            let binding = format!("#{}", name.name);
5733                            let (kind, _) = self.private_use(&binding, expr.span)?;
5734                            self.private_callee(&binding, kind)?;
5735                        }
5736                    }
5737                    self.emit_jump(Opcode::Goto, call, &[]);
5738                    self.place_label(short);
5739                    self.emit(Opcode::Undefined, &[]);
5740                    self.place_label(call);
5741                    if Self::has_spread(arguments) {
5742                        self.argument_array(arguments)?;
5743                        self.emit(Opcode::Perm3, &[]);
5744                        self.emit(Opcode::Apply, &[Op::Int(0)]);
5745                        return Ok(());
5746                    }
5747                    for argument in arguments {
5748                        self.expr(argument)?;
5749                    }
5750                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5751                    return Ok(());
5752                }
5753                self.chain_link(callee, end)?;
5754                if *optional {
5755                    self.optional_guard(end);
5756                }
5757                if Self::has_spread(arguments) {
5758                    // `func array -> func undefined array`, which is the plain-call
5759                    // form of `apply`: the receiver is `undefined`.
5760                    self.argument_array(arguments)?;
5761                    self.emit(Opcode::Undefined, &[]);
5762                    self.emit(Opcode::Swap, &[]);
5763                    self.emit(Opcode::Apply, &[Op::Int(0)]);
5764                    return Ok(());
5765                }
5766                for argument in arguments {
5767                    self.expr(argument)?;
5768                }
5769                self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
5770                Ok(())
5771            }
5772            _ => self.expr(expr),
5773        }
5774    }
5775
5776    /// Compile `expr` as a tail call when it is one, reporting whether it was.
5777    ///
5778    /// `tail_call` reuses the current frame instead of pushing a new one, so a
5779    /// tail-recursive function runs in constant stack space. It also has to be the
5780    /// *last* thing the function does, which is why only a `return` reaches here.
5781    fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
5782        let ExprKind::Call {
5783            callee,
5784            arguments,
5785            optional: false,
5786        } = &expr.unparen().kind
5787        else {
5788            return Ok(false);
5789        };
5790        // A spread call has no tail form: `tail_call` takes its arguments one at a time off
5791        // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
5792        // as an ordinary call costs the one frame the optimisation was saving and keeps the
5793        // semantics — the alternative was reaching the spread expression below and failing
5794        // with "this expression form is not supported", which is how `return super.m(...a)`
5795        // stopped compiling. Checked before anything is emitted, because the decision cannot
5796        // be taken back once `super_base` or a `get_field2` is on the stack.
5797        if Self::has_spread(arguments) {
5798            return Ok(false);
5799        }
5800        let end = self.new_label();
5801        if let ExprKind::Member {
5802            object,
5803            property,
5804            optional: false,
5805        } = &callee.unparen().kind
5806        {
5807            // `super.m()` in tail position is still an ordinary method call with `this`
5808            // as the receiver; only the read of the method differs.
5809            if matches!(object.unparen().kind, ExprKind::SuperProp) {
5810                self.super_base();
5811                match property {
5812                    MemberProp::Ident(name) => self.emit(
5813                        Opcode::PushAtomValue,
5814                        &[Op::Atom(Atom::from_text(&name.name))],
5815                    ),
5816                    MemberProp::Computed(index) => self.expr(index)?,
5817                    MemberProp::Private(_) => return Ok(false),
5818                }
5819                self.emit(Opcode::GetArrayEl, &[]);
5820                for argument in arguments {
5821                    self.expr(argument)?;
5822                }
5823                self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5824                self.place_label(end);
5825                return Ok(true);
5826            }
5827            self.chain_link(object, end)?;
5828            match property {
5829                MemberProp::Ident(name) => {
5830                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5831                }
5832                MemberProp::Computed(index) => {
5833                    self.expr(index)?;
5834                    self.emit(Opcode::GetArrayEl2, &[]);
5835                }
5836                MemberProp::Private(_) => return Ok(false),
5837            }
5838            for argument in arguments {
5839                self.expr(argument)?;
5840            }
5841            self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5842            self.place_label(end);
5843            return Ok(true);
5844        }
5845        self.chain_link(callee, end)?;
5846        for argument in arguments {
5847            self.expr(argument)?;
5848        }
5849        self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
5850        self.place_label(end);
5851        Ok(true)
5852    }
5853
5854    /// The `?.` guard: keep the value if it is neither null nor undefined,
5855    /// otherwise replace it with `undefined` and leave the whole chain.
5856    fn optional_guard(&mut self, end: Label) {
5857        let cont = self.new_label();
5858        self.emit(Opcode::Dup, &[]);
5859        self.emit(Opcode::IsUndefinedOrNull, &[]);
5860        self.emit_jump(Opcode::IfFalse, cont, &[]);
5861        self.emit(Opcode::Drop, &[]);
5862        self.emit(Opcode::Undefined, &[]);
5863        self.emit_jump(Opcode::Goto, end, &[]);
5864        self.place_label(cont);
5865    }
5866
5867    fn push_number(&mut self, value: f64) {
5868        // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
5869        // goes into the constant pool.
5870        if value == value.trunc() && value.abs() <= i32::MAX as f64 {
5871            let int = value as i32;
5872            if (-1..=7).contains(&int) {
5873                self.emit(Opcode::PushI32, &[Op::Int(int)]);
5874                return;
5875            }
5876            if (-128..=127).contains(&int) {
5877                self.emit(Opcode::PushI8, &[Op::Int(int)]);
5878                return;
5879            }
5880            if (-32768..=32767).contains(&int) {
5881                self.emit(Opcode::PushI16, &[Op::Int(int)]);
5882                return;
5883            }
5884            self.emit(Opcode::PushI32, &[Op::Int(int)]);
5885            return;
5886        }
5887        let index = self.push_constant(Constant::Number(value));
5888        self.emit(Opcode::PushConst, &[Op::Const(index)]);
5889    }
5890
5891    /// Push a `BigInt` literal.
5892    ///
5893    /// A value that fits an `i32` uses the immediate form, which is what the reference
5894    /// emits too; anything larger goes into the constant pool, because the operand of
5895    /// `push_bigint` is only four bytes wide.
5896    fn push_bigint(&mut self, digits: &str, radix: u32) {
5897        if radix == 10
5898            && let Ok(value) = digits.parse::<i64>()
5899            && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
5900        {
5901            self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
5902            return;
5903        }
5904        let index = self.push_constant(Constant::BigInt {
5905            digits: digits.to_string(),
5906            radix,
5907        });
5908        self.emit(Opcode::PushConst, &[Op::Const(index)]);
5909    }
5910
5911    fn push_string(&mut self, text: &Wtf8) {
5912        if text.is_empty() {
5913            self.emit(Opcode::PushEmptyString, &[]);
5914            return;
5915        }
5916        self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
5917    }
5918
5919    /// Name an anonymous function from the binding it is assigned to.
5920    ///
5921    /// `var f = function(){}` produces a function whose `name` is `f`, which the
5922    /// runtime cannot know without being told: the function object is created
5923    /// before the store. `set_name` carries the name across.
5924    fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
5925        if !value.is_anonymous_function_definition() {
5926            return;
5927        }
5928        // A class cannot use `set_name`, because its static field initialisers have already
5929        // run by the time the store happens and they can see `this.name`:
5930        // `var E = class { static f = this.name }` has to answer `"E"`. The reference patches
5931        // the `define_class` instruction's name operand instead, which is why
5932        // `set_class_name` is a compile-time marker with no runtime effect
5933        // (`class-name-static-initializer-anonymous`).
5934        if matches!(value.unparen().kind, ExprKind::Class(_)) {
5935            if let Some(index) = self.last_define_class() {
5936                let atom = Atom::from_wtf8(name);
5937                if let Some(Insn::Fixed { operands, .. }) = self.state().insns.get_mut(index) {
5938                    // `define_class <atom> <flags>`: the name is operand 0.
5939                    operands[0] = Op::Atom(atom);
5940                }
5941            }
5942            return;
5943        }
5944        self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
5945    }
5946
5947    /// The index of the most recent `define_class` in this function's instruction stream.
5948    ///
5949    /// A backwards scan, because everything the class body emitted for the *enclosing*
5950    /// function is still there after it — the static initialiser's call, the class
5951    /// binding's store, `leave_scope` — and only the `define_class` carries the name.
5952    fn last_define_class(&self) -> Option<usize> {
5953        self.cur().insns.iter().rposition(|insn| {
5954            matches!(
5955                insn,
5956                Insn::Fixed {
5957                    op: Opcode::DefineClass,
5958                    ..
5959                }
5960            )
5961        })
5962    }
5963
5964    /// The same, for a computed key: the name comes from the value on the stack
5965    /// rather than from an atom, so a different instruction carries it.
5966    fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
5967        if value.is_anonymous_function_definition() {
5968            self.emit(Opcode::SetNameComputed, &[]);
5969        }
5970    }
5971
5972    /// Compile a function body that exists only in the compiler's head — a class's
5973    /// implicit constructor or its field initialiser.
5974    ///
5975    /// Everything structural is the same as a written function: a fresh `FnState`, its
5976    /// own body block, and resolution while the frame is still on the stack. Only the
5977    /// statements differ.
5978    fn compile_synthetic_function(
5979        &mut self,
5980        name: &str,
5981        strict: bool,
5982        span: Span,
5983        body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
5984    ) -> Result<CompiledFunction, SyntaxError> {
5985        let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
5986        state.span = Some((span.start.offset as usize, span.end.offset as usize));
5987        state.strict = strict;
5988        state.created_in_block = self.cur().current_block;
5989        state.with_names = self.cur().with_names.clone();
5990        state.line = span.start.line;
5991        state.column = span.start.column;
5992        let depth = self.stack.len();
5993        self.stack.push(state);
5994        let body_key = span.start.offset as u64;
5995        self.push_block(body_key, NO_PARENT);
5996        self.state().body_block = body_key;
5997        let result = (|| {
5998            self.emit_scope_enter(body_key);
5999            body(self)?;
6000            if self.end_is_reachable() {
6001                self.emit(Opcode::ReturnUndef, &[]);
6002            }
6003            Ok(())
6004        })();
6005        if result.is_err() {
6006            self.stack.truncate(depth);
6007            return result.map(|()| unreachable!());
6008        }
6009        Ok(self.finish_current())
6010    }
6011
6012    /// The implicit return of a class constructor.
6013    ///
6014    /// A constructor that falls off the end initialises its instance fields first, and a
6015    /// derived one returns `this` — which is what makes `new D()` the object `super()`
6016    /// built rather than `undefined`.
6017    fn emit_class_constructor_tail(&mut self) {
6018        match self.cur().ctor_kind {
6019            CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
6020            // Nothing to install: a base constructor did it in its prologue and a derived
6021            // one at each `super()` site, which is where `this` first exists.
6022            CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
6023            CtorKind::Derived => {
6024                // `get_loc_check` rather than `get_loc`: reaching the end without ever
6025                // running `super()` is a ReferenceError, not `undefined`.
6026                self.emit_var(VarAction::Get, "this");
6027                self.emit(Opcode::Return, &[]);
6028            }
6029        }
6030    }
6031
6032    /// `yield expr` / `yield* expr`.
6033    ///
6034    /// The suspension itself is one instruction: the value is on the stack, `yield` hands
6035    /// it to the caller and parks the frame. On resume the stack holds the value the
6036    /// caller passed *and* a "magic" number saying which method resumed it — `next`
6037    /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
6038    /// `if_false <continue>` asks whether this was an ordinary `next`:
6039    ///
6040    /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
6041    /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
6042    ///   and uses the value sitting under the magic number.
6043    ///
6044    /// A `throw` never reaches here: the interpreter unwinds instead (see
6045    /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
6046    fn yield_expression(
6047        &mut self,
6048        argument: Option<&Expr>,
6049        delegate: bool,
6050    ) -> Result<(), SyntaxError> {
6051        if delegate {
6052            return self.yield_star(argument);
6053        }
6054        // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
6055        // does the same for the `return(v)` that can resume it — which is why an async
6056        // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
6057        // generator's is just `yield`.
6058        let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
6059        match argument {
6060            Some(value) => self.expr(value)?,
6061            None => self.emit(Opcode::Undefined, &[]),
6062        }
6063        if is_async {
6064            self.emit(Opcode::Await, &[]);
6065            self.state().has_await = true;
6066        }
6067        self.emit(Opcode::Yield, &[]);
6068        let resume = self.new_label();
6069        self.emit_jump(Opcode::IfFalse, resume, &[]);
6070        // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
6071        // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
6072        // finished the generator and never ran the `finally`.
6073        if is_async {
6074            self.emit(Opcode::Await, &[]);
6075        }
6076        self.emit_unwind_for_return(true);
6077        self.emit(Opcode::ReturnAsync, &[]);
6078        self.place_label(resume);
6079        // Nothing is emitted here: the value the caller passed to `next` *is* the value
6080        // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
6081        // it through the ordinary expression-statement discard.
6082        Ok(())
6083    }
6084
6085    /// `yield* iterable`.
6086    ///
6087    /// The shape is the reference's, and it is a fall-through chain rather than a
6088    /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
6089    /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
6090    /// the inner iterator and finishes, `throw` forwards the exception into it and
6091    /// continues only if it has a `throw` method.
6092    ///
6093    /// The stack is `iter next catch value` throughout, `catch` being the offset
6094    /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
6095    fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
6096        match argument {
6097            Some(value) => self.expr(value)?,
6098            // The parser rejects a bare `yield*`, so this is unreachable in practice.
6099            None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
6100        }
6101        // `for await of` is the same protocol as `for of` with two differences that matter
6102        // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
6103        // every `next()` result is a promise the delegate has to await.
6104        let is_async = self.cur().kind.is_async();
6105        self.emit(
6106            if is_async {
6107                Opcode::ForAwaitOfStart
6108            } else {
6109                Opcode::ForOfStart
6110            },
6111            &[],
6112        );
6113        self.emit(Opcode::Drop, &[]);
6114        self.emit(Opcode::Undefined, &[]);
6115        self.emit(Opcode::Undefined, &[]);
6116        let next = self.new_label();
6117        let resume = self.new_label();
6118        let finished = self.new_label();
6119        let rethrow = self.new_label();
6120        let throw_no_method = self.new_label();
6121        let done = self.new_label();
6122        self.place_label(next);
6123        self.emit(Opcode::IteratorNext, &[]);
6124        if is_async {
6125            self.emit(Opcode::Await, &[]);
6126            self.state().has_await = true;
6127        }
6128        self.emit(Opcode::IteratorCheckObject, &[]);
6129        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6130        self.emit_jump(Opcode::IfTrue, done, &[]);
6131        // The suspension. `resume` is both the label the return path jumps back to in order
6132        // to yield one more value and where the caller's answer arrives, as the value
6133        // followed by the magic number.
6134        //
6135        // The two forms differ in what they hand the suspension: `yield_star` takes the
6136        // result object itself, `async_yield_star` takes `.value`, because an async
6137        // generator awaits and re-wraps whatever it yields.
6138        self.place_label(resume);
6139        if is_async {
6140            self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6141            self.emit(Opcode::AsyncYieldStar, &[]);
6142        } else {
6143            self.emit(Opcode::YieldStar, &[]);
6144        }
6145        self.emit(Opcode::Dup, &[]);
6146        self.emit_jump(Opcode::IfTrue, rethrow, &[]);
6147        self.emit(Opcode::Drop, &[]);
6148        self.emit_jump(Opcode::Goto, next, &[]);
6149
6150        // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
6151        self.place_label(rethrow);
6152        self.emit(Opcode::PushI32, &[Op::Int(2)]);
6153        self.emit(Opcode::StrictEq, &[]);
6154        self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
6155        // A `return` closes the inner iterator; if it had none, the delegate simply
6156        // finishes with the requested value. In an async generator both the call and its
6157        // result are awaited, because the inner `return` may itself be async.
6158        if is_async {
6159            self.emit(Opcode::Await, &[]);
6160        }
6161        self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
6162        self.emit_jump(Opcode::IfTrue, finished, &[]);
6163        if is_async {
6164            self.emit(Opcode::Await, &[]);
6165        }
6166        self.emit(Opcode::IteratorCheckObject, &[]);
6167        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6168        self.emit_jump(Opcode::IfFalse, resume, &[]);
6169        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6170        self.place_label(finished);
6171        self.emit(Opcode::Nip, &[]);
6172        self.emit(Opcode::Nip, &[]);
6173        self.emit(Opcode::Nip, &[]);
6174        // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
6175        // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
6176        // awaits the value in an async generator and then runs the same `finally`/iterator
6177        // unwinding a written `return` would. Skipping the unwinding made
6178        // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
6179        if is_async {
6180            self.emit(Opcode::Await, &[]);
6181        }
6182        self.emit_unwind_for_return(true);
6183        self.emit(Opcode::ReturnAsync, &[]);
6184
6185        // `throw(e)`: forward it into the inner iterator.
6186        self.place_label(throw_no_method);
6187        self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
6188        let no_throw = self.new_label();
6189        self.emit_jump(Opcode::IfTrue, no_throw, &[]);
6190        if is_async {
6191            self.emit(Opcode::Await, &[]);
6192        }
6193        self.emit(Opcode::IteratorCheckObject, &[]);
6194        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6195        self.emit_jump(Opcode::IfFalse, resume, &[]);
6196        self.emit_jump(Opcode::Goto, done, &[]);
6197        // No `throw` method: close the iterator, then report the spec's TypeError. The
6198        // `if_true` before the `await` is the reference's shape — the flag it consumes is
6199        // what `iterator_call` leaves behind, and a close that *did* find no `return`
6200        // method has nothing to await.
6201        self.place_label(no_throw);
6202        self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
6203        let no_close = self.new_label();
6204        self.emit_jump(Opcode::IfTrue, no_close, &[]);
6205        if is_async {
6206            self.emit(Opcode::Await, &[]);
6207        }
6208        self.place_label(no_close);
6209        self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
6210
6211        // The inner iterator finished: the delegate's value is the `yield*` expression's
6212        // value, so it is left on the stack for whatever consumes it.
6213        self.place_label(done);
6214        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6215        self.emit(Opcode::Nip, &[]);
6216        self.emit(Opcode::Nip, &[]);
6217        self.emit(Opcode::Nip, &[]);
6218        Ok(())
6219    }
6220
6221    /// `await expr`: exactly one instruction.
6222    ///
6223    /// No resume-magic branch follows it. The reference's `await` leaves a single value
6224    /// on the stack and completion is signalled by the `return_async` at the end of the
6225    /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
6226    /// reference never emits, and a `for await` loop — which reaches `await` through the
6227    /// same opcode — would then spill a value the loop's unpacking does not expect.
6228    fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
6229        self.expr(argument)?;
6230        self.emit(Opcode::Await, &[]);
6231        self.state().has_await = true;
6232        Ok(())
6233    }
6234
6235    /// The `super` base: the receiver followed by the home object's prototype.
6236    ///
6237    /// Everything `super` does needs both. A *read* starts at the prototype but reports
6238    /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
6239    /// prototype but calls it with the receiver.
6240    fn super_base(&mut self) {
6241        self.this_expression();
6242        self.home_object();
6243        self.emit(Opcode::GetSuper, &[]);
6244    }
6245
6246    /// `[[HomeObject]]` as `super` sees it.
6247    ///
6248    /// A method, a constructor and a field initialiser each carry one — `set_home_object`
6249    /// put it there — so for them the special object *is* the answer. An arrow and a
6250    /// static block have none: they read the enclosing function's, which has to be
6251    /// materialised into a local, exactly as `this` is for an arrow.
6252    ///
6253    /// The name matches what the reference stores, so the disassembly agrees; it is not a
6254    /// name any program can write.
6255    fn home_object(&mut self) {
6256        if !self.cur().is_arrow {
6257            self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
6258            return;
6259        }
6260        if let Some(target) = self.enclosing_function() {
6261            self.state_at(target).needs_home_object_local = true;
6262            self.declare_at(target, HOME_OBJECT);
6263        }
6264        self.emit_var(VarAction::Get, HOME_OBJECT);
6265    }
6266
6267    /// `super(args)`: construct the parent class and adopt the result as `this`.
6268    ///
6269    /// The parent is the prototype of the constructor that is running, which is exactly
6270    /// what `extends` set up. `new.target` is passed through unchanged so that
6271    /// `new.target` inside the parent is the class actually being constructed.
6272    fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
6273        self.active_func_expression();
6274        self.emit(Opcode::GetSuper, &[]);
6275        self.new_target_expression();
6276        if Self::has_spread(arguments) {
6277            self.argument_array(arguments)?;
6278            self.emit(Opcode::Apply, &[Op::Int(1)]);
6279        } else {
6280            for argument in arguments {
6281                self.expr(argument)?;
6282            }
6283            self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
6284        }
6285        // The value stays on the stack: `super()` is an expression, and a derived
6286        // constructor's `this` may only be initialised once.
6287        self.emit(Opcode::Dup, &[]);
6288        self.emit_var(VarAction::PutInitChecked, "this");
6289        // Instance fields are installed here, not at the top of the body: a derived
6290        // constructor has no `this` to install them on until `super()` returns. The
6291        // reference emits the same call at every `super()` site.
6292        self.call_field_initialiser();
6293        Ok(())
6294    }
6295
6296    /// `this` as a local, which every class constructor and field initialiser needs.
6297    ///
6298    /// The reference materialises the receiver into a local rather than reading
6299    /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
6300    /// and a field initialiser has to see the final value.
6301    fn begin_this_local(&mut self) {
6302        self.declare_hidden_local("this", VarKind::Normal);
6303        self.emit(Opcode::PushThis, &[]);
6304        self.emit_var(VarAction::Put, "this");
6305        // The store is already at the top of the body, so `provide_this_local` has
6306        // nothing left to prepend. Without this the initialiser ended up with
6307        // `push_this; put_loc0 this` twice whenever the class also held a field
6308        // initialiser whose body read `this` through an arrow.
6309        self.state().has_this_prologue = true;
6310    }
6311
6312    /// Compile a constructor the class wrote.
6313    ///
6314    /// The flags have to be in place before the body is compiled, but
6315    /// `compile_function_with_name` creates its own state — so the caller's state is
6316    /// marked instead and the new one inherits it. That is the same trick the parameter
6317    /// prologue uses, and it keeps one code path for both.
6318    fn compile_class_constructor(
6319        &mut self,
6320        func: &ast::Function,
6321        has_heritage: bool,
6322    ) -> Result<CompiledFunction, SyntaxError> {
6323        let saved = self.cur().ctor_kind;
6324        self.state().class_ctor_pending = Some(if has_heritage {
6325            CtorKind::Derived
6326        } else {
6327            CtorKind::Base
6328        });
6329        let result = self.compile_function_with_name(func, false);
6330        self.state().ctor_kind = saved;
6331        self.state().class_ctor_pending = None;
6332        result
6333    }
6334
6335    /// The constructor a class gets when it does not declare one.
6336    ///
6337    /// A base class's is empty; a derived class's forwards every argument to the parent
6338    /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
6339    /// instance field initialiser afterwards when the class has fields, which is why the
6340    /// initialiser is captured rather than inlined.
6341    fn compile_implicit_constructor(
6342        &mut self,
6343        class: &Class,
6344        has_heritage: bool,
6345    ) -> Result<CompiledFunction, SyntaxError> {
6346        self.compile_synthetic_function(
6347            "",
6348            true,
6349            Span::new(class.body_end, class.body_end),
6350            |compiler| {
6351                if has_heritage {
6352                    // A derived constructor's `this` does not exist until `super()` returns,
6353                    // so it starts in the dead zone and `init_ctor` fills it.
6354                    compiler.declare("this", VarDef::lexical("this"));
6355                    compiler.emit(
6356                        Opcode::SetLocUninitialized,
6357                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6358                    );
6359                    compiler.emit(Opcode::InitCtor, &[]);
6360                    compiler.emit(
6361                        Opcode::PutLocCheckInit,
6362                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6363                    );
6364                } else {
6365                    compiler.begin_this_local();
6366                    compiler.emit(Opcode::CheckCtor, &[]);
6367                }
6368                compiler.call_field_initialiser();
6369                // A derived constructor returns `this`, the object `super()` built. Without
6370                // this the implicit constructor fell through to `return_undef`, and `new B()`
6371                // handed back the empty object `construct` had made instead of the one the
6372                // parent constructor initialised.
6373                if has_heritage {
6374                    compiler.emit_var(VarAction::Get, "this");
6375                    compiler.emit(Opcode::Return, &[]);
6376                }
6377                Ok(())
6378            },
6379        )
6380    }
6381
6382    /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
6383    ///
6384    /// A class with no instance fields leaves the binding `undefined`, and calling it
6385    /// would throw; the reference emits the same guard rather than branching at compile
6386    /// time because a class can be extended by a subclass whose fields still have to run.
6387    fn call_field_initialiser(&mut self) {
6388        let skip = self.new_label();
6389        self.emit_var(VarAction::Get, "<class_fields_init>");
6390        self.emit(Opcode::Dup, &[]);
6391        self.emit_jump(Opcode::IfFalse, skip, &[]);
6392        self.emit_var(VarAction::Get, "this");
6393        self.emit(Opcode::Swap, &[]);
6394        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6395        self.place_label(skip);
6396        self.emit(Opcode::Drop, &[]);
6397    }
6398
6399    /// The function that defines one class's fields on `this`, and runs its static blocks.
6400    ///
6401    /// `define_field` rather than `put_field`: a field is an own property created
6402    /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
6403    /// `x = 1` field must not call the setter.
6404    ///
6405    /// One function serves the whole class: it is called once per instance (or once, for
6406    /// the static half) and walks the members in source order. Static blocks are compiled
6407    /// into the same function because they *are* part of the same sequence — `static a =
6408    /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
6409    /// different values, so the two kinds cannot be split apart.
6410    fn compile_field_initialiser(
6411        &mut self,
6412        items: &[StaticInitItem<'_>],
6413        span: Span,
6414        instance: bool,
6415        add_brand: bool,
6416    ) -> Result<CompiledFunction, SyntaxError> {
6417        self.compile_synthetic_function("", true, span, |compiler| {
6418            // A field initialiser and a static block are not functions, so neither has an
6419            // `arguments` of its own; see `FnState::no_arguments_binding`.
6420            let current = compiler.stack.len() - 1;
6421            compiler.stack[current].no_arguments_binding = true;
6422            if instance {
6423                // An instance initialiser always carries a `<home_object>` local, because the
6424                // brand block below reads it — even when that block turns out to be dead. The
6425                // reference has the same artefact, and the store is visible in its dump.
6426                let current = compiler.stack.len() - 1;
6427                compiler.stack[current].needs_home_object_local = true;
6428            }
6429            compiler.begin_this_local();
6430            if instance {
6431                // `this` gets the brand the prototype created, before any field is defined —
6432                // which is what makes `#m()` usable from inside a field initialiser.
6433                //
6434                // The reference always emits `push_false; if_false L; this; home; add_brand;
6435                // L:` and patches the `push_false` to `push_true` from the class parse when
6436                // the class has private methods; either way the branch folds, but the *mark*
6437                // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
6438                // `this` local from being fused into a `set_loc`.
6439                let skip = compiler.new_label();
6440                if add_brand {
6441                    compiler.emit(Opcode::PushTrue, &[]);
6442                } else {
6443                    compiler.emit(Opcode::PushFalse, &[]);
6444                }
6445                compiler.emit_jump(Opcode::IfFalse, skip, &[]);
6446                compiler.emit_var(VarAction::Get, "this");
6447                compiler.emit_var(VarAction::Get, HOME_OBJECT);
6448                compiler.emit(Opcode::AddBrand, &[]);
6449                compiler.place_label(skip);
6450            }
6451            for item in items {
6452                match item {
6453                    StaticInitItem::Field(key, value) => {
6454                        // A private field is *defined*, not assigned: `define_private_field`
6455                        // reads `obj symbol value`, and its point is that it fails on a
6456                        // receiver that is not this class's — which `put_field` would not.
6457                        //
6458                        // The three shapes are the reference's: `define_field <atom>` for a
6459                        // static name, `define_array_el` for a key that is only known at run
6460                        // time (`obj key value`), `define_private_field` for `#x`, and a
6461                        // computed key is read from its binding rather than recomputed.
6462                        compiler.emit_var(VarAction::Get, "this");
6463                        match key {
6464                            FieldKey::Private(binding) | FieldKey::Computed(binding) => {
6465                                compiler.emit_var(VarAction::Get, binding);
6466                            }
6467                            FieldKey::Literal(_) => {}
6468                        }
6469                        match value {
6470                            Some(value) => {
6471                                compiler.expr(value)?;
6472                                // A field initialiser is a `NamedEvaluation` target:
6473                                // `x = function(){}` names the function `"x"`, and a private
6474                                // field keeps its `#` (`static #f = () => 1` is named
6475                                // `"#f"` (elements/static-field-anonymous-function-name).
6476                                match key {
6477                                    FieldKey::Literal(literal) => {
6478                                        let text = compiler.property_key_text(literal, span)?;
6479                                        compiler.set_name_if_anonymous(value, &text);
6480                                    }
6481                                    FieldKey::Private(binding) => {
6482                                        compiler.set_name_if_anonymous(value, &Wtf8::new(binding));
6483                                    }
6484                                    // The key is a value on the stack, and `set_name_computed`
6485                                    // is exactly the instruction for that.
6486                                    FieldKey::Computed(_) => {
6487                                        compiler.set_name_if_anonymous_computed(value);
6488                                    }
6489                                }
6490                            }
6491                            None => compiler.emit(Opcode::Undefined, &[]),
6492                        }
6493                        match key {
6494                            FieldKey::Literal(literal) => {
6495                                let text = compiler.property_key_text(literal, span)?;
6496                                compiler
6497                                    .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
6498                            }
6499                            FieldKey::Computed(_) => {
6500                                compiler.emit(Opcode::DefineArrayEl, &[]);
6501                                // `define_array_el` leaves `obj key`; the key is consumed by
6502                                // the copy the pattern machinery wants, so both go.
6503                                compiler.emit(Opcode::Drop, &[]);
6504                            }
6505                            FieldKey::Private(_) => {
6506                                compiler.emit(Opcode::DefinePrivateField, &[]);
6507                            }
6508                        }
6509                        compiler.emit(Opcode::Drop, &[]);
6510                    }
6511                    StaticInitItem::Block { body, body_start } => {
6512                        let block = compiler.compile_static_block(body, *body_start)?;
6513                        let index = compiler.push_constant(Constant::Function(Box::new(block)));
6514                        // `this fclosure`, so `call_method` finds the receiver below the
6515                        // callee: the block runs with `this` bound to the class.
6516                        compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
6517                        compiler.emit_var(VarAction::Get, "this");
6518                        compiler.emit(Opcode::Swap, &[]);
6519                        compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
6520                        // Nothing the block evaluates is wanted; its effects are the point.
6521                        compiler.emit(Opcode::Drop, &[]);
6522                    }
6523                }
6524            }
6525            Ok(())
6526        })
6527    }
6528
6529    /// Compile a `static { … }` body into the function the class calls for it.
6530    ///
6531    /// Shaped like an arrow, because that is the one function form with no `this`,
6532    /// `new.target` or `arguments` of its own: all three reach the enclosing static
6533    /// initialiser, and through it the class. `arguments` never gets that far — the parser
6534    /// rejects the reference — but `this` and `super` both depend on it.
6535    ///
6536    /// The body is hoisted like a function body's, because the reference parses it as one:
6537    /// `var` inside a block is a local of the block's function, not of whatever encloses
6538    /// the class.
6539    fn compile_static_block(
6540        &mut self,
6541        body: &[Stmt],
6542        body_start: Position,
6543    ) -> Result<CompiledFunction, SyntaxError> {
6544        let mut state = FnState::new(String::new(), FunctionKind::Normal);
6545        // Class bodies are strict, so a static block is too.
6546        state.strict = true;
6547        // The one property that makes this an arrow: nothing of its own to bind `this` to,
6548        // so `this` and `super` come from the initialiser that calls it.
6549        state.is_arrow = true;
6550        state.created_in_block = self.cur().current_block;
6551        state.with_names = self.cur().with_names.clone();
6552        state.line = body_start.line;
6553        state.column = body_start.column;
6554        let depth = self.stack.len();
6555        self.stack.push(state);
6556        let body_key = body_start.offset as u64;
6557        self.push_block(body_key, NO_PARENT);
6558        self.state().body_block = body_key;
6559        let result = (|| {
6560            self.hoist(body, body_key)?;
6561            self.emit_scope_enter(body_key);
6562            for statement in body {
6563                self.stmt(statement)?;
6564            }
6565            if self.end_is_reachable() {
6566                self.emit(Opcode::ReturnUndef, &[]);
6567            }
6568            Ok(())
6569        })();
6570        if result.is_err() {
6571            self.stack.truncate(depth);
6572            return result.map(|()| unreachable!());
6573        }
6574        Ok(self.finish_current())
6575    }
6576
6577    /// Compile a class, leaving the constructor on the stack when `keep`.
6578    ///
6579    /// The shape follows the reference: the class body is its own scope holding the
6580    /// class's *inner* name as a `const` — which is what lets a method refer to the
6581    /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
6582    /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
6583    /// on the top of the stack: the prototype for instance members, the constructor
6584    /// itself for `static` ones, which is why a static member costs an extra `swap`.
6585    fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
6586        let parent_block = self.cur().current_block;
6587        let key = class.span.start.offset as u64;
6588        self.push_block(key, parent_block);
6589        let name = class.name.as_ref().map(|ident| ident.name.clone());
6590        // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
6591        // resolves `E` without a global lookup. An *unnamed* class expression has no such
6592        // binding, and `define_class` is handed the empty name.
6593        if let Some(name) = &name {
6594            self.declare(name, VarDef::constant(name.clone()));
6595        }
6596        self.emit_scope_enter(key);
6597
6598        // The heritage clause is evaluated outside the class's own scope: it cannot see
6599        // the class binding it is about to initialise.
6600        let saved_block = self.cur().current_block;
6601        self.state().current_block = parent_block;
6602        match &class.super_class {
6603            Some(parent) => self.expr(parent)?,
6604            None => self.emit(Opcode::Undefined, &[]),
6605        }
6606        self.state().current_block = saved_block;
6607        let has_heritage = class.super_class.is_some();
6608
6609        // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
6610        // lands after the heritage's code — which is where the reference puts it, because it
6611        // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
6612        // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
6613        // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
6614        // came out in the opposite order from the reference's.
6615        //
6616        // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
6617        // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
6618        // a const accepts — so the old comment's worry ("a const would refuse the second
6619        // store") did not apply: there is no second store.
6620        // Every `#name` the class declares gets a `const` binding in the class scope, and so
6621        // does every computed field key. That is how the reference does it
6622        // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
6623        // what makes a private name resolve like any other class-scope variable — including
6624        // through a nested function's closure — while remaining invisible outside.
6625        //
6626        // All of them are declared *before* `<class_fields_init>`, in member order, because
6627        // that is when the reference's parser creates them.
6628        let plan = ClassPlan::build(class);
6629        // The body's private names are visible from here to the end of the class, and shadow
6630        // any outer class's of the same spelling. Pushed *before* the constructor is compiled
6631        // — it is compiled first because `define_class` consumes it, but its body can name
6632        // `#x` like any other member's.
6633        self.private_scopes.push(plan.uses.clone());
6634        let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
6635        for binding in &plan.bindings {
6636            class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
6637        }
6638        let fci = self.declare(
6639            "<class_fields_init>",
6640            VarDef::constant("<class_fields_init>"),
6641        );
6642        // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
6643        // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
6644        // members' bindings follow in reverse.
6645        self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
6646        for slot in class_slots.iter().rev() {
6647            self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
6648        }
6649
6650        // The constructor is compiled before `define_class` because that instruction
6651        // consumes it; a class without one gets the implicit version.
6652        let constructor = class.elements.iter().find_map(|element| match element {
6653            ClassElement::Method {
6654                kind: MethodKind::Constructor,
6655                func,
6656                ..
6657            } => Some(&**func),
6658            _ => None,
6659        });
6660        // A constructor is compiled differently from a method: it owns `this`. The flags
6661        // go on the *enclosing* state because a constructor is a nested function and
6662        // `compile_function_with_name` starts a fresh one.
6663        let ctor = match constructor {
6664            Some(func) => self.compile_class_constructor(func, has_heritage)?,
6665            None => self.compile_implicit_constructor(class, has_heritage)?,
6666        };
6667        // A closure, not the bare constant: the constructor captures
6668        // `<class_fields_init>`, which is only filled after `define_class` has run, so it
6669        // has to hold the cell rather than a copy of its value.
6670        //
6671        // The pool slot is left unassigned for now, because the reference gives the
6672        // constructor the *last* index of the members' range: `js_parse_class` emits a
6673        // `push_const` whose operand is patched at the end of the class parse, after every
6674        // method has taken a slot. Emitting the members first and the constant second is how
6675        // the numbering comes out the same; the instruction itself stays where it is.
6676        let ctor_insn = self.cur().insns.len();
6677        self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
6678        let flags = if has_heritage { 1 } else { 0 };
6679        self.emit(
6680            Opcode::DefineClass,
6681            &[
6682                Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
6683                Op::Int(flags),
6684            ],
6685        );
6686
6687        // Instance fields and static fields are two different functions: the first runs
6688        // per instance from the constructor, the second runs once, here.
6689        let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
6690        let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
6691        for (index, element) in class.elements.iter().enumerate() {
6692            match element {
6693                ClassElement::Method {
6694                    key: member_key,
6695                    is_static,
6696                    kind,
6697                    func,
6698                    span,
6699                } => {
6700                    if *kind == MethodKind::Constructor {
6701                        continue;
6702                    }
6703                    // `static(x)` is a *method* named `static`, not a static method; the
6704                    // parser already decided which by putting it in `kind`.
6705                    if *is_static {
6706                        self.emit(Opcode::Swap, &[]);
6707                    }
6708                    // A computed key is evaluated *here*, before the method's closure
6709                    // exists, and stays under it: `define_method_computed` pops
6710                    // `function, key, object`, so the stack has to read
6711                    // `[class, prototype, key, function]`. Evaluating the key after the
6712                    // `fclosure` and swapping the two put the prototype *below* the
6713                    // closure, which defined the method on the function and lost the
6714                    // prototype: `class C { [k]() {} }` left `C` undefined. The order is
6715                    // also the spec's — a class body evaluates every element's name before
6716                    // that element's function.
6717                    if let PropName::Computed(key) = member_key {
6718                        self.expr(key)?;
6719                    }
6720                    let function = self.compile_function_with_name(func, true)?;
6721                    let index = self.push_constant(Constant::Function(Box::new(function)));
6722                    self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6723                    match member_key {
6724                        // A private method is not a property of the prototype: it is a
6725                        // closure in the class scope, which is why nothing outside can reach
6726                        // it and why a use site has to brand-check. `set_name` gives the
6727                        // function its `name` (`#m`), which an accessor does not get — the
6728                        // reference leaves that commented out.
6729                        PropName::Private(ident) => {
6730                            let name = format!("#{}", ident.name);
6731                            // `set_home_object` first: the brand check reads the function's
6732                            // home object, and for a method that is the prototype.
6733                            self.emit(Opcode::SetHomeObject, &[]);
6734                            let binding = if *kind == MethodKind::Set {
6735                                format!("{name}<set>")
6736                            } else {
6737                                name.clone()
6738                            };
6739                            if *kind == MethodKind::Method {
6740                                self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
6741                            }
6742                            self.emit_var(VarAction::PutInit, &binding);
6743                        }
6744                        PropName::Computed(_) => {
6745                            self.emit(
6746                                Opcode::DefineMethodComputed,
6747                                &[Op::Int(class_method_flags(*kind))],
6748                            );
6749                        }
6750                        PropName::Literal(literal) => {
6751                            let text = self.property_key_text(literal, *span)?;
6752                            self.emit(
6753                                Opcode::DefineMethod,
6754                                &[
6755                                    Op::Atom(Atom::from_wtf8(&text)),
6756                                    Op::Int(class_method_flags(*kind)),
6757                                ],
6758                            );
6759                        }
6760                    }
6761                    if *is_static {
6762                        self.emit(Opcode::Swap, &[]);
6763                    }
6764                }
6765                ClassElement::Field {
6766                    key: field_key,
6767                    is_static,
6768                    value,
6769                    ..
6770                } => {
6771                    // A private field's *symbol* is created here, at the member, and stored
6772                    // in its binding: the field's property is keyed by it, so it has to exist
6773                    // before any initialiser runs, and a fresh one per class body is what
6774                    // makes two classes that both write `#x` independent.
6775                    //
6776                    // A computed key is evaluated once, here, and `to_propkey`'d once — a key
6777                    // whose `toString` has a side effect must not run again per instance.
6778                    let key = match field_key {
6779                        PropName::Private(ident) => {
6780                            let binding = format!("#{}", ident.name);
6781                            if *is_static {
6782                                self.emit(Opcode::Swap, &[]);
6783                            }
6784                            self.emit(
6785                                Opcode::PrivateSymbol,
6786                                &[Op::Atom(Atom::from_text(&binding))],
6787                            );
6788                            self.emit_var(VarAction::PutInit, &binding);
6789                            if *is_static {
6790                                self.emit(Opcode::Swap, &[]);
6791                            }
6792                            FieldKey::Private(binding)
6793                        }
6794                        PropName::Computed(expression) => {
6795                            let binding = plan
6796                                .computed
6797                                .get(&index)
6798                                .cloned()
6799                                .expect("every computed key got a binding");
6800                            if *is_static {
6801                                self.emit(Opcode::Swap, &[]);
6802                            }
6803                            self.expr(expression)?;
6804                            self.emit(Opcode::ToPropkey, &[]);
6805                            self.emit_var(VarAction::PutInit, &binding);
6806                            if *is_static {
6807                                self.emit(Opcode::Swap, &[]);
6808                            }
6809                            FieldKey::Computed(binding)
6810                        }
6811                        PropName::Literal(literal) => FieldKey::Literal(literal),
6812                    };
6813                    if *is_static {
6814                        static_items.push(StaticInitItem::Field(key, value.as_deref()));
6815                    } else {
6816                        instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
6817                    }
6818                }
6819                ClassElement::StaticBlock {
6820                    body, body_start, ..
6821                } => static_items.push(StaticInitItem::Block {
6822                    body,
6823                    body_start: *body_start,
6824                }),
6825            }
6826        }
6827
6828        // Now that every member has its slot, the constructor can have the next one and the
6829        // `fclosure` above can name it.
6830        let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
6831        match self.state().insns.get_mut(ctor_insn) {
6832            Some(Insn::Fixed { operands, .. }) => {
6833                operands[0] = Op::Const(ctor_index);
6834            }
6835            // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
6836            // loudly beats emitting a `fclosure` of slot 4294967295.
6837            _ => {
6838                return Err(SyntaxError::new(
6839                    "the class constructor's fclosure went missing",
6840                    class.span,
6841                ));
6842            }
6843        }
6844
6845        // The instance brand: a symbol created once on the prototype, which every instance
6846        // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
6847        // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
6848        // copy is created. The prototype is on top of the stack at this point.
6849        if plan.instance_brand {
6850            self.emit(Opcode::Dup, &[]);
6851            self.emit(Opcode::Null, &[]);
6852            self.emit(Opcode::Swap, &[]);
6853            self.emit(Opcode::AddBrand, &[]);
6854        }
6855
6856        // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
6857        // class has no instance fields. The constructor calls it only when it is defined.
6858        //
6859        // A class with private *methods* but no fields still needs one, because adding the
6860        // brand to each new instance is the initialiser's job.
6861        if instance_fields.is_empty() && !plan.instance_brand {
6862            self.emit(Opcode::Undefined, &[]);
6863        } else {
6864            let initialiser = self.compile_field_initialiser(
6865                &instance_fields,
6866                class.span,
6867                true,
6868                plan.instance_brand,
6869            )?;
6870            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6871            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6872            // `set_home_object` reads `obj func`, so the prototype stays where it is.
6873            self.emit(Opcode::SetHomeObject, &[]);
6874        }
6875        self.emit_var(VarAction::PutInit, "<class_fields_init>");
6876        // The prototype has done its job: every instance member is defined on it. What
6877        // is left under it is the constructor.
6878        self.emit(Opcode::Drop, &[]);
6879
6880        // The static brand, for `static #m() {}`: same opcode, but the home object is the
6881        // constructor itself, so the symbol lands on the class and the class carries it.
6882        if plan.static_brand {
6883            self.emit(Opcode::Dup, &[]);
6884            self.emit(Opcode::Dup, &[]);
6885            self.emit(Opcode::AddBrand, &[]);
6886        }
6887
6888        // The class binding is initialised *before* static fields run, so a static field
6889        // can refer to the class by name (`static y = S.x`).
6890        // `set_loc` leaves the constructor on the stack, which is what the static field
6891        // call and the outer store both consume.
6892        //
6893        // Only when there *is* such a binding: an anonymous class expression declares no
6894        // class-scope name, and asking for one by the empty string resolved to nothing —
6895        // which made `var x = class {}` assign `undefined` and put a bogus global store in
6896        // the instruction stream.
6897        if let Some(name) = &name {
6898            self.emit_var(VarAction::SetInit, name);
6899        }
6900        if !static_items.is_empty() {
6901            // The static half has no brand prologue of its own: the constructor got its
6902            // brand above, before this runs.
6903            let initialiser =
6904                self.compile_field_initialiser(&static_items, class.span, false, false)?;
6905            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6906            self.emit(Opcode::Dup, &[]);
6907            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6908            self.emit(Opcode::SetHomeObject, &[]);
6909            self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6910            self.emit(Opcode::Drop, &[]);
6911        }
6912        // The body is over, and with it this class's private names.
6913        let _ = self.private_scopes.pop();
6914        self.emit_scope_leave(key);
6915        self.state().current_block = parent_block;
6916        if keep {
6917            // A class *expression* is its own value; the class-scope binding was only
6918            // ever an alias for it.
6919            return Ok(());
6920        }
6921        // A declaration stores into the binding the enclosing statement declared.
6922        self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
6923        Ok(())
6924    }
6925
6926    fn push_this(&mut self) {
6927        self.emit(Opcode::PushThis, &[]);
6928    }
6929
6930    /// `this`, which an arrow does not have of its own.
6931    ///
6932    /// The reference gives the enclosing function a local named `this`, initialised from
6933    /// `push_this` at the top of its body, and the arrow then reads it as a captured
6934    /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
6935    /// the arrow is called with none.
6936    fn this_expression(&mut self) {
6937        // In a class constructor `this` is a local: a derived constructor only gets one
6938        // when `super()` returns, and reading the raw receiver would give the *outer*
6939        // one instead.
6940        if self.cur().ctor_kind != CtorKind::None {
6941            self.emit_var(VarAction::Get, "this");
6942            return;
6943        }
6944        if !self.cur().is_arrow {
6945            self.push_this();
6946            return;
6947        }
6948        // An arrow at the **top level** of a script or module has no enclosing function,
6949        // but it still inherits `this` — the script's or module's own. Falling through to
6950        // `emit_var(Get, "this")` without a target made that a *global* lookup, so
6951        // `var f = () => typeof this` at top level reported
6952        // `ReferenceError: 'this' is not defined` instead of `"object"`
6953        // (`Set/prototype/forEach/this-arg-explicit-cannot-override-lexical-this-arrow`
6954        // is the test262 case that reaches it, through a native `forEach`).
6955        //
6956        // The script state is the bottom of the stack, so it is the fallback target. Its
6957        // own `provide_this_local` then prepends the `push_this` the arrow reads.
6958        let target = self.enclosing_function().unwrap_or(0);
6959        self.state_at(target).needs_this_local = true;
6960        self.declare_at(target, "this");
6961        self.emit_var(VarAction::Get, "this");
6962    }
6963
6964    /// `new.target`, which an arrow likewise does not own.
6965    fn new_target_expression(&mut self) {
6966        if !self.cur().is_arrow {
6967            self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
6968            return;
6969        }
6970        if let Some(target) = self.enclosing_function() {
6971            self.state_at(target).needs_new_target_local = true;
6972            self.declare_at(target, NEW_TARGET);
6973        }
6974        self.emit_var(VarAction::Get, NEW_TARGET);
6975    }
6976
6977    /// `this.active_func`: the function `super()` resolves against.
6978    ///
6979    /// In a constructor or a method that is the function being run, so the special object
6980    /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
6981    /// a closure variable — see [`FnState::needs_active_func_local`].
6982    fn active_func_expression(&mut self) {
6983        if !self.cur().is_arrow {
6984            self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
6985            return;
6986        }
6987        if let Some(target) = self.enclosing_function() {
6988            self.state_at(target).needs_active_func_local = true;
6989            self.declare_at(target, ACTIVE_FUNC);
6990        }
6991        self.emit_var(VarAction::Get, ACTIVE_FUNC);
6992    }
6993
6994    /// Give the function a local `<active_func>`, for an arrow inside it to capture.
6995    fn provide_active_func_local(&mut self) {
6996        let current = self.stack.len() - 1;
6997        if !self.stack[current].needs_active_func_local {
6998            return;
6999        }
7000        if !self.stack[current]
7001            .vars
7002            .iter()
7003            .any(|var| var.name == ACTIVE_FUNC)
7004        {
7005            self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
7006        }
7007        self.prepend_initialiser(
7008            ACTIVE_FUNC,
7009            Insn::Fixed {
7010                op: Opcode::SpecialObject,
7011                operands: vec![Op::Int(2)],
7012            },
7013        );
7014    }
7015
7016    /// Give the function a local `new.target`, for an arrow inside it to capture.
7017    fn provide_new_target_local(&mut self) {
7018        let current = self.stack.len() - 1;
7019        if !self.stack[current].needs_new_target_local {
7020            return;
7021        }
7022        if !self.stack[current]
7023            .vars
7024            .iter()
7025            .any(|var| var.name == NEW_TARGET)
7026        {
7027            self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
7028        }
7029        self.prepend_initialiser(
7030            NEW_TARGET,
7031            Insn::Fixed {
7032                op: Opcode::SpecialObject,
7033                operands: vec![Op::Int(3)],
7034            },
7035        );
7036    }
7037
7038    /// `arguments` reached from an arrow, which likewise belongs to the enclosing
7039    /// function.
7040    fn ensure_enclosing_arguments(&mut self) {
7041        // An arrow created in a parameter list needs the *parameter* scope's
7042        // `arguments`, not the body's: the two are separate bindings and the arrow was
7043        // born before the body existed.
7044        let from_params = self.cur().created_in_params;
7045        if let Some(target) = self.enclosing_function() {
7046            self.state_at(target).needs_arguments_local = true;
7047            if from_params {
7048                self.state_at(target).needs_param_arguments = true;
7049                // Declare it now, not at the enclosing function's `finish_current`: the
7050                // arrow resolves its own `arguments` before that runs, and a binding that
7051                // does not exist yet resolves as a global.
7052                declare_param_var_at(&mut self.stack[target], "arguments");
7053            }
7054            self.declare_at(target, "arguments");
7055        }
7056    }
7057
7058    /// The innermost enclosing frame that is a real function — an arrow inherits from it
7059    /// rather than starting a scope of its own.
7060    /// The innermost enclosing frame that can own a lexical binding an arrow reads —
7061    /// a real function, or a **script** top level.
7062    ///
7063    /// A script is in the list because an `eval` body is compiled as one and an arrow
7064    /// written in eval'd code still has to find the caller's `new.target`, `this.active_func`
7065    /// and `[[HomeObject]]`. Excluding it made `eval("() => new.target")` compile the read as
7066    /// a *global* lookup of `new.target`, which no frame provides — so it raised
7067    /// `ReferenceError` instead of answering the caller's value
7068    /// (`arrow-body-direct-eval-err-contains-newtarget`).
7069    fn enclosing_function(&self) -> Option<usize> {
7070        (0..self.stack.len())
7071            .rev()
7072            .find(|index| !self.stack[*index].is_arrow)
7073    }
7074
7075    fn state_at(&mut self, index: usize) -> &mut FnState {
7076        &mut self.stack[index]
7077    }
7078
7079    /// Declare a `var` binding directly in a specific frame.
7080    fn declare_at(&mut self, index: usize, name: &str) {
7081        let state = &mut self.stack[index];
7082        if state.vars.iter().any(|var| var.name == name) {
7083            return;
7084        }
7085        state.var_block.push(FUNCTION_SCOPE);
7086        state.vars.push(VarDef::var(name));
7087    }
7088
7089    /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
7090    /// the reference calls a `special_object` gets initialised on entry.
7091    fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
7092        let current = self.stack.len() - 1;
7093        let init = [
7094            producer,
7095            Insn::Var {
7096                action: VarAction::Put,
7097                name: name.to_string(),
7098                block: 0,
7099                // A prologue initialiser runs before the body proper, but it is body
7100                // code: `this` and `arguments` are provided for it, not by it.
7101                in_params: false,
7102            },
7103        ];
7104        let inserted = init.len();
7105        for (index, instruction) in init.into_iter().enumerate() {
7106            self.stack[current].insns.insert(index, instruction);
7107        }
7108        for placed in self.stack[current].labels.iter_mut().flatten() {
7109            *placed += inserted;
7110        }
7111        self.stack[current].label_since_insn = true;
7112    }
7113
7114    fn push_constant(&mut self, constant: Constant) -> u32 {
7115        let state = self.state();
7116        let index = state.cpool.len() as u32;
7117        state.cpool.push(constant);
7118        index
7119    }
7120
7121    /// Compile `a && b`, `a || b`, `a ?? b`.
7122    ///
7123    /// A run of the *same* operator shares one end label, so `a || b || c` tests
7124    /// `a` once and jumps past everything when it is truthy, instead of falling
7125    /// into `b`'s test. The parser builds such a run left-associated —
7126    /// `((a || b) || c)` — so the operands are collected off the left spine.
7127    ///
7128    /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
7129    /// `||`'s label, because the inner chain really does end before `&&` begins.
7130    fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
7131        let mut operands = Vec::new();
7132        collect_same_operator(op, left, &mut operands);
7133        operands.push(right);
7134
7135        let end = self.new_label();
7136        // Every operand but the last decides whether the chain stops here.
7137        let last = operands.pop().expect("the right operand is always present");
7138        for operand in operands {
7139            self.expr(operand)?;
7140            self.emit(Opcode::Dup, &[]);
7141            match op {
7142                LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
7143                LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
7144                // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
7145                // `0 || b` is `b`. The dedicated test keeps the value unless it is
7146                // null-ish, so the jump is taken on `false`.
7147                LogicalOp::Coalesce => {
7148                    self.emit(Opcode::IsUndefinedOrNull, &[]);
7149                    self.emit_jump(Opcode::IfFalse, end, &[]);
7150                }
7151            }
7152            self.emit(Opcode::Drop, &[]);
7153        }
7154        self.expr(last)?;
7155        self.place_label(end);
7156        Ok(())
7157    }
7158
7159    fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
7160        match op {
7161            UnaryOp::Typeof => {
7162                // `typeof x` must not throw on an undeclared name.
7163                if let ExprKind::Ident(name) = &argument.kind {
7164                    self.emit_var(VarAction::GetUndef, &name.name);
7165                } else {
7166                    self.expr(argument)?;
7167                }
7168                self.emit(Opcode::Typeof, &[]);
7169            }
7170            UnaryOp::Delete => {
7171                // `delete obj.prop` really deletes, and answers whether it could.
7172                // Deleting a *binding* is always `false`: a local, an argument and a
7173                // declared global are all non-configurable, which the reference encodes
7174                // as a constant `push_false` rather than a runtime check. Only a
7175                // property access has anything to do at run time.
7176                // `delete super.x` is not a delete at all: the spec refuses it, and the
7177                // reference encodes the refusal as a `throw_error`. The receiver and the
7178                // key are still evaluated first, which is what keeps the evaluation order
7179                // of the operand intact.
7180                // `delete z?.b.c` answers `true` when the chain short-circuits: there is
7181                // nothing to delete, and a failed delete is not the same as a skipped
7182                // one. The reference emits the guards so they land on a `drop; push_true`
7183                // tail, which is what this reproduces.
7184                if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
7185                    && let ExprKind::Member {
7186                        object, property, ..
7187                    } = &inner.unparen().kind
7188                {
7189                    let end = self.new_label();
7190                    let done = self.new_label();
7191                    self.chain_link(object, end)?;
7192                    match property {
7193                        MemberProp::Ident(name) => self.emit(
7194                            Opcode::PushAtomValue,
7195                            &[Op::Atom(Atom::from_text(&name.name))],
7196                        ),
7197                        MemberProp::Computed(index) => self.expr(index)?,
7198                        MemberProp::Private(_) => {
7199                            return Err(SyntaxError::new(
7200                                "deleting a private field is not allowed",
7201                                argument.span,
7202                            ));
7203                        }
7204                    }
7205                    self.emit(Opcode::Delete, &[]);
7206                    self.emit_jump(Opcode::Goto, done, &[]);
7207                    self.place_label(end);
7208                    self.emit(Opcode::Drop, &[]);
7209                    self.emit(Opcode::PushTrue, &[]);
7210                    self.place_label(done);
7211                    return Ok(());
7212                }
7213                if let ExprKind::Member { object, .. } = &argument.unparen().kind
7214                    && matches!(object.unparen().kind, ExprKind::SuperProp)
7215                {
7216                    self.super_base();
7217                    self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
7218                    return Ok(());
7219                }
7220                // Parentheses are transparent to `delete`: `(x)` is still a Reference to
7221                // the binding `x`, so `delete (x)` answers `false` exactly as `delete x`
7222                // does, and `delete (a().b)` still evaluates `a()`. Matching on the
7223                // unparenthesised operand is what keeps both — matching on `argument.kind`
7224                // sent every parenthesised form to the "not a Reference" arm, which cost
7225                // `delete(__variable) === false` in test262's `S12.2_A2`.
7226                match &argument.unparen().kind {
7227                    ExprKind::Member {
7228                        object, property, ..
7229                    } => {
7230                        self.expr(object)?;
7231                        match property {
7232                            MemberProp::Ident(name) => {
7233                                self.emit(
7234                                    Opcode::PushAtomValue,
7235                                    &[Op::Atom(Atom::from_text(&name.name))],
7236                                );
7237                            }
7238                            MemberProp::Computed(index) => self.expr(index)?,
7239                            MemberProp::Private(_) => {
7240                                return Err(SyntaxError::new(
7241                                    "deleting a private field is not allowed",
7242                                    argument.span,
7243                                ));
7244                            }
7245                        }
7246                        self.emit(Opcode::Delete, &[]);
7247                    }
7248                    ExprKind::Ident(name) => {
7249                        self.delete_ident(&name.name);
7250                    }
7251                    // §13.5.1.2 step 2: an operand that is **not** a Reference Record
7252                    // answers `true` — there is nothing to delete, and "nothing needed
7253                    // deleting" is success. `delete !0`, `delete (1 + 2)` and
7254                    // `delete typeof 0` are all `true`, and the operand is still evaluated
7255                    // (which is why it is `Drop`ed rather than skipped:
7256                    // `delete f()` must call `f`).
7257                    //
7258                    // Answering `false` here is the C reference's old behaviour and was
7259                    // wrong in an observable way: test262's
7260                    // `dynamic-import/assignment-expression/logical-and-expr` builds a
7261                    // specifier out of `delete void typeof +-~! 0 && b`, and a `false` left
7262                    // half turned the whole `&&` into `false`, so the import asked for a
7263                    // module named "false".
7264                    _ => {
7265                        self.expr(argument)?;
7266                        self.emit(Opcode::Drop, &[]);
7267                        self.emit(Opcode::PushTrue, &[]);
7268                    }
7269                }
7270            }
7271            UnaryOp::Void => {
7272                self.expr(argument)?;
7273                self.emit(Opcode::Drop, &[]);
7274                self.emit(Opcode::Undefined, &[]);
7275            }
7276            UnaryOp::Minus => {
7277                self.expr(argument)?;
7278                self.emit(Opcode::Neg, &[]);
7279            }
7280            UnaryOp::Plus => {
7281                self.expr(argument)?;
7282                self.emit(Opcode::Plus, &[]);
7283            }
7284            UnaryOp::Not => {
7285                self.expr(argument)?;
7286                self.emit(Opcode::Lnot, &[]);
7287            }
7288            UnaryOp::BitNot => {
7289                self.expr(argument)?;
7290                self.emit(Opcode::Not, &[]);
7291            }
7292        }
7293        Ok(())
7294    }
7295
7296    /// A store to `name` while a `with` may capture it.
7297    ///
7298    /// The reference is resolved **first**, before the right-hand side runs. That order is
7299    /// the whole point: in `x = (delete env.x, 0)` the resolution has already decided that
7300    /// `x` is `env`'s property, so `PutValue` then finds it gone and strict code throws
7301    /// `ReferenceError` (`set-mutable-binding-binding-deleted-with-typed-array-in-
7302    /// proto-chain-strict-mode`). The ordinary path evaluates the right-hand side before
7303    /// the guard runs, which put the guard *after* the mutation.
7304    ///
7305    /// Shapes mirror [`Compiler::assign_ident_plain`] and the member arms of
7306    /// [`Compiler::assign`], with `dup; with_get_var` in place of `get_field2` and
7307    /// `with_put_var` in place of `put_field` — the same stack effects, but each half also
7308    /// asks the `HasProperty` that `GetBindingValue`/`SetMutableBinding` require.
7309    fn with_assign(
7310        &mut self,
7311        with_local: &str,
7312        name: &Ident,
7313        op: AssignOp,
7314        value: &Expr,
7315        keep: bool,
7316    ) -> Result<(), SyntaxError> {
7317        let atom = Atom::from_text(&name.name);
7318        self.state().cur_pos = Some(name.span.start);
7319        match op {
7320            AssignOp::Assign => {
7321                self.expr(value)?;
7322                self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7323                if keep {
7324                    self.emit(Opcode::Dup, &[]);
7325                }
7326                self.state().no_value = !keep;
7327                self.emit_var(VarAction::Get, with_local);
7328                self.emit(Opcode::Swap, &[]);
7329                self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7330            }
7331            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7332                let (keep_label, end) = (self.new_label(), self.new_label());
7333                self.emit_var(VarAction::Get, with_local);
7334                self.emit(Opcode::Dup, &[]);
7335                self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7336                // `obj value` — the object stays underneath for the store.
7337                self.emit(Opcode::Dup, &[]);
7338                self.emit_logical_test(op);
7339                self.emit_jump(logical_jump(op), keep_label, &[]);
7340                self.emit(Opcode::Drop, &[]);
7341                self.expr(value)?;
7342                self.emit(Opcode::Insert2, &[]);
7343                self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7344                self.emit_jump(Opcode::Goto, end, &[]);
7345                self.place_label(keep_label);
7346                self.emit(Opcode::Nip, &[]);
7347                self.place_label(end);
7348            }
7349            _ => {
7350                self.emit_var(VarAction::Get, with_local);
7351                self.emit(Opcode::Dup, &[]);
7352                self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7353                self.expr(value)?;
7354                self.state().cur_pos = Some(name.span.start);
7355                self.emit(compound_opcode(op), &[]);
7356                self.state().no_value = !keep;
7357                if keep {
7358                    self.emit(Opcode::Insert2, &[]);
7359                }
7360                self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7361            }
7362        }
7363        Ok(())
7364    }
7365
7366    /// `x++` / `++x` while a `with` may capture `x`, with one resolution for both halves.
7367    fn with_update(
7368        &mut self,
7369        with_local: &str,
7370        name: &Ident,
7371        op: UpdateOp,
7372        prefix: bool,
7373    ) -> Result<(), SyntaxError> {
7374        let instruction = match (op, prefix) {
7375            (UpdateOp::Increment, true) => Opcode::Inc,
7376            (UpdateOp::Increment, false) => Opcode::PostInc,
7377            (UpdateOp::Decrement, true) => Opcode::Dec,
7378            (UpdateOp::Decrement, false) => Opcode::PostDec,
7379        };
7380        let atom = Atom::from_text(&name.name);
7381        self.state().cur_pos = Some(name.span.start);
7382        self.emit_var(VarAction::Get, with_local);
7383        self.emit(Opcode::Dup, &[]);
7384        self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7385        self.emit(instruction, &[]);
7386        self.emit(
7387            if prefix {
7388                Opcode::Insert2
7389            } else {
7390                Opcode::Perm3
7391            },
7392            &[],
7393        );
7394        self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7395        Ok(())
7396    }
7397
7398    /// A store to a plain identifier, with no `with` in the way.
7399    fn assign_ident_plain(
7400        &mut self,
7401        op: AssignOp,
7402        name: &Ident,
7403        value: &Expr,
7404        discard: bool,
7405    ) -> Result<(), SyntaxError> {
7406        // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7407        // about, so it is set only when this assignment *is* that expression.
7408        let keep = !discard;
7409        // A *simple* store is blamed on the identifier, not on the `=`: a
7410        // strict-mode `not_def = 1` raises when the name is written, which the
7411        // reference reports at the name's column. A compound store is blamed on
7412        // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
7413        // which the reference reports at the `+=`), so only the simple case
7414        // moves the position.
7415        let saved = self.cur().cur_pos;
7416        let name_pos = Some(name.span.start);
7417        if matches!(op, AssignOp::Assign) {
7418            self.state().cur_pos = name_pos;
7419        }
7420        // A *compound* store reads the binding before it combines, and that read
7421        // is blamed on the identifier: `not_def += 2` fails while reading
7422        // `not_def`, so the position is the name's, not the `+=`'s. The
7423        // combination that follows is blamed on the operator, which is why
7424        // `cur_pos` is put back to the operator position before it is emitted.
7425        self.state().cur_pos = name_pos;
7426        match op {
7427            AssignOp::Assign => {
7428                self.expr(value)?;
7429                self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7430                // A discarded store to a *slot* consumes its value, so no copy
7431                // is needed. A global store goes through `put_var`, which the
7432                // reference always pairs with a `dup` — matching it keeps the
7433                // bytecode identical. Getting this wrong is not only an extra
7434                // instruction: a stray copy gives the peephole a chance to fold
7435                // the store into an unrelated later read.
7436                let slot = self.is_slot(&name.name);
7437                if keep || !slot {
7438                    self.emit(Opcode::Dup, &[]);
7439                }
7440                self.state().no_value = !keep && slot;
7441                self.emit_var(VarAction::Put, &name.name);
7442            }
7443            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7444                let end = self.new_label();
7445                self.emit_var(VarAction::Get, &name.name);
7446                self.state().cur_pos = saved;
7447                self.emit(Opcode::Dup, &[]);
7448                self.emit_logical_test(op);
7449                self.emit_jump(logical_jump(op), end, &[]);
7450                self.emit(Opcode::Drop, &[]);
7451                self.expr(value)?;
7452                self.emit(Opcode::Dup, &[]);
7453                self.emit_var(VarAction::Put, &name.name);
7454                self.place_label(end);
7455            }
7456            _ => {
7457                self.emit_var(VarAction::Get, &name.name);
7458                self.expr(value)?;
7459                self.state().cur_pos = saved;
7460                self.emit(compound_opcode(op), &[]);
7461                self.emit(Opcode::Dup, &[]);
7462                self.emit_var(VarAction::Put, &name.name);
7463            }
7464        }
7465        self.state().cur_pos = saved;
7466        Ok(())
7467    }
7468
7469    /// Compile an assignment.
7470    ///
7471    /// Three operator families, three shapes:
7472    ///
7473    /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
7474    ///   the value is kept, because `put_field`/`put_array_el` consume both the
7475    ///   object and the value: `insert2` is `obj a -> a obj a`, so the store sees
7476    ///   the pair it wants and leaves a copy on top.
7477    /// * **compound** `+=` … — read the place, apply the operator, store. A member
7478    ///   reads through `get_field2`/`get_array_el3`, which leave the object (and
7479    ///   index) underneath the value precisely so the store can follow.
7480    /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
7481    ///   right-hand side. The test *keeps* the current value and skips the store
7482    ///   entirely, which is the whole point: `a ||= b` must not evaluate `b` when
7483    ///   `a` is already truthy.
7484    fn assign(
7485        &mut self,
7486        op: AssignOp,
7487        target: &Pattern,
7488        value: &Expr,
7489        discard: bool,
7490    ) -> Result<(), SyntaxError> {
7491        // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7492        // about, so it is set only when this assignment *is* that expression.
7493        let keep = !discard;
7494        match &target.kind {
7495            PatternKind::Ident(name) => {
7496                // Any store to a name a `with` may capture resolves the reference first and
7497                // keeps that resolution for both halves — see [`Compiler::with_assign`].
7498                // Plain `=` needs it just as much as `+=`: `x = (delete env.x, 0)` must
7499                // resolve `x` before the right-hand side deletes it.
7500                let plain_name = name.name.clone();
7501                if !self.visible_with_names(&plain_name).is_empty() {
7502                    return self.with_reference(
7503                        &plain_name,
7504                        &mut |compiler, with_local| {
7505                            compiler.with_assign(with_local, name, op, value, !discard)
7506                        },
7507                        &mut |compiler| compiler.assign_ident_plain(op, name, value, discard),
7508                    );
7509                }
7510                self.assign_ident_plain(op, name, value, discard)
7511            }
7512            PatternKind::Member(member) => {
7513                // `super.x = v` is not a store through a value: it starts at the home
7514                // object's prototype but writes to `this`, so it goes through
7515                // `put_super_value` rather than `put_field`. The receiver, prototype, key
7516                // and value are handed over together.
7517                if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
7518                    return self.assign_super(member, op, value);
7519                }
7520                // A store is blamed on the selector punctuator (`.` or `[`), the same
7521                // token a load is blamed on — the reference records `put_field obj.a`
7522                // at the `.`, so a setter that throws reports that column and not the
7523                // `=` of the assignment it sits in. The inner expressions restore their
7524                // own positions, so the selector's sticks for the store instructions.
7525                let saved = self.cur().cur_pos;
7526                self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7527                self.expr(&member.object)?;
7528                match &member.property {
7529                    MemberProp::Ident(property) => {
7530                        let atom = Atom::from_text(&property.name);
7531                        match op {
7532                            AssignOp::Assign => {
7533                                self.expr(value)?;
7534                                // `put_field` consumes the object and the value, so
7535                                // without `insert2` nothing is left over for the
7536                                // statement to drop.
7537                                self.state().no_value = !keep;
7538                                if keep {
7539                                    self.emit(Opcode::Insert2, &[]);
7540                                }
7541                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7542                            }
7543                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7544                                // `get_field2` leaves the object under the value, so
7545                                // the keep path has an object to dispose of. The store
7546                                // path must jump *over* that cleanup: falling into it
7547                                // would `nip` a stack that only holds the value.
7548                                let (keep_label, end) = (self.new_label(), self.new_label());
7549                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7550                                self.emit(Opcode::Dup, &[]);
7551                                self.emit_logical_test(op);
7552                                self.emit_jump(logical_jump(op), keep_label, &[]);
7553                                self.emit(Opcode::Drop, &[]);
7554                                self.expr(value)?;
7555                                self.emit(Opcode::Insert2, &[]);
7556                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7557                                self.emit_jump(Opcode::Goto, end, &[]);
7558                                self.place_label(keep_label);
7559                                self.emit(Opcode::Nip, &[]);
7560                                self.place_label(end);
7561                            }
7562                            _ => {
7563                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7564                                self.expr(value)?;
7565                                self.emit(compound_opcode(op), &[]);
7566                                self.state().no_value = !keep;
7567                                if keep {
7568                                    self.emit(Opcode::Insert2, &[]);
7569                                }
7570                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7571                            }
7572                        }
7573                    }
7574                    MemberProp::Computed(index) => {
7575                        self.expr(index)?;
7576                        match op {
7577                            AssignOp::Assign => {
7578                                self.expr(value)?;
7579                                self.state().no_value = !keep;
7580                                if keep {
7581                                    self.emit(Opcode::Insert3, &[]);
7582                                }
7583                                self.emit(Opcode::PutArrayEl, &[]);
7584                            }
7585                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7586                                let (keep_label, end) = (self.new_label(), self.new_label());
7587                                self.emit(Opcode::GetArrayEl3, &[]);
7588                                self.emit(Opcode::Dup, &[]);
7589                                self.emit_logical_test(op);
7590                                self.emit_jump(logical_jump(op), keep_label, &[]);
7591                                self.emit(Opcode::Drop, &[]);
7592                                self.expr(value)?;
7593                                self.emit(Opcode::Insert3, &[]);
7594                                self.emit(Opcode::PutArrayEl, &[]);
7595                                self.emit_jump(Opcode::Goto, end, &[]);
7596                                self.place_label(keep_label);
7597                                // Both the object and the index are left over.
7598                                self.emit(Opcode::Nip, &[]);
7599                                self.emit(Opcode::Nip, &[]);
7600                                self.place_label(end);
7601                            }
7602                            _ => {
7603                                self.emit(Opcode::GetArrayEl3, &[]);
7604                                self.expr(value)?;
7605                                self.emit(compound_opcode(op), &[]);
7606                                self.state().no_value = !keep;
7607                                if keep {
7608                                    self.emit(Opcode::Insert3, &[]);
7609                                }
7610                                self.emit(Opcode::PutArrayEl, &[]);
7611                            }
7612                        }
7613                    }
7614                    MemberProp::Private(name) => {
7615                        // `obj value` is on the stack, and every private store wants exactly
7616                        // that. A top-level private name cannot be assigned (the parser rejects
7617                        // `#x = 1`), so the only way here is `this.#x = …` inside the class.
7618                        //
7619                        // The reference emits `insert2` whether or not the value is wanted,
7620                        // so this does too: the copy left behind is the assignment expression's
7621                        // value, and a discarded one is simply never read.
7622                        let binding = format!("#{}", name.name);
7623                        let (kind, setter) = self.private_use(&binding, member.span)?;
7624                        match op {
7625                            AssignOp::Assign => {
7626                                self.expr(value)?;
7627                                if keep {
7628                                    self.emit(Opcode::Insert2, &[]);
7629                                }
7630                                self.private_store(&binding, kind, setter.as_deref())?;
7631                                self.state().no_value = !keep;
7632                            }
7633                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7634                                let (keep_label, end) = (self.new_label(), self.new_label());
7635                                self.emit(Opcode::Dup, &[]);
7636                                self.private_load(&binding, kind, member.span)?;
7637                                self.emit(Opcode::Dup, &[]);
7638                                self.emit_logical_test(op);
7639                                self.emit_jump(logical_jump(op), keep_label, &[]);
7640                                self.emit(Opcode::Drop, &[]);
7641                                self.expr(value)?;
7642                                self.emit(Opcode::Insert2, &[]);
7643                                self.private_store(&binding, kind, setter.as_deref())?;
7644                                self.emit_jump(Opcode::Goto, end, &[]);
7645                                self.place_label(keep_label);
7646                                self.emit(Opcode::Nip, &[]);
7647                                self.place_label(end);
7648                            }
7649                            _ => {
7650                                self.emit(Opcode::Dup, &[]);
7651                                self.private_load(&binding, kind, member.span)?;
7652                                self.expr(value)?;
7653                                self.emit(compound_opcode(op), &[]);
7654                                self.emit(Opcode::Insert2, &[]);
7655                                self.private_store(&binding, kind, setter.as_deref())?;
7656                            }
7657                        }
7658                    }
7659                }
7660                self.state().cur_pos = saved;
7661                Ok(())
7662            }
7663            // A destructuring assignment: the right-hand side is the expression's own
7664            // value, so it is evaluated once and kept under the pattern's stores.
7665            PatternKind::Array { .. } | PatternKind::Object { .. } => {
7666                self.expr(value)?;
7667                if keep {
7668                    self.emit(Opcode::Dup, &[]);
7669                }
7670                self.destructure(target, None)?;
7671                self.state().no_value = !keep;
7672                Ok(())
7673            }
7674            _ => Err(SyntaxError::new(
7675                "this assignment target is not supported by the compiler yet",
7676                target.span,
7677            )),
7678        }
7679    }
7680
7681    /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
7682    ///
7683    /// The stack has to carry four values — receiver, prototype, key, value — because
7684    /// `put_super_value` takes them together; the receiver is what makes a setter found on
7685    /// the prototype run with `this`, and the key has to survive until the store, which is
7686    /// why a compound form converts it to a property key once and `dup3`s rather than
7687    /// evaluating it twice.
7688    fn assign_super(
7689        &mut self,
7690        member: &MemberPattern,
7691        op: AssignOp,
7692        value: &Expr,
7693    ) -> Result<(), SyntaxError> {
7694        let saved = self.cur().cur_pos;
7695        self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7696        self.super_base();
7697        match &member.property {
7698            MemberProp::Ident(property) => self.emit(
7699                Opcode::PushAtomValue,
7700                &[Op::Atom(Atom::from_text(&property.name))],
7701            ),
7702            MemberProp::Computed(index) => self.expr(index)?,
7703            MemberProp::Private(_) => {
7704                return Err(SyntaxError::new(
7705                    "private fields are not supported by the compiler yet",
7706                    member.span,
7707                ));
7708            }
7709        }
7710        match op {
7711            AssignOp::Assign => {
7712                // The key is only converted once, by `put_super_value` itself, so a
7713                // computed key's `toString` runs exactly once.
7714                self.expr(value)?;
7715                self.emit(Opcode::Insert4, &[]);
7716                self.emit(Opcode::PutSuperValue, &[]);
7717            }
7718            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7719                let (keep_label, end) = (self.new_label(), self.new_label());
7720                self.emit(Opcode::ToPropkey, &[]);
7721                self.emit(Opcode::Dup3, &[]);
7722                self.emit(Opcode::GetSuperValue, &[]);
7723                self.emit(Opcode::Dup, &[]);
7724                self.emit_logical_test(op);
7725                self.emit_jump(logical_jump(op), keep_label, &[]);
7726                self.emit(Opcode::Drop, &[]);
7727                self.expr(value)?;
7728                self.emit(Opcode::Insert4, &[]);
7729                self.emit(Opcode::PutSuperValue, &[]);
7730                self.emit_jump(Opcode::Goto, end, &[]);
7731                self.place_label(keep_label);
7732                // The prototype and the key are still under the value that was read.
7733                self.emit(Opcode::Nip, &[]);
7734                self.emit(Opcode::Nip, &[]);
7735                self.emit(Opcode::Nip, &[]);
7736                self.place_label(end);
7737            }
7738            _ => {
7739                self.emit(Opcode::ToPropkey, &[]);
7740                self.emit(Opcode::Dup3, &[]);
7741                self.emit(Opcode::GetSuperValue, &[]);
7742                self.expr(value)?;
7743                self.emit(compound_opcode(op), &[]);
7744                self.emit(Opcode::Insert4, &[]);
7745                self.emit(Opcode::PutSuperValue, &[]);
7746            }
7747        }
7748        // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
7749        // is still on the stack when the store finishes, and the expression statement is
7750        // what disposes of it — the same arrangement as `put_field`, reached from the other
7751        // side: there the store consumes the value (`no_value`), here it leaves it
7752        // (`keep` already false, so nothing tells the statement otherwise).
7753        self.state().cur_pos = saved;
7754        Ok(())
7755    }
7756
7757    /// The test a logical assignment applies to the current value.
7758    ///
7759    /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
7760    /// assign, while `0 ||= b` must not.
7761    fn emit_logical_test(&mut self, op: AssignOp) {
7762        if op == AssignOp::Coalesce {
7763            self.emit(Opcode::IsUndefinedOrNull, &[]);
7764        }
7765    }
7766
7767    /// The private name `#name` this use site resolves against.
7768    ///
7769    /// The parser has already rejected a name no enclosing class declares, so a miss here
7770    /// means the compiler lost track of a class scope — which is worth a real error rather
7771    /// than an `unwrap`.
7772    fn private_use(
7773        &self,
7774        binding: &str,
7775        span: Span,
7776    ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
7777        ClassPlan::find(self, binding)
7778            .map(|use_| (use_.kind, use_.setter.clone()))
7779            .ok_or_else(|| {
7780                SyntaxError::new(
7781                    format!("the private name '{binding}' is out of scope here"),
7782                    span,
7783                )
7784            })
7785    }
7786
7787    /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
7788    ///
7789    /// The three readable kinds take three different instructions, because a private name
7790    /// holds three different things — a symbol, a method function, a getter function — and
7791    /// only the first one is a property read at all.
7792    fn private_load(
7793        &mut self,
7794        binding: &str,
7795        kind: PrivateKind,
7796        span: Span,
7797    ) -> Result<(), SyntaxError> {
7798        match kind {
7799            PrivateKind::Field => {
7800                self.emit_var(VarAction::Get, binding);
7801                self.emit(Opcode::GetPrivateField, &[]);
7802            }
7803            PrivateKind::Method => {
7804                self.emit_var(VarAction::Get, binding);
7805                self.emit(Opcode::CheckBrand, &[]);
7806                // `check_brand` reads `obj func` and leaves both; the method itself is what
7807                // `this.#m` evaluates to.
7808                self.emit(Opcode::Nip, &[]);
7809            }
7810            PrivateKind::Getter => {
7811                self.emit_var(VarAction::Get, binding);
7812                self.emit(Opcode::CheckBrand, &[]);
7813                self.emit(Opcode::CallMethod, &[Op::Int(0)]);
7814            }
7815            // `#a` is declared but never filled when only a setter exists, so reading it is
7816            // the same refusal as assigning to a `const`. The reference reports it with the
7817            // generic read-only wording and leaves the better message as a `XXX`.
7818            PrivateKind::Setter => self.emit(
7819                Opcode::ThrowError,
7820                &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7821            ),
7822        }
7823        let _ = span;
7824        Ok(())
7825    }
7826
7827    /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
7828    fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
7829        match kind {
7830            // A method *is* the callee, so only the check goes in between.
7831            PrivateKind::Method => {
7832                self.emit_var(VarAction::Get, binding);
7833                self.emit(Opcode::CheckBrand, &[]);
7834            }
7835            _ => self.private_load(binding, kind, Span::default())?,
7836        }
7837        Ok(())
7838    }
7839
7840    /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
7841    /// wanted back.
7842    ///
7843    /// A getter/setter pair is a *method call*, not a property store: the reference reads
7844    /// the setter out of its own binding and calls it with the receiver, which is why the
7845    /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
7846    /// keeps the assignment's value for an expression context.
7847    fn private_store(
7848        &mut self,
7849        binding: &str,
7850        kind: PrivateKind,
7851        setter: Option<&str>,
7852    ) -> Result<(), SyntaxError> {
7853        match kind {
7854            PrivateKind::Field => {
7855                self.emit_var(VarAction::Get, binding);
7856                self.emit(Opcode::PutPrivateField, &[]);
7857            }
7858            PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
7859                Some(setter) => {
7860                    self.emit_var(VarAction::Get, setter);
7861                    // `obj func value` -> `value obj func` for the check, and back again for
7862                    // the call, which wants `obj func arg`.
7863                    self.emit(Opcode::Swap, &[]);
7864                    self.emit(Opcode::Rot3r, &[]);
7865                    self.emit(Opcode::CheckBrand, &[]);
7866                    self.emit(Opcode::Rot3l, &[]);
7867                    self.emit(Opcode::CallMethod, &[Op::Int(1)]);
7868                    // The setter's return value is discarded; the assignment's own value is
7869                    // whatever the caller left underneath.
7870                    self.emit(Opcode::Drop, &[]);
7871                }
7872                None => self.emit(
7873                    Opcode::ThrowError,
7874                    &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7875                ),
7876            },
7877        }
7878        Ok(())
7879    }
7880
7881    fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
7882        // `x++` inside a `with` is a read-modify-write of a *property*, so the object is
7883        // resolved once for both halves. See [`Compiler::with_reference`].
7884        let unparened = argument.unparen();
7885        if let ExprKind::Ident(ident) = &unparened.kind {
7886            let name = ident.name.clone();
7887            if !self.visible_with_names(&name).is_empty() {
7888                return self.with_reference(
7889                    &name,
7890                    &mut |compiler, with_local| compiler.with_update(with_local, ident, op, prefix),
7891                    &mut |compiler| compiler.update_plain(op, unparened, prefix),
7892                );
7893            }
7894        }
7895        self.update_plain(op, argument, prefix)
7896    }
7897
7898    fn update_plain(
7899        &mut self,
7900        op: UpdateOp,
7901        argument: &Expr,
7902        prefix: bool,
7903    ) -> Result<(), SyntaxError> {
7904        let instruction = match (op, prefix) {
7905            (UpdateOp::Increment, true) => Opcode::Inc,
7906            (UpdateOp::Increment, false) => Opcode::PostInc,
7907            (UpdateOp::Decrement, true) => Opcode::Dec,
7908            (UpdateOp::Decrement, false) => Opcode::PostDec,
7909        };
7910        // `(y)++` and `((o.x))++` are the same updates as the unparenthesised forms: §13.4
7911        // evaluates the operand as a `LeftHandSideExpression` and the parentheses around a
7912        // reference change nothing — they do not copy the value. Reading `argument.kind`
7913        // directly therefore rejected every parenthesised target with "increment of a
7914        // non-variable", which is not a thing the language has (`target-cover-id`).
7915        let argument = argument.unparen();
7916        if let ExprKind::Member {
7917            object,
7918            property,
7919            optional: _,
7920        } = &argument.kind
7921        {
7922            // `o.x++` needs the receiver twice, so the last link is read with the
7923            // `get_*2`/`get_*3` form that keeps it, and the update is written back
7924            // with `put_field`/`put_array_el`. The reordering in between is what puts
7925            // the old value below the receiver for a postfix update and the new one
7926            // above it for a prefix one:
7927            //
7928            //   `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
7929            //   `obj val` → `inc`      → `obj new new` → `insert2` → `new obj new`
7930            //
7931            // This mirrors the reference instruction for instruction.
7932            self.expr(object)?;
7933            match property {
7934                MemberProp::Ident(name) => {
7935                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
7936                    self.emit(instruction, &[]);
7937                    self.emit(
7938                        if prefix {
7939                            Opcode::Insert2
7940                        } else {
7941                            Opcode::Perm3
7942                        },
7943                        &[],
7944                    );
7945                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
7946                }
7947                MemberProp::Computed(index) => {
7948                    self.expr(index)?;
7949                    self.emit(Opcode::GetArrayEl3, &[]);
7950                    self.emit(instruction, &[]);
7951                    self.emit(
7952                        if prefix {
7953                            Opcode::Insert3
7954                        } else {
7955                            Opcode::Perm4
7956                        },
7957                        &[],
7958                    );
7959                    self.emit(Opcode::PutArrayEl, &[]);
7960                }
7961                MemberProp::Private(name) => {
7962                    // The receiver is duplicated and the read keeps it, exactly as `get_field2`
7963                    // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
7964                    // `perm3` -> `old obj new` -> store.
7965                    let binding = format!("#{}", name.name);
7966                    let (kind, setter) = self.private_use(&binding, argument.span)?;
7967                    self.emit(Opcode::Dup, &[]);
7968                    self.private_load(&binding, kind, argument.span)?;
7969                    self.emit(instruction, &[]);
7970                    self.emit(
7971                        if prefix {
7972                            Opcode::Insert2
7973                        } else {
7974                            Opcode::Perm3
7975                        },
7976                        &[],
7977                    );
7978                    self.private_store(&binding, kind, setter.as_deref())?;
7979                }
7980            }
7981            return Ok(());
7982        }
7983        let ExprKind::Ident(name) = &argument.kind else {
7984            return Err(SyntaxError::new(
7985                "increment of a non-variable is not supported by the compiler yet",
7986                argument.span,
7987            ));
7988        };
7989        // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
7990        // reference's `inc_loc` folds those three into one, but it does so only in some
7991        // positions (a `for` update and not a bare statement, and never for a lexical
7992        // binding), so emitting it unconditionally would move *away* from its output.
7993        // The instruction is equivalent either way; matching the reference matters more
7994        // than saving two instructions.
7995        let _ = !std::mem::take(&mut self.state().discard_value);
7996        self.emit_var(VarAction::Get, &name.name);
7997        self.emit(instruction, &[]);
7998        if prefix {
7999            self.emit(Opcode::Dup, &[]);
8000        }
8001        self.emit_var(VarAction::Put, &name.name);
8002        Ok(())
8003    }
8004
8005    /// Compile an array literal.
8006    ///
8007    /// The reference splits this into three phases, and the split is load-bearing
8008    /// rather than an optimisation detail:
8009    ///
8010    /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
8011    ///    the array in one instruction.
8012    /// 2. **Everything up to the first spread** is appended with explicit indices
8013    ///    (`define_field <index>`), because a hole has no element to pass to
8014    ///    `array_from`. A hole here is what makes `length` need fixing up: an
8015    ///    explicit index does not extend the array the way a pushed element does.
8016    /// 3. **From the first spread on** the index lives on the stack, so `append` and
8017    ///    `define_array_el` can consume it and `inc` advances it.
8018    ///
8019    /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
8020    /// forces phase 2, and `[...a]` forces phase 3.
8021    fn array_literal(
8022        &mut self,
8023        elements: &[Option<ArrayElement>],
8024        span: Span,
8025    ) -> Result<(), SyntaxError> {
8026        let _ = span;
8027        let mut index: u32 = 0;
8028        let mut cursor = 0usize;
8029
8030        // Phase 1: a leading run of plain elements, at most 32 of them.
8031        while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
8032            if index >= 32 {
8033                break;
8034            }
8035            self.expr(element)?;
8036            index += 1;
8037            cursor += 1;
8038        }
8039        self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
8040
8041        // Phase 2: explicit indices, up to the first spread.
8042        let mut need_length = false;
8043        while let Some(element) = elements.get(cursor) {
8044            if matches!(element, Some(ArrayElement::Spread(_))) {
8045                break;
8046            }
8047            need_length = true;
8048            if let Some(ArrayElement::Expr(expression)) = element {
8049                self.expr(expression)?;
8050                self.emit_define_index(index);
8051                need_length = false;
8052            }
8053            index += 1;
8054            cursor += 1;
8055        }
8056
8057        if cursor >= elements.len() {
8058            if need_length {
8059                // `define_field` cannot set `length`, which is not configurable.
8060                self.emit(Opcode::Dup, &[]);
8061                self.push_number(index as f64);
8062                self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
8063            }
8064            return Ok(());
8065        }
8066
8067        // Phase 3: the index moves onto the stack for the spreading tail.
8068        //
8069        // `need_length` deliberately carries over from phase 2: a hole before the
8070        // first spread still has to be reflected in `length`, and only the final
8071        // check can do it because the array is not finished until the tail is
8072        // appended.
8073        self.push_number(index as f64);
8074        while let Some(element) = elements.get(cursor) {
8075            match element {
8076                Some(ArrayElement::Spread(expression)) => {
8077                    // `append` copies an iterable and leaves the next index behind,
8078                    // so no `inc` is needed here.
8079                    self.expr(spread_argument(expression))?;
8080                    self.emit(Opcode::Append, &[]);
8081                }
8082                None | Some(ArrayElement::Expr(_)) => {
8083                    need_length = true;
8084                    if let Some(ArrayElement::Expr(expression)) = element {
8085                        self.expr(expression)?;
8086                        self.emit(Opcode::DefineArrayEl, &[]);
8087                        need_length = false;
8088                    }
8089                    self.emit(Opcode::Inc, &[]);
8090                }
8091            }
8092            cursor += 1;
8093        }
8094        if need_length {
8095            self.emit(Opcode::Dup1, &[]);
8096            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
8097        } else {
8098            self.emit(Opcode::Drop, &[]);
8099        }
8100        Ok(())
8101    }
8102
8103    /// `define_field` with an array-index atom, which is how phase 2 stores elements.
8104    fn emit_define_index(&mut self, index: u32) {
8105        self.emit(
8106            Opcode::DefineField,
8107            &[Op::Atom(Atom::from_text(&index.to_string()))],
8108        );
8109    }
8110
8111    // -- functions ---------------------------------------------------------
8112
8113    fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
8114        self.compile_function_with_name(func, false)
8115    }
8116
8117    /// Compile a function, recording whether it is a *named function expression*.
8118    ///
8119    /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
8120    /// must not leak outside. The reference does that by declaring `g` as a local of
8121    /// the function itself and initialising it with `special_object 2` (the current
8122    /// function), which is why this has to be known at compile time.
8123    fn compile_function_with_name(
8124        &mut self,
8125        func: &ast::Function,
8126        is_expression: bool,
8127    ) -> Result<CompiledFunction, SyntaxError> {
8128        let kind = match (func.is_generator, func.is_async) {
8129            (false, false) => FunctionKind::Normal,
8130            (true, false) => FunctionKind::Generator,
8131            (false, true) => FunctionKind::Async,
8132            (true, true) => FunctionKind::AsyncGenerator,
8133        };
8134        let mut state = FnState::new(
8135            func.name
8136                .as_ref()
8137                .map(|n| n.name.clone())
8138                .unwrap_or_default(),
8139            kind,
8140        );
8141        // The function's own mode, recorded by the parser. Inheriting the enclosing
8142        // function's instead let a nested `"use strict"` directive be ignored, so the
8143        // body ran with sloppy `this`, sloppy `arguments` and no const checks.
8144        state.strict = func.strict;
8145        // A function defined inside a `with` block keeps seeing that object: the guard
8146        // chain names the enclosing `<with>` locals, which resolve outward into closure
8147        // variables exactly like any other captured binding.
8148        state.inherited_with_names = self.cur().with_names.len();
8149        state.with_names = self.cur().with_names.clone();
8150        state.is_arrow = func.is_arrow;
8151        state.created_in_block = self.cur().current_block;
8152        // A default anywhere in the parameter list is what gives the function two
8153        // variable environments. The reference decides this the same way: it scans the
8154        // parenthesis for a top-level `=`, so a destructured name without a default
8155        // stays a plain function-scope binding.
8156        state.in_params = false;
8157        // The reference scans the parenthesis for *any* `=`, including one nested inside
8158        // a pattern, so `function f({a = 1})` has parameter expressions even though the
8159        // parameter itself carries no initialiser.
8160        state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
8161        // `IsSimpleParameterList`: no default, no rest, no destructuring. Unlike the
8162        // flag above this looks at the *shape* of each parameter, not just for `=`.
8163        state.simple_parameter_list = func
8164            .params
8165            .iter()
8166            .all(|pattern| matches!(pattern.kind, PatternKind::Ident(_)));
8167        // A function born inside a parameter list inherits the prohibition: it must not
8168        // see the body bindings of the function it was created in.
8169        state.created_in_params = self.cur().in_params || self.cur().created_in_params;
8170        // A class constructor knows what it is only because the class told it.
8171        if let Some(kind) = self.cur().class_ctor_pending {
8172            state.ctor_kind = kind;
8173        }
8174        // A named *expression* binds its own name; a declaration's name is already
8175        // bound in the enclosing scope.
8176        state.self_name = if is_expression && !func.is_arrow {
8177            func.name.as_ref().map(|n| n.name.clone())
8178        } else {
8179            None
8180        };
8181        // Keep the written range so `Function.prototype.toString` can answer with the
8182        // original text rather than `[native code]`.
8183        //
8184        // It starts at the *parameter list*, not at the function: §20.2.3.5 removes the
8185        // accessor and generator prefixes, and for a method it must not include the name
8186        // or a leading `static`. `params_span` is exactly that boundary.
8187        // A *method* keeps the old `[native code]` answer: its reported text is defined
8188        // by the method-definition grammar (no name, no `static`, no `get`/`set`, but
8189        // the comments in between kept verbatim), and reconstructing that from a byte
8190        // span got it wrong in more cases than it got right. A plain function and an
8191        // arrow are the shapes libraries actually introspect, and those are exact.
8192        // A method's reported text starts at its **key** — `m(){}`, `[expr](){}`,
8193        // `#f /* a */ ( /* b */ ) {}` — which is exactly where the parser put `span.start`,
8194        // so the same slice works for every form. (`Params_span` is the boundary that
8195        // excludes `static`/`async`/`get`, which the spec's method grammar also omits.)
8196        // `source_span` is set only where the reported text is not the function's own
8197        // range — a class's constructor reports the whole class definition.
8198        let reported = func.source_span.unwrap_or(func.span);
8199        state.span = Some((reported.start.offset as usize, reported.end.offset as usize));
8200        state.line = func.span.start.line;
8201        state.column = func.span.start.column;
8202        // A function body has no hidden `<ret>` local; the value comes back on
8203        // the stack. Only a script keeps one.
8204        // Parameters are positional, so even a pattern occupies one argument slot. A
8205        // simple name is that slot itself; anything else (a pattern, a default, a rest
8206        // parameter) takes an anonymous slot and is unpicked into locals at the top of
8207        // the body, which is the only way one argument can bind several names.
8208        let mut prologue: Vec<(usize, Pattern)> = Vec::new();
8209        // `.length` stops at the first parameter that can be substituted: a default
8210        // fills a missing argument in, and a rest parameter absorbs the rest.
8211        let mut defined_args = func.params.len() as u32;
8212        for (index, param) in func.params.iter().enumerate() {
8213            match simple_parameter(param) {
8214                Some(name) => state.args.push(VarDef::var(name.name.clone())),
8215                None => {
8216                    state.args.push(VarDef::var(ANONYMOUS_BINDING));
8217                    prologue.push((index, param.clone()));
8218                }
8219            }
8220        }
8221        // A default anywhere before the end also ends the count, which the loop above
8222        // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
8223        for (position, param) in func.params.iter().enumerate() {
8224            if matches!(
8225                param.kind,
8226                PatternKind::Assign { .. } | PatternKind::Rest(_)
8227            ) {
8228                defined_args = position as u32;
8229                break;
8230            }
8231        }
8232        state.defined_args = defined_args;
8233        state.param_prologue = prologue;
8234        let depth = self.stack.len();
8235        self.stack.push(state);
8236        let result = self.compile_function_body(func);
8237        if result.is_err() {
8238            // A failed compile must not leave its `FnState` behind. Every caller
8239            // reads `self.state()` as "the function being compiled", so a leftover
8240            // frame silently retargets all later bookkeeping at a dead function.
8241            self.stack.truncate(depth);
8242        }
8243        result
8244    }
8245
8246    /// The body of a function, with its frame already pushed.
8247    fn compile_function_body(
8248        &mut self,
8249        func: &ast::Function,
8250    ) -> Result<CompiledFunction, SyntaxError> {
8251        let body_key = func.params_span.end.offset as u64;
8252        // Where the body begins, in source order. The runtime needs this to tell a
8253        // closure created by a default expression from one the body creates — the two see
8254        // different variable environments — and a bytecode offset would not survive the
8255        // instruction shuffling that building the frame does. Positions are in source
8256        // order, so a comparison answers it.
8257        self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
8258        self.push_block(body_key, NO_PARENT);
8259        self.state().body_block = body_key;
8260        // An arrow with an expression body has no statements; the expression is
8261        // its `return`. Building the statement here keeps one code path below, and
8262        // matters for correctness beyond convenience: returning early with the new
8263        // `FnState` still on the stack would leave the compiler looking at the
8264        // wrong function, which surfaces as an unrelated underflow later.
8265        let concise = match &func.body {
8266            js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
8267                StmtKind::Return(Some(Box::new((**value).clone()))),
8268                value.span,
8269            )),
8270            js_parse::ast::FunctionBody::Block(_) => None,
8271        };
8272        let body: &[Stmt] = match &concise {
8273            Some(stmt) => std::slice::from_ref(stmt),
8274            None => func
8275                .body
8276                .statements()
8277                .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
8278        };
8279        let prologue = std::mem::take(&mut self.state().param_prologue);
8280        let has_param_scope = self.cur().has_parameter_expressions;
8281        // The parameter scope's own bindings, declared in source order.
8282        //
8283        // With parameter expressions the list gets a variable environment of its own, and
8284        // every name it binds is a `let` there. That is what puts the *list* in the
8285        // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
8286        // and `function f(x = y, y){}` does the same, where a single shared environment
8287        // would answer `undefined` to both.
8288        if has_param_scope {
8289            let mut declared: Vec<String> = Vec::new();
8290            for param in &func.params {
8291                let mut names = Vec::new();
8292                param.bound_names(&mut names);
8293                for name in names {
8294                    if declared.contains(&name.name) {
8295                        continue;
8296                    }
8297                    declared.push(name.name.clone());
8298                    self.declare_param_binding(&name.name);
8299                }
8300            }
8301        }
8302        // A pattern parameter binds its names as function-scope locals, so they have to
8303        // exist — and be unpicked from the argument — before the body runs. With a
8304        // parameter scope these are the *second* environment: the pattern fills the
8305        // parameter's copy, and the body's binding is filled from it afterwards.
8306        for (_, pattern) in &prologue {
8307            let mut names = Vec::new();
8308            pattern.bound_names(&mut names);
8309            for name in names {
8310                self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
8311            }
8312        }
8313        self.hoist(body, body_key)?;
8314        // A constructor's prologue is not a parameter unpacking but the `this` binding:
8315        // a base constructor takes the receiver, a derived one starts in the dead zone
8316        // because only `super()` may produce it.
8317        match self.cur().ctor_kind {
8318            CtorKind::None => {}
8319            CtorKind::Base => {
8320                self.begin_this_local();
8321                self.emit(Opcode::CheckCtor, &[]);
8322                // Instance fields are installed at the top of a base constructor's body,
8323                // before any statement — `class C { x = 1; constructor() { this.x } }` sees
8324                // `1`. This used to be emitted at the *tail*, which made every field read
8325                // `undefined` inside the constructor that declared it.
8326                self.call_field_initialiser();
8327            }
8328            CtorKind::Derived => {
8329                self.declare("this", VarDef::lexical("this"));
8330                let slot = self.cur().vars.len() as u32 - 1;
8331                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8332                self.emit(Opcode::CheckCtor, &[]);
8333            }
8334        }
8335        // Entering the parameter list: everything it binds starts in the dead zone.
8336        // The order is the reference's — it walks the scope chain, which is prepended, so
8337        // the bindings come out newest first.
8338        for name in self.param_binding_names().into_iter().rev() {
8339            if let Some(slot) = self.param_binding_slot(&name) {
8340                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8341            }
8342        }
8343        // The whole parameter list is one scope, and nothing in the body exists yet, so
8344        // every name it mentions resolves against the parameter bindings and outward.
8345        self.state().in_params = has_param_scope;
8346        for (index, param) in func.params.iter().enumerate() {
8347            if let Some(pattern) = prologue_pattern(&prologue, index) {
8348                // A destructuring parameter *initialises* its bindings: with a parameter
8349                // scope they are the list's own `let`s, which is why the stores skip the
8350                // dead-zone check, and why the reference reads their properties with
8351                // `get_field2` — a `let` needs no reference.
8352                let kind = if has_param_scope {
8353                    VarDeclKind::Let
8354                } else {
8355                    VarDeclKind::Var
8356                };
8357                match &pattern.kind {
8358                    // `...rest` collects what is left rather than reading one slot.
8359                    PatternKind::Rest(inner) => {
8360                        self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8361                        self.destructure(inner, Some(kind))?;
8362                    }
8363                    _ => {
8364                        self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8365                        self.destructure(pattern, Some(kind))?;
8366                    }
8367                }
8368                continue;
8369            }
8370            // A plain name binds straight from its argument slot. With a parameter scope
8371            // the slot is also copied into the parameter binding, which is what a later
8372            // default (or a closure made among the defaults) reads.
8373            let Some(name) = simple_parameter(param) else {
8374                continue;
8375            };
8376            let target = self.param_binding_slot(&name.name);
8377            if matches!(param.kind, PatternKind::Rest(_)) {
8378                self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8379                if let Some(slot) = target {
8380                    self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
8381                }
8382                // `put_arg` rather than `set_arg`: the array is the last thing on the
8383                // stack and nothing keeps it. Named by hand because a name in the
8384                // parameter list resolves to the parameter binding, and this store has to
8385                // reach the *argument* — that is what the body reads.
8386                self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
8387                continue;
8388            }
8389            if let PatternKind::Assign { default, .. } = &param.kind {
8390                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8391                let has_value = self.new_label();
8392                self.emit(Opcode::Dup, &[]);
8393                self.emit(Opcode::IsUndefined, &[]);
8394                self.emit_jump(Opcode::IfFalse, has_value, &[]);
8395                self.emit(Opcode::Drop, &[]);
8396                self.expr(default)?;
8397                self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
8398                // The argument slot keeps the substituted value, because the *body* reads
8399                // the slot rather than the parameter binding — so this store is named
8400                // explicitly, like the rest parameter's.
8401                self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8402                self.place_label(has_value);
8403                if let Some(slot) = target {
8404                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8405                }
8406                continue;
8407            }
8408            if let Some(slot) = target {
8409                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8410                self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8411            }
8412        }
8413        // Copy the parameter scope into the body. A plain parameter needs nothing: the
8414        // body reads its argument slot, and the list kept the two in step. A name a
8415        // pattern bound has no argument slot of its own, so the body gets a `var` filled
8416        // from the parameter's copy — and *that* is why an assignment inside a default
8417        // does not reach the body.
8418        if has_param_scope {
8419            for (_, pattern) in &prologue {
8420                let mut names = Vec::new();
8421                pattern.bound_names(&mut names);
8422                for name in names {
8423                    let Some(slot) = self.param_binding_slot(&name.name) else {
8424                        continue;
8425                    };
8426                    let Some(body) = self.body_var_slot(&name.name) else {
8427                        continue;
8428                    };
8429                    self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
8430                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
8431                }
8432            }
8433        }
8434        // The parameter list is over; from here on a direct `eval` belongs to the body.
8435        self.state().in_params = false;
8436        // Entering the body's own scope comes *after* the parameter list: the body's
8437        // `let`s are not in existence while the defaults run, and the reference emits
8438        // their `set_loc_uninitialized` only once the parameters are bound.
8439        self.emit_scope_enter(body_key);
8440        // A generator starts suspended: `initial_yield` parks the body so that creating one
8441        // runs no body code until the first `next()`.
8442        //
8443        // It comes *after* the parameter unpacking, not before, because a parameter
8444        // initialiser is not body code — `function* g(a = sideEffect())` must run
8445        // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
8446        // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
8447        // until the first `next()` and 29 test262 cases that check for a synchronous throw
8448        // saw none at all.
8449        //
8450        // An async function does **not** get one. Its body runs synchronously up to the
8451        // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
8452        // before its caller's next statement — so an `initial_yield` here would park the
8453        // body before it started, which is not fixable at run time: the suspension looks
8454        // exactly like a real `await`.
8455        if self.cur().kind.is_generator() {
8456            self.emit(Opcode::InitialYield, &[]);
8457        }
8458        // Through `stmts`: the body is a block, and a `using` declaration in it is a
8459        // disposal region.
8460        self.stmts(body)?;
8461        // The implicit return only exists if control can actually get here: an
8462        // infinite loop never falls off the end.
8463        if self.end_is_reachable() {
8464            if self.cur().is_suspending() {
8465                // Falling off the end finishes the generator with `undefined`, and the
8466                // value is what tells the resume machinery "completed" rather than
8467                // "suspended".
8468                self.emit(Opcode::Undefined, &[]);
8469                self.emit(Opcode::ReturnAsync, &[]);
8470            } else {
8471                self.emit_class_constructor_tail();
8472            }
8473        }
8474        // Resolution runs while this function is still on the stack: capturing a
8475        // variable from an enclosing function means reaching into that
8476        // function's state, which requires the whole chain to be present.
8477        Ok(self.finish_current())
8478    }
8479
8480    /// Put every binding of a function that contains a direct `eval` into a cell.
8481    ///
8482    /// A direct eval can name any binding in scope, and any closure it creates has to
8483    /// keep sharing that binding after the function returns — `for (let i …)
8484    /// eval("push(() => i)")` collects one closure per iteration and each must read its
8485    /// own `i`. A copy in a side table would freeze the value, so the binding has to be
8486    /// a cell. Doing this unconditionally for such functions is the cheap, honest
8487    /// answer: the alternative is knowing at compile time which names a string will
8488    /// mention.
8489    fn capture_everything_for_eval(&mut self) {
8490        let current = self.stack.len() - 1;
8491        if !self.stack[current].has_direct_eval {
8492            return;
8493        }
8494        for arg in &mut self.stack[current].args {
8495            arg.is_captured = true;
8496        }
8497        for var in &mut self.stack[current].vars {
8498            var.is_captured = true;
8499        }
8500    }
8501
8502    /// Whether the current position in the instruction stream can be reached.
8503    ///
8504    /// A walk over the control-flow graph, using labels as instruction indices.
8505    /// The reference does the same thing to decide whether an implicit
8506    /// `return_undef` is needed.
8507    fn end_is_reachable(&self) -> bool {
8508        let state = self.cur();
8509        reachable_instructions(state, state.insns.len())[state.insns.len()]
8510    }
8511
8512    /// Resolve and assemble the function on top of the compiler stack, then pop
8513    /// it.
8514    fn finish_current(&mut self) -> CompiledFunction {
8515        self.provide_param_arguments();
8516        self.provide_arguments();
8517        self.provide_this_local();
8518        self.provide_new_target_local();
8519        self.provide_home_object_local();
8520        self.provide_active_func_local();
8521        self.provide_self_name();
8522        self.materialize_eval_sites();
8523        self.capture_everything_for_eval();
8524        let (mut resolved, resolved_pos) = resolve(&mut self.stack);
8525        // Captured bindings need a reference cell; the count goes in the header so
8526        // the runtime knows how many cells to allocate on entry.
8527        let current = self.stack.len() - 1;
8528        let captured = self.stack[current]
8529            .args
8530            .iter()
8531            .filter(|a| a.is_captured)
8532            .count()
8533            + self.stack[current]
8534                .vars
8535                .iter()
8536                .filter(|v| v.is_captured)
8537                .count();
8538        self.stack[current].var_ref_count = captured as u32;
8539        // The scope chain is only final now that every binding is known.
8540        rebuild_scope_chain(&mut self.stack[current]);
8541        let (code, stack_size, positions) =
8542            assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
8543        let _ = &mut resolved;
8544        let mut state = self.stack.pop().expect("a function is being compiled");
8545        CompiledFunction {
8546            name: state.name,
8547            kind: state.kind,
8548            strict: state.strict,
8549            is_derived_constructor: matches!(state.ctor_kind, CtorKind::Derived),
8550            is_arrow: state.is_arrow,
8551            has_parameter_expressions: state.has_parameter_expressions,
8552            simple_parameter_list: state.simple_parameter_list,
8553            body_start: state.body_start,
8554            args: state.args,
8555            defined_args: state.defined_args,
8556            vars: state.vars,
8557            closure_vars: state.closure_vars,
8558            cpool: state.cpool,
8559            atoms: state.atoms,
8560            code,
8561            stack_size,
8562            var_ref_count: state.var_ref_count,
8563            positions,
8564            source: self.function_source(state.span, state.line, state.column),
8565            line: state.line,
8566            column: state.column,
8567            filename: None,
8568            eval_sites: state.eval_sites,
8569            module: state.module.take().map(Box::new),
8570        }
8571    }
8572}
8573
8574/// Assign each binding a scope level and rebuild the scope chains.
8575///
8576/// Levels are numbered in the order the blocks appear, with 0 reserved for the
8577/// function scope where `var` and hoisted functions live. Every binding outside
8578/// level 0 gets a `scope_next` link to the next binding visible from the same
8579/// point, so walking a block's chain enumerates exactly the bindings live there.
8580///
8581/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
8582/// point at `b`, which is declared later in the source but earlier in the chain.
8583fn rebuild_scope_chain(state: &mut FnState) {
8584    // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
8585    // real block that happens to start at offset zero keeps its own level instead of
8586    // being merged into the function scope.
8587    let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
8588    for block in &state.blocks {
8589        if !levels.contains(&block.key) {
8590            levels.push(block.key);
8591        }
8592    }
8593    let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
8594    let parent_level = |level: usize| -> usize {
8595        if level == 0 {
8596            return 0;
8597        }
8598        let key = levels[level];
8599        let parent = state
8600            .blocks
8601            .iter()
8602            .find(|b| b.key == key)
8603            .map(|b| b.parent)
8604            .unwrap_or(FUNCTION_SCOPE);
8605        level_of(parent)
8606    };
8607
8608    // Own bindings per level, in declaration order.
8609    let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
8610    let keys: Vec<u64> = (0..state.vars.len())
8611        .map(|index| {
8612            state
8613                .var_block
8614                .get(index)
8615                .copied()
8616                .unwrap_or(FUNCTION_SCOPE)
8617        })
8618        .collect();
8619    for (index, key) in keys.into_iter().enumerate() {
8620        // The parameter scope is not a block: it is a level of its own with no parent,
8621        // assigned below. Letting it land in level 0 would chain the body's bindings onto
8622        // it, which the reference does not do — the two environments are siblings.
8623        if key == PARAM_SCOPE {
8624            continue;
8625        }
8626        let level = level_of(key);
8627        state.vars[index].scope_level = level as u32;
8628        // A `catch` parameter is part of the runtime scope chain even though it is
8629        // not lexical: the handler's own bindings chain on to it, which is why the
8630        // reference prints `let y [next:1]` with `e` at 1.
8631        if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
8632        {
8633            own[level].push(index);
8634        }
8635    }
8636
8637    // A scope's chain is its own bindings in reverse declaration order followed
8638    // by the enclosing scope's chain.
8639    let mut head = vec![-1i32; levels.len()];
8640    for level in 0..levels.len() {
8641        let inherited = if level == 0 {
8642            -1
8643        } else {
8644            head[parent_level(level)]
8645        };
8646        let chain: Vec<usize> = own[level].iter().rev().copied().collect();
8647        head[level] = chain.first().map_or(inherited, |first| *first as i32);
8648        for (position, &index) in chain.iter().enumerate() {
8649            let next = chain
8650                .get(position + 1)
8651                .map_or(inherited, |next| *next as i32);
8652            state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
8653        }
8654    }
8655    state.block_heads = head;
8656
8657    // The parameter list is a scope of its own, and it has no parent: the reference pops
8658    // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
8659    // the `-1` a block uses. A level past every real block keeps it out of the walk above
8660    // — nothing but the dump reads it — and the links run newest-to-oldest through the
8661    // bindings themselves, which is the order `set_loc_uninitialized` walks.
8662    let param_level = levels.len() as u32;
8663    let mut previous: Option<usize> = None;
8664    for index in 0..state.vars.len() {
8665        if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
8666        {
8667            continue;
8668        }
8669        state.vars[index].scope_level = param_level;
8670        state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
8671        previous = Some(index);
8672    }
8673}
8674
8675/// This is where names become slots and where the temporal dead zone shows up in
8676/// the instruction stream: a read of a `let`/`const` binding compiles to
8677/// `get_loc_check`, which throws if the binding is still uninitialised.
8678///
8679/// The peephole pass from the reference implementation is applied at the end,
8680/// for the same reason it is applied to resolved bytecode there: the patterns are
8681/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
8682/// resolution. Deleted instructions stay in the list as `None` so that label
8683/// indices remain valid; [`Assembler`] maps them to byte offsets.
8684/// A resolved instruction and the source position it came from.
8685type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
8686
8687/// A resolved instruction paired with its position, which is what `assemble` consumes.
8688type PositionedInsn = (Opcode, Vec<Op>);
8689
8690fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
8691    let current = stack.len() - 1;
8692    // Dead-code elimination, on the symbolic form where labels are still
8693    // instruction indices. A `break` inside a loop leaves the trailing `goto`
8694    // unreachable, and a `return` leaves everything after it unreachable; the
8695    // reference drops both. Doing it here means the emitter never has to think
8696    // about reachability.
8697    strip_empty_gosubs(stack, current);
8698    eliminate_dead_code(stack, current);
8699    let insns = std::mem::take(&mut stack[current].insns);
8700    // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
8701    // `insns`, and every arm below pushes exactly one instruction, so the positions
8702    // stay aligned with `out`.
8703    let positions = std::mem::take(&mut stack[current].insn_pos);
8704    let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
8705    let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
8706    for (index, insn) in insns.iter().enumerate() {
8707        let pos = positions.get(index).copied().flatten();
8708        out_pos.push(pos);
8709        match insn {
8710            Insn::Fixed { op, operands } => {
8711                let operands = operands
8712                    .iter()
8713                    .map(|operand| match operand {
8714                        Op::Atom(atom) => {
8715                            Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
8716                        }
8717                        other => other.clone(),
8718                    })
8719                    .collect();
8720                out.push(Some((*op, operands)));
8721            }
8722            Insn::Var {
8723                action,
8724                name,
8725                block,
8726                in_params,
8727            } => {
8728                // Both reads and writes in the parameter list address the parameter
8729                // scope. That is what puts the list in the temporal dead zone — a read of
8730                // a later parameter is `get_loc_check` on an uninitialised slot — and it
8731                // is also what keeps an assignment made inside a default away from the
8732                // body, which sees a separate environment.
8733                let slot = resolve_slot(stack, current, name, *block, *in_params);
8734                // A store to the name of a named function expression is special: the
8735                // reference drops it in sloppy mode and throws in strict mode, because
8736                // the binding is immutable but only *checked* when the body is strict.
8737                // The same rule applies when the name is reached through a closure:
8738                // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
8739                // the store in the arrow too, not just in the function that owns the
8740                // binding. Reaching the owner means walking the chain of closure
8741                // entries, which is what `self_name_binding` does.
8742                let self_name = matches!(action, VarAction::Put | VarAction::Set)
8743                    .then(|| {
8744                        // A local of this function is the common case and needs no
8745                        // chain walk; only an access that resolves elsewhere can be
8746                        // pointing at an enclosing function's name binding.
8747                        if let Slot::Loc(index) = slot {
8748                            stack[current]
8749                                .vars
8750                                .get(index as usize)
8751                                .filter(|var| var.kind == VarKind::FunctionName)
8752                                .map(|var| var.is_const)
8753                        } else {
8754                            self_name_binding(stack, current, name, *block)
8755                        }
8756                    })
8757                    .flatten();
8758                if let Some(is_const) = self_name {
8759                    out.push(Some(if is_const {
8760                        (
8761                            Opcode::ThrowError,
8762                            vec![
8763                                Op::AtomId(intern_atom(&mut stack[current], name)),
8764                                Op::Int(0),
8765                            ],
8766                        )
8767                    } else {
8768                        (Opcode::Drop, Vec::new())
8769                    }));
8770                    continue;
8771                }
8772                out.push(Some(variable_instruction(stack, current, *action, slot)));
8773            }
8774            Insn::CloseCaptured { name, block } => {
8775                // The block matters: a loop variable is scoped to the `for` head's own
8776                // block, so resolving it against block 0 would miss it entirely and
8777                // silently emit nothing.
8778                let slot = resolve_slot(stack, current, name, *block, false);
8779                // Only a local with a reference cell has anything to close. A global
8780                // or a never-captured local resolves to no instruction at all, which
8781                // keeps the bytecode identical to the reference's.
8782                if let Slot::Loc(index) = slot
8783                    && stack[current]
8784                        .vars
8785                        .get(index as usize)
8786                        .is_some_and(|v| v.is_captured)
8787                {
8788                    out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
8789                } else {
8790                    out.push(None);
8791                }
8792            }
8793            Insn::DeleteVar { name } => {
8794                // A binding — a local, an argument, or a declared global — cannot be
8795                // deleted, and the reference encodes that as a constant `push_false`.
8796                // Only an implicit global needs the runtime lookup.
8797                if matches!(
8798                    resolve_slot(stack, current, name, 0, false),
8799                    Slot::Global(_)
8800                ) {
8801                    let atom = intern_atom(&mut stack[current], name);
8802                    out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
8803                } else {
8804                    out.push(Some((Opcode::PushFalse, Vec::new())));
8805                }
8806            }
8807            Insn::Dead => out.push(None),
8808        }
8809    }
8810    // Which label (if any) sits on each instruction, so the jump patterns can
8811    // tell whether they would cross a jump target.
8812    let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
8813    for (id, placed) in stack[current].labels.iter().enumerate() {
8814        if let Some(index) = *placed
8815            && index < label_at.len()
8816            && label_at[index].is_none()
8817        {
8818            label_at[index] = Some(id as u32);
8819        }
8820    }
8821    if std::env::var_os("QJS_DEBUG").is_some() {
8822        eprintln!("--- peephole entry ---");
8823        for (i, e) in out.iter().enumerate() {
8824            eprintln!("{i}: {e:?}");
8825        }
8826        eprintln!("label_at: {label_at:?}");
8827    }
8828    peephole(&mut out, &label_at, &stack[current].labels);
8829    (out, out_pos)
8830}
8831
8832/// Find where `name` lives, capturing it in an enclosing function when needed.
8833///
8834/// The search runs outward through the enclosing functions' states, which are
8835/// still on the compiler stack while a nested function is resolved. Finding the
8836/// name in an enclosing function is what creates a closure reference, and every
8837/// function in between has to forward it — a function can only reach its own
8838/// parent's frame.
8839///
8840/// A name declared nowhere is a global. The reference does *not* look it up by
8841/// name from the inner function: the top-level function gets one `[global]`
8842/// entry and every nested function gets a `[global_ref<n>]` pointing at its
8843/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
8844/// rather than `[global]`.
8845/// The lexical blocks enclosing `block`, innermost first.
8846fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
8847    let mut chain = Vec::new();
8848    let mut current = Some(block);
8849    while let Some(key) = current {
8850        // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
8851        // explicitly (rather than on "no block with this key") is what keeps a block
8852        // that happens to sit at offset zero from being mistaken for the terminator.
8853        if key == NO_PARENT || chain.contains(&key) {
8854            break;
8855        }
8856        chain.push(key);
8857        current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
8858    }
8859    chain
8860}
8861
8862/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
8863///
8864/// The binding may be several functions away: an arrow nested in `function myfunc`
8865/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
8866/// means following `Ref` entries down and then reading the owning function's var table.
8867fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
8868    let state = stack.get(current)?;
8869    // A parameter shadows everything and is never a function-expression name.
8870    if state.args.iter().any(|arg| arg.name == name) {
8871        return None;
8872    }
8873    // A local of this very function: the answer is in its var table.
8874    if let Some(index) = local_slot_index(state, name, block) {
8875        let var = state.vars.get(index)?;
8876        return (var.kind == VarKind::FunctionName).then_some(var.is_const);
8877    }
8878    // Otherwise the name lives further out, and the closure entry says how to get
8879    // there. `Local` names the owner's slot directly; `Ref` names the next level's
8880    // closure entry, so the walk continues downwards.
8881    let mut level = current;
8882    let mut index = state
8883        .closure_vars
8884        .iter()
8885        .position(|closure| closure.name == name)?;
8886    loop {
8887        let state = stack.get(level)?;
8888        let closure = state.closure_vars.get(index)?;
8889        match closure.closure_type {
8890            ClosureType::Local => {
8891                let owner = stack.get(level.checked_sub(1)?)?;
8892                let var = owner.vars.get(closure.var_idx as usize)?;
8893                return (var.kind == VarKind::FunctionName).then_some(var.is_const);
8894            }
8895            ClosureType::Arg => return None,
8896            ClosureType::Ref => {
8897                level -= 1;
8898                index = closure.var_idx as usize;
8899            }
8900            // A global is never a function-expression name.
8901            ClosureType::Global
8902            | ClosureType::GlobalDecl
8903            | ClosureType::GlobalRef
8904            | ClosureType::ModuleDecl
8905            | ClosureType::ModuleImport => return None,
8906        }
8907    }
8908}
8909
8910/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
8911fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
8912    block_chain(state, block).into_iter().find_map(|scope| {
8913        state.vars.iter().enumerate().find_map(|(index, var)| {
8914            (var.name == name && state.var_block.get(index).copied() == Some(scope))
8915                .then_some(index)
8916        })
8917    })
8918}
8919
8920/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
8921fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
8922    if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
8923        var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
8924    }) {
8925        return index as u32;
8926    }
8927    state.var_block.push(PARAM_SCOPE);
8928    state.vars.push(VarDef::var(name));
8929    state.vars.len() as u32 - 1
8930}
8931
8932/// The name a parameter binds straight from its argument slot, if it has one.
8933///
8934/// A plain name does — with or without a default, and with or without `...`. Everything
8935/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
8936/// reference names the argument in the first case and leaves it `<null>` in the second,
8937/// so both the dump and the closures that capture the argument depend on this.
8938fn simple_parameter(param: &Pattern) -> Option<&Ident> {
8939    match &param.kind {
8940        PatternKind::Ident(name) => Some(name),
8941        PatternKind::Assign { target, .. } => match &target.kind {
8942            PatternKind::Ident(name) => Some(name),
8943            _ => None,
8944        },
8945        PatternKind::Rest(inner) => match &inner.kind {
8946            PatternKind::Ident(name) => Some(name),
8947            _ => None,
8948        },
8949        _ => None,
8950    }
8951}
8952
8953/// The pattern a parameter list has to unpick, if `index` is one of them.
8954fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
8955    prologue
8956        .iter()
8957        .find(|(at, _)| *at == index)
8958        .map(|(_, pattern)| pattern)
8959}
8960
8961fn pattern_has_default(pattern: &Pattern) -> bool {
8962    match &pattern.kind {
8963        PatternKind::Assign { .. } => true,
8964        PatternKind::Rest(inner) => pattern_has_default(inner),
8965        PatternKind::Array { elements, rest } => {
8966            elements.iter().flatten().any(element_has_default)
8967                || rest.as_deref().is_some_and(rest_has_default)
8968        }
8969        PatternKind::Object { properties, rest } => {
8970            properties.iter().flatten().any(element_has_default)
8971                || rest.as_deref().is_some_and(rest_has_default)
8972        }
8973        _ => false,
8974    }
8975}
8976
8977fn element_has_default(element: &PatternElement) -> bool {
8978    match element {
8979        PatternElement::Pattern(pattern) => pattern_has_default(pattern),
8980        PatternElement::Property { value, .. } => pattern_has_default(value),
8981    }
8982}
8983
8984fn rest_has_default(rest: &RestElement) -> bool {
8985    match rest {
8986        RestElement::Pattern(pattern) => pattern_has_default(pattern),
8987        RestElement::Member(_) => false,
8988    }
8989}
8990
8991/// Whether a function-scope binding is visible to the parameter list.
8992///
8993/// The parameter list runs before the body, so the body's `var`s and function
8994/// declarations do not exist yet — a name that only the body declares has to resolve
8995/// outward instead. What *does* exist by then is the compiler's own prologue: the
8996/// self-name of a named function expression (bound by `special_object 2` before anything
8997/// else), `this` and `new.target`. Those stay visible, which is what makes
8998/// `function f(a = this)` and `var f = function f(a = f)` work.
8999///
9000/// `arguments` is handled separately, as a binding of the parameter scope itself: with
9001/// parameter expressions the reference creates two of them, and the one the parameter
9002/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
9003fn visible_in_params(var: &VarDef) -> bool {
9004    var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
9005}
9006
9007fn resolve_slot(
9008    stack: &mut [FnState],
9009    current: usize,
9010    name: &str,
9011    block: u64,
9012    in_params: bool,
9013) -> Slot {
9014    // The parameter list's own bindings. They are consulted first because they shadow
9015    // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
9016    // `a` in the parameter scope, so a closure made there reads the parameter even after
9017    // the body assigns to its own `a`.
9018    if in_params
9019        && let Some(index) = stack[current]
9020            .vars
9021            .iter()
9022            .enumerate()
9023            .position(|(index, var)| {
9024                var.name == name
9025                    && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
9026            })
9027    {
9028        return Slot::Loc(index as u32);
9029    }
9030    // A name can be bound more than once: two `catch` parameters in nested
9031    // handlers are two slots. The binding that wins is the one whose scope encloses
9032    // the access, and among those the innermost — so the blocks are walked outward
9033    // and the first binding found on the way is the one that counts. A binding in
9034    // no block (`var`) is reachable from anywhere, which is why the function scope
9035    // is the end of the walk.
9036    //
9037    // The block walk comes *before* the argument slots, because a block may shadow a
9038    // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
9039    // slot is only the answer once nothing nearer claims the name.
9040    let chain = block_chain(&stack[current], block);
9041    for scope in &chain {
9042        let found = stack[current]
9043            .vars
9044            .iter()
9045            .enumerate()
9046            .find(|(index, var)| {
9047                var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
9048            })
9049            .map(|(index, _)| index);
9050        if let Some(index) = found {
9051            return Slot::Loc(index as u32);
9052        }
9053    }
9054    // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
9055    // its own slot, and `var` of the same name in the body is the same binding.
9056    if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
9057        return Slot::Arg(index as u32);
9058    }
9059    // Function-scope bindings — `var` and function declarations — are recorded with
9060    // the sentinel block `0`, which no real scope uses, so the walk above cannot see
9061    // them. They are reachable from anywhere in the function, which is exactly what
9062    // the sentinel means.
9063    //
9064    // This pass is *only* for those. A lexical binding has to be found through the
9065    // chain or not at all, and looking a name up without its block is precisely how
9066    // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
9067    // block leaked out of it.
9068    let function_scoped = stack[current]
9069        .vars
9070        .iter()
9071        .enumerate()
9072        .find(|(index, var)| {
9073            var.name == name
9074                && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
9075                && (!in_params || visible_in_params(var))
9076        })
9077        .map(|(index, _)| index);
9078    if let Some(index) = function_scoped {
9079        return Slot::Loc(index as u32);
9080    }
9081    if let Some(index) = stack[current]
9082        .closure_vars
9083        .iter()
9084        .position(|c| c.name == name)
9085    {
9086        return slot_for_closure(&stack[current].closure_vars[index], index as u32);
9087    }
9088
9089    for owner in (0..current).rev() {
9090        // The nested function was created inside one of this frame's blocks, and the
9091        // outermost visible binding is the innermost block on that chain — not whatever
9092        // comes first in the variable table. `function f(){ class S{} }` has two `S`
9093        // bindings: the `let S` inside `f` and the `const S` inside the class body, and
9094        // the class body is the one a method may see.
9095        let entry = stack
9096            .get(owner + 1)
9097            .map(|s| s.created_in_block)
9098            .unwrap_or(0);
9099        let lexical = block_chain(&stack[owner], entry)
9100            .into_iter()
9101            .find_map(|scope| {
9102                stack[owner]
9103                    .vars
9104                    .iter()
9105                    .enumerate()
9106                    .find(|(index, var)| {
9107                        var.name == name
9108                            && stack[owner].var_block.get(*index).copied() == Some(scope)
9109                    })
9110                    .map(|(index, _)| index)
9111            });
9112        // A function born in a parameter list sees that list's bindings, not the body's:
9113        // the parameter scope is the environment it was created in.
9114        let in_param_scope = stack
9115            .get(owner + 1)
9116            .is_some_and(|child| child.created_in_params)
9117            .then(|| {
9118                stack[owner]
9119                    .vars
9120                    .iter()
9121                    .enumerate()
9122                    .position(|(index, var)| {
9123                        var.name == name
9124                            && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
9125                    })
9126            })
9127            .flatten();
9128        let found = if let Some(index) = in_param_scope {
9129            let var = &stack[owner].vars[index];
9130            Some(Found::Local(
9131                ClosureType::Local,
9132                index as u32,
9133                var.is_const,
9134                var.needs_check(),
9135            ))
9136        } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
9137            Some(Found::Local(ClosureType::Arg, index as u32, false, false))
9138        } else if let Some(index) = lexical {
9139            let var = &stack[owner].vars[index];
9140            Some(Found::Local(
9141                ClosureType::Local,
9142                index as u32,
9143                var.is_const,
9144                var.needs_check(),
9145            ))
9146        } else if let Some(index) = stack[owner]
9147            .vars
9148            .iter()
9149            .enumerate()
9150            .find_map(|(index, var)| {
9151                // A function created inside a parameter list must not see the body of the
9152                // function it was born in; see [`FnState::created_in_params`].
9153                let hidden = stack
9154                    .get(owner + 1)
9155                    .is_some_and(|child| child.created_in_params);
9156                (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
9157            })
9158        {
9159            let var = &stack[owner].vars[index];
9160            Some(Found::Local(
9161                ClosureType::Local,
9162                index as u32,
9163                var.is_const,
9164                var.needs_check(),
9165            ))
9166        } else if stack[owner].self_name.as_deref() == Some(name) {
9167            // A named function expression's own name. The reference declares it here,
9168            // on the first lookup that fails, rather than up front — and that is what
9169            // makes it reachable from a *nested* function: the nested lookup is what
9170            // walks out and creates the binding. A direct reference in the body is
9171            // caught the same way, which is why `provide_self_name` only has to add
9172            // the prologue.
9173            let strict = stack[owner].strict;
9174            stack[owner].var_block.push(FUNCTION_SCOPE);
9175            stack[owner].vars.push(VarDef {
9176                kind: VarKind::FunctionName,
9177                // In strict mode the name is immutable, so a store raises; sloppy
9178                // mode drops the store instead (see `variable_instruction`).
9179                is_const: strict,
9180                ..VarDef::var(name)
9181            });
9182            let index = stack[owner].vars.len() as u32 - 1;
9183            Some(Found::Local(ClosureType::Local, index, strict, false))
9184        } else if let Some(index) = stack[owner]
9185            .closure_vars
9186            .iter()
9187            .position(|c| c.name == name)
9188        {
9189            let closure = &stack[owner].closure_vars[index];
9190            Some(match closure.closure_type {
9191                // `GlobalRef` belongs here too: it is a *global* reached through this
9192                // frame's reference table, so treating it as a `Ref` to a local cell makes
9193                // the reader look for a cell no frame ever fills. That is how a second
9194                // function using `eval` in its parameter list read `undefined` after a
9195                // sibling had already made `eval` a closure entry.
9196                ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
9197                    Found::Global(index as u32)
9198                }
9199                // A module variable is a cell in the *module's* environment, which is
9200                // the module body's parent as far as a nested function is concerned — so
9201                // it is captured as a plain reference, not looked up as a global.
9202                ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
9203                    ClosureType::Ref,
9204                    index as u32,
9205                    closure.is_const,
9206                    closure.is_lexical,
9207                ),
9208                _ => Found::Local(
9209                    ClosureType::Ref,
9210                    index as u32,
9211                    closure.is_const,
9212                    closure.is_lexical,
9213                ),
9214            })
9215        } else {
9216            None
9217        };
9218        let Some(found) = found else { continue };
9219
9220        let (is_const, is_lexical) = match found {
9221            Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
9222            Found::Global(_) => (false, false),
9223        };
9224        // Mark the owner's binding as captured so it moves into a reference cell.
9225        if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
9226            let slot = match found {
9227                Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
9228                _ => &mut stack[owner].vars[index as usize],
9229            };
9230            slot.is_captured = true;
9231        }
9232        // Forward the reference through every function in between.
9233        let mut previous = match found {
9234            Found::Local(kind, index, _, _) => (kind, index),
9235            Found::Global(index) => (ClosureType::Global, index),
9236        };
9237        for level in owner + 1..=current {
9238            let kind = match (previous.0, level) {
9239                // A global stays a global at *every* level. Without `GlobalRef` in
9240                // this arm the second nested function over the same global got a
9241                // `Ref` to a cell no frame ever held, so the innermost closure read
9242                // `undefined` — which is how a two-deep getter lost its outer
9243                // variable.
9244                (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
9245                    ClosureType::GlobalRef
9246                }
9247                (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
9248                _ => ClosureType::Ref,
9249            };
9250            let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
9251            previous = (kind, index);
9252        }
9253        let index = previous.1;
9254        return slot_for_closure(&stack[current].closure_vars[index as usize], index);
9255    }
9256
9257    // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
9258    // creating a property. The top-level function holds the entry.
9259    let mut previous = (
9260        ClosureType::Global,
9261        ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
9262    );
9263    for level in 1..=current {
9264        let index = ensure_closure(
9265            stack,
9266            level,
9267            name,
9268            false,
9269            false,
9270            ClosureType::GlobalRef,
9271            previous.1,
9272        );
9273        previous = (ClosureType::GlobalRef, index);
9274    }
9275    Slot::Global(previous.1)
9276}
9277
9278/// What an outward search turned up.
9279#[derive(Debug, Clone, Copy)]
9280enum Found {
9281    /// A binding in an enclosing function, reachable through a closure of this
9282    /// type, with its const/lexical flags.
9283    Local(ClosureType, u32, bool, bool),
9284    /// A global, reached through the enclosing function's closure entry.
9285    Global(u32),
9286}
9287
9288/// Add a closure entry to `level` if it is not there yet.
9289fn ensure_closure(
9290    stack: &mut [FnState],
9291    level: usize,
9292    name: &str,
9293    is_const: bool,
9294    is_lexical: bool,
9295    closure_type: ClosureType,
9296    var_idx: u32,
9297) -> u32 {
9298    if let Some(index) = stack[level]
9299        .closure_vars
9300        .iter()
9301        .position(|c| c.name == name)
9302    {
9303        return index as u32;
9304    }
9305    stack[level].closure_vars.push(ClosureVar {
9306        name: name.to_string(),
9307        is_const,
9308        is_lexical,
9309        closure_type,
9310        var_idx: var_idx as u16,
9311    });
9312    stack[level].closure_vars.len() as u32 - 1
9313}
9314
9315fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
9316    match closure.closure_type {
9317        // A `global_ref` only says *how* the binding is found (through the
9318        // parent's closure table); the access itself is an ordinary global one.
9319        ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
9320        ClosureType::GlobalDecl => Slot::GlobalDecl(index),
9321        // A module variable is a real cell in the module's environment, so it is reached
9322        // exactly like a captured local — the host, not the global object, is what fills
9323        // the slot.
9324        ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
9325        _ => Slot::VarRef(index),
9326    }
9327}
9328
9329/// Pick the opcode for one variable access.
9330///
9331/// The `_check` variants are what enforce the temporal dead zone. They are used
9332/// for every access to a `let`/`const` binding except its own initialisation —
9333/// which is exactly the operation that takes the binding out of the dead zone.
9334fn variable_instruction(
9335    stack: &[FnState],
9336    current: usize,
9337    action: VarAction,
9338    slot: Slot,
9339) -> (Opcode, Vec<Op>) {
9340    let lexical = match slot {
9341        Slot::Loc(index) => stack[current]
9342            .vars
9343            .get(index as usize)
9344            .is_some_and(|v| v.needs_check()),
9345        Slot::VarRef(index) => stack[current]
9346            .closure_vars
9347            .get(index as usize)
9348            .is_some_and(|c| c.is_lexical),
9349        _ => false,
9350    };
9351    let operand = vec![Op::Slot(slot)];
9352    match (action, slot) {
9353        (VarAction::Get, Slot::Loc(index)) => (
9354            if lexical {
9355                Opcode::GetLocCheck
9356            } else {
9357                Opcode::GetLoc
9358            },
9359            vec![Op::Slot(Slot::Loc(index))],
9360        ),
9361        (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
9362        (VarAction::Get, Slot::VarRef(index)) => (
9363            if lexical {
9364                Opcode::GetVarRefCheck
9365            } else {
9366                Opcode::GetVarRef
9367            },
9368            vec![Op::Slot(Slot::VarRef(index))],
9369        ),
9370        (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
9371        (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
9372        // `typeof x` is a *reading* of `x` (§13.5.3 evaluates the operand as a Reference and
9373        // then `GetValue`s it), so a lexical binding still has its dead zone checked. Only
9374        // the *unresolvable* case is different: `typeof undeclared` answers `"undefined"`
9375        // instead of throwing, and that is what `GetVarUndef` is for. Skipping the check for
9376        // every slot made `typeof x; let x;` print `"undefined"` where the spec requires a
9377        // `ReferenceError`.
9378        (VarAction::GetUndef, Slot::Loc(index)) => (
9379            if lexical {
9380                Opcode::GetLocCheck
9381            } else {
9382                Opcode::GetLoc
9383            },
9384            vec![Op::Slot(Slot::Loc(index))],
9385        ),
9386        (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
9387        (VarAction::GetUndef, Slot::VarRef(index)) => (
9388            if lexical {
9389                Opcode::GetVarRefCheck
9390            } else {
9391                Opcode::GetVarRef
9392            },
9393            vec![Op::Slot(Slot::VarRef(index))],
9394        ),
9395        (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9396            (Opcode::GetVarUndef, operand)
9397        }
9398
9399        (VarAction::Put, Slot::Loc(_)) => (
9400            if lexical {
9401                Opcode::PutLocCheck
9402            } else {
9403                Opcode::PutLoc
9404            },
9405            operand,
9406        ),
9407        (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
9408        (VarAction::Put, Slot::VarRef(_)) => (
9409            if lexical {
9410                Opcode::PutVarRefCheck
9411            } else {
9412                Opcode::PutVarRef
9413            },
9414            operand,
9415        ),
9416        (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
9417        (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9418        // Initialisation is what ends the dead zone, so it never checks.
9419        (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9420        (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
9421        // `this` in a derived constructor is always a local, so these cannot happen;
9422        // routing them to the ordinary forms keeps the match total without inventing
9423        // opcodes the reference does not have.
9424        (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
9425        // The captured form of `PutLocCheckInit`: `super()` inside an arrow that closes over
9426        // the constructor's `this` still has to refuse a second initialisation, and the
9427        // plain store accepted it (`fields-run-once-on-double-super`).
9428        (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRefCheckInit, operand),
9429        (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9430            (Opcode::PutVarInit, operand)
9431        }
9432        (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
9433        (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9434        (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9435            (Opcode::PutVarInit, operand)
9436        }
9437        (VarAction::Set, Slot::Loc(_)) => (
9438            if lexical {
9439                Opcode::SetLocCheck
9440            } else {
9441                Opcode::SetLoc
9442            },
9443            operand,
9444        ),
9445        (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
9446        (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
9447        (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9448        (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9449        (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
9450        (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9451        (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
9452        (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
9453        (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9454        (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
9455        (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9456        (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
9457    }
9458}
9459
9460/// The instruction-rewriting pass.
9461///
9462/// These are the reference implementation's patterns, restricted to the ones the
9463/// constructs this compiler supports can produce. Each entry is a comment on the
9464/// bytecode it removes, because the whole point is that the result is one
9465/// instruction shorter than the literal translation of the AST.
9466fn peephole(
9467    insns: &mut [Option<(Opcode, Vec<Op>)>],
9468    label_at: &[Option<u32>],
9469    placed: &[Option<usize>],
9470) {
9471    fold_dup_patterns(insns, label_at);
9472
9473    // `drop` before `return_undef` is dead: the return discards the whole frame
9474    // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
9475    // consumes its own `drop`; removing the drop first would leave the `dup` and
9476    // produce a `set_` where the reference has a `put_`.
9477    for index in 0..insns.len() {
9478        if opcode_at(insns, index) != Some(Opcode::Drop) {
9479            continue;
9480        }
9481        // Skip over a run of drops, but stop at a jump target: removing code on
9482        // one side of a label would silently retarget the jump.
9483        let mut next = index + 1;
9484        while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
9485            next += 1;
9486        }
9487        if is_label_at(label_at, next) {
9488            continue;
9489        }
9490        if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
9491            for entry in &mut insns[index..next] {
9492                *entry = None;
9493            }
9494        }
9495    }
9496
9497    // The rewrites below all decide against one fixed snapshot, which is what the
9498    // reference sees: `code_match` reads the bytecode buffer as it was on entry to
9499    // the pass, so a rule never observes what an earlier rule removed. Gathering
9500    // every deletion first and applying them together reproduces that.
9501    let snapshot: Vec<Option<Opcode>> = insns
9502        .iter()
9503        .map(|entry| entry.as_ref().map(|(op, _)| *op))
9504        .collect();
9505    // The next instruction that is still there. Holes left by dead-code
9506    // elimination are not instructions, so a rule looks past them.
9507    let next_op = |index: usize| -> Option<usize> {
9508        (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
9509    };
9510
9511    let mut doomed = vec![false; insns.len()];
9512    for index in 0..insns.len() {
9513        // A constant pushed only to be dropped does nothing at all. This is what a
9514        // comma expression with a literal left operand compiles to — `(0, f)()` — and
9515        // the reference removes the pair rather than making the reader step over it.
9516        let constant = matches!(
9517            snapshot[index],
9518            Some(
9519                Opcode::Undefined
9520                    | Opcode::Null
9521                    | Opcode::PushMinus1
9522                    | Opcode::Push0
9523                    | Opcode::Push1
9524                    | Opcode::Push2
9525                    | Opcode::Push3
9526                    | Opcode::Push4
9527                    | Opcode::Push5
9528                    | Opcode::Push6
9529                    | Opcode::Push7
9530                    | Opcode::PushTrue
9531                    | Opcode::PushFalse
9532                    | Opcode::PushI32
9533            )
9534        );
9535        if constant
9536            && let Some(next) = next_op(index)
9537            && snapshot[next] == Some(Opcode::Drop)
9538        {
9539            doomed[index] = true;
9540            doomed[next] = true;
9541        }
9542    }
9543    for (index, entry) in insns.iter_mut().enumerate() {
9544        if doomed[index] {
9545            *entry = None;
9546        }
9547    }
9548
9549    // A conditional whose destination is the very next instruction just pops its
9550    // condition, so it becomes a plain `drop`. This is what an empty `case` clause
9551    // compiles to.
9552    //
9553    // Order matters, and it is the reference's order: this runs *before* the
9554    // folding below, on the instruction the conditional originally had. Folding
9555    // moves a conditional's destination, and the reference never re-examines it
9556    // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
9557    // a conditional even though folding leaves it pointing at the next
9558    // instruction.
9559    for (index, entry) in insns.iter_mut().enumerate() {
9560        let Some((op, operands)) = entry.clone() else {
9561            continue;
9562        };
9563        if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
9564            continue;
9565        }
9566        let Some(id) = label_id(&operands) else {
9567            continue;
9568        };
9569        if placed.get(id as usize).copied().flatten() == Some(index + 1) {
9570            *entry = Some((Opcode::Drop, Vec::new()));
9571        }
9572    }
9573
9574    // A constant condition is decided here rather than at run time.
9575    fold_constant_conditions(insns, label_at);
9576    // The conditional folding below is about pairs of *real* branches, so it runs
9577    // before a jump to the next instruction is dropped: `do { … if (c) continue }
9578    // while (t)` puts `continue` exactly on the condition, and the reference inverts
9579    // the branch first and only then notices the jump goes nowhere.
9580    fold_conditional_jumps(insns, label_at, placed);
9581
9582    // A jump whose destination is the very next instruction does nothing, which is
9583    // what constant folding leaves behind for `while (1) { … }`.
9584    remove_jump_to_next(insns, placed);
9585
9586    // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
9587    // a use of the same variable boils down to.
9588    for index in 0..insns.len() {
9589        let Some((put_op, _)) = insns[index].clone() else {
9590            continue;
9591        };
9592        if !is_foldable_put(put_op) {
9593            continue;
9594        }
9595        if is_label_at(label_at, index + 1) {
9596            continue;
9597        }
9598        let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
9599            continue;
9600        };
9601        if get_op != get_form_of(put_op) {
9602            continue;
9603        }
9604        let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
9605        if put_slot.is_none() || put_slot != get_operands.first().cloned() {
9606            continue;
9607        }
9608        insns[index] = Some((set_form_of(put_op), get_operands));
9609        insns[index + 1] = None;
9610    }
9611}
9612
9613/// Drop `gosub`s that call an empty subroutine.
9614///
9615/// A `gosub` whose target starts with `ret` returns immediately, so the reference
9616/// drops the call. This is how `try`/`catch` without a `finally` loses its
9617/// finalizer plumbing: the finalizer block is empty, its first instruction is
9618/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
9619/// [`eliminate_dead_code`] then removes.
9620fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
9621    let state = &stack[current];
9622    let mut targets = Vec::new();
9623    for insn in &state.insns {
9624        if let Insn::Fixed { op, operands } = insn
9625            && *op == Opcode::Gosub
9626            && let Some(id) = label_id(operands)
9627            && let Some(target) = state.labels.get(id as usize).copied().flatten()
9628        {
9629            targets.push(target);
9630        }
9631    }
9632    let empty: Vec<usize> = targets
9633        .into_iter()
9634        .filter(|target| {
9635            stack[current]
9636                .insns
9637                .get(*target)
9638                .map(|insn| {
9639                    matches!(
9640                        insn,
9641                        Insn::Fixed {
9642                            op: Opcode::Ret,
9643                            ..
9644                        }
9645                    )
9646                })
9647                .unwrap_or(false)
9648        })
9649        .collect();
9650    if empty.is_empty() {
9651        return;
9652    }
9653    for insn in stack[current].insns.iter_mut() {
9654        if let Insn::Fixed { op, operands } = insn
9655            && *op == Opcode::Gosub
9656            && let Some(id) = label_id(operands)
9657            && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
9658            && empty.contains(&target)
9659        {
9660            *insn = Insn::Dead;
9661        }
9662    }
9663}
9664
9665/// Replace unreachable instructions with [`Insn::Dead`].
9666fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
9667    let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
9668    for (index, insn) in stack[current].insns.iter_mut().enumerate() {
9669        if !reachable[index] {
9670            *insn = Insn::Dead;
9671        }
9672    }
9673}
9674
9675/// Mark every instruction index reachable from the entry, plus the index one past
9676/// the last instruction.
9677///
9678/// `seen[len]` answers "can control reach the end of this function", and the
9679/// entries before it identify dead code. Both DCE and the implicit-return decision
9680/// read the same result, which keeps them from disagreeing.
9681fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
9682    let mut seen = vec![false; count + 1];
9683    let mut worklist = vec![0usize];
9684    while let Some(index) = worklist.pop() {
9685        if index > count || seen[index] {
9686            continue;
9687        }
9688        seen[index] = true;
9689        if index == count {
9690            continue;
9691        }
9692        let (op, operands) = match &state.insns[index] {
9693            Insn::Fixed { op, operands } => (*op, operands.as_slice()),
9694            // A variable access never transfers control, and a removed
9695            // instruction is only reachable if it is already marked.
9696            Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
9697                worklist.push(index + 1);
9698                continue;
9699            }
9700        };
9701        match op {
9702            // A return, a throw and a `ret` all leave this instruction stream: the
9703            // first two give control to the caller or the handler, and `ret`
9704            // returns to a `gosub` elsewhere.
9705            // A tail call leaves the function too: the callee's result becomes this
9706            // function's result, so nothing after it runs.
9707            Opcode::Return
9708            | Opcode::ReturnUndef
9709            | Opcode::ReturnAsync
9710            | Opcode::TailCall
9711            | Opcode::TailCallMethod
9712            | Opcode::Throw
9713            | Opcode::ThrowError
9714            | Opcode::Ret => {}
9715            // A `catch` records where exceptions from the code that follows go.
9716            // That code is not reachable through normal control flow, but it is
9717            // reachable — through the exception edge — so the walk has to follow
9718            // it, or dead-code elimination would delete every handler.
9719            Opcode::Catch => {
9720                if let Some(target) = placed_label(state, operands) {
9721                    worklist.push(target);
9722                }
9723                worklist.push(index + 1);
9724            }
9725            // A `gosub` calls a subroutine and then continues, so both edges count.
9726            Opcode::Gosub => {
9727                if let Some(target) = placed_label(state, operands) {
9728                    worklist.push(target);
9729                }
9730                worklist.push(index + 1);
9731            }
9732            Opcode::Goto => {
9733                if let Some(target) = placed_label(state, operands) {
9734                    worklist.push(target);
9735                }
9736            }
9737            Opcode::IfTrue | Opcode::IfFalse => {
9738                if let Some(target) = placed_label(state, operands) {
9739                    worklist.push(target);
9740                }
9741                worklist.push(index + 1);
9742            }
9743            _ => worklist.push(index + 1),
9744        }
9745    }
9746    seen
9747}
9748
9749/// The instruction index a jump operand points at, resolved through the label
9750/// placement table.
9751fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
9752    let id = label_id(operands)?;
9753    state.labels.get(id as usize).copied().flatten()
9754}
9755
9756/// The label an instruction refers to.
9757fn label_id(operands: &[Op]) -> Option<u32> {
9758    operands.iter().find_map(|operand| match operand {
9759        Op::Label(label) => Some(label.0),
9760        _ => None,
9761    })
9762}
9763
9764/// Turn `if_false L; goto M; L:` into `if_true M`.
9765///
9766/// A conditional whose alternate branch is an unconditional jump needs one jump,
9767/// not two. This is the shape `if (c) break;` produces, so folding it removes an
9768/// instruction and a label from every conditional `break`.
9769/// The boolean a constant-push instruction produces, or `None` if it is not one.
9770///
9771/// Only the operators whose truthiness is decided by the opcode are covered; a
9772/// constant that needs the constant pool (a string) is left alone, because reading it
9773/// would mean threading the pool through the peephole for a case the reference also
9774/// skips.
9775fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
9776    match op {
9777        // `push_0` returns -1 for zero, `push_1` 1, and so on.
9778        Opcode::PushMinus1 => Some(true),
9779        Opcode::Push0 => Some(false),
9780        Opcode::Push1
9781        | Opcode::Push2
9782        | Opcode::Push3
9783        | Opcode::Push4
9784        | Opcode::Push5
9785        | Opcode::Push6
9786        | Opcode::Push7 => Some(true),
9787        Opcode::PushTrue => Some(true),
9788        Opcode::PushFalse => Some(false),
9789        Opcode::Undefined | Opcode::Null => Some(false),
9790        Opcode::PushI32 => match operands.first() {
9791            Some(Op::Int(value)) => Some(*value != 0),
9792            _ => None,
9793        },
9794        _ => None,
9795    }
9796}
9797
9798/// Fold a branch on a constant condition.
9799///
9800/// `if (0) a() else b()` must not test anything at run time, and the reference
9801/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
9802/// which is why the bytecode for a `while (1)` loop has no condition at all.
9803///
9804/// Two instructions become one, so the slot the test occupied is left empty rather
9805/// than shifting everything after it: labels have already been resolved to indices.
9806fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
9807    for index in 0..insns.len() {
9808        let Some((push_op, push_operands)) = insns[index].clone() else {
9809            continue;
9810        };
9811        let Some(truth) = constant_truth(push_op, &push_operands) else {
9812            continue;
9813        };
9814        let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
9815            continue;
9816        };
9817        // A label on the branch means something else jumps *here* — the value is on the
9818        // stack and the conditional is what pops it. Deleting the branch would leave that
9819        // jump with no instruction, and a label whose slot is empty resolves to the next
9820        // one that is not, i.e. to the far side of the branch. That is how
9821        // `if (a && false) then else` jumped to `then`: `&&` ends its chain on a label, and
9822        // the constant `false` sits directly in front of the statement's own conditional.
9823        if is_label_at(label_at, index + 1) {
9824            continue;
9825        }
9826        let (destination, taken) = match branch_op {
9827            Opcode::IfTrue => (branch_operands.first().cloned(), truth),
9828            Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
9829            _ => continue,
9830        };
9831        let Some(destination) = destination else {
9832            continue;
9833        };
9834        insns[index] = if taken {
9835            // The branch is always taken, so it becomes an unconditional jump.
9836            Some((Opcode::Goto, vec![destination]))
9837        } else {
9838            // The branch never runs: both instructions disappear and control falls
9839            // through to what came after.
9840            None
9841        };
9842        insns[index + 1] = None;
9843    }
9844}
9845
9846/// Remove a jump whose destination is the instruction right after it.
9847///
9848/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
9849/// its test into nothing, and the loop-end jump then points at the following
9850/// instruction. The reference drops them, so `stack_size` and the listing agree.
9851fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
9852    for index in 0..insns.len() {
9853        let Some((op, operands)) = insns[index].clone() else {
9854            continue;
9855        };
9856        if !is_goto(op) {
9857            continue;
9858        }
9859        let Some(id) = label_id(&operands) else {
9860            continue;
9861        };
9862        // The next instruction that still exists, which is what "the instruction
9863        // after this jump" means once earlier folds have punched holes.
9864        let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
9865        if placed.get(id as usize).copied().flatten() == next {
9866            insns[index] = None;
9867        }
9868    }
9869}
9870
9871fn fold_conditional_jumps(
9872    insns: &mut [Option<(Opcode, Vec<Op>)>],
9873    label_at: &[Option<u32>],
9874    placed: &[Option<usize>],
9875) {
9876    for index in 0..insns.len() {
9877        let Some((op, operands)) = insns[index].clone() else {
9878            continue;
9879        };
9880        let inverted = match op {
9881            Opcode::IfFalse => Opcode::IfTrue,
9882            Opcode::IfTrue => Opcode::IfFalse,
9883            _ => continue,
9884        };
9885        // Next must be an unconditional jump that is not itself a target, and the
9886        // instruction after it must be exactly where the conditional goes.
9887        let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
9888            continue;
9889        };
9890        if !is_goto(next_op) || is_label_at(label_at, index + 1) {
9891            continue;
9892        }
9893        // The conditional must land on the instruction *after* the jump. Several
9894        // labels can share a position, so this asks where *this* label was put
9895        // rather than what label happens to sit there.
9896        let Some(taken) = label_id(&operands) else {
9897            continue;
9898        };
9899        if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
9900            continue;
9901        }
9902        let Some(destination) = next_operands.first().cloned() else {
9903            continue;
9904        };
9905        insns[index] = Some((inverted, vec![destination]));
9906        insns[index + 1] = None;
9907    }
9908}
9909
9910/// Whether a jump target is placed at this instruction index.
9911fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
9912    label_at.get(index).copied().flatten().is_some()
9913}
9914
9915fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
9916    // `dup put_x(n)` -> `set_x(n)`
9917    // `dup put_x(n) drop` -> `put_x(n)`
9918    // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
9919    for index in 0..insns.len() {
9920        if opcode_at(insns, index) != Some(Opcode::Dup) {
9921            continue;
9922        }
9923        if is_label_at(label_at, index + 1) {
9924            continue;
9925        }
9926        let Some((put_op, put_operands)) = insns[index + 1].clone() else {
9927            continue;
9928        };
9929        if !is_foldable_put(put_op) {
9930            continue;
9931        }
9932        let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
9933            continue;
9934        };
9935        let mut new_op = set_form_of(put_op);
9936        let mut end = index + 2;
9937        if is_label_at(label_at, end) {
9938            // The `put` has to stay as it is; only the `dup` can be folded.
9939            insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
9940            insns[index + 1] = None;
9941            continue;
9942        }
9943        // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
9944        // Deleting it moves the label's target onto whatever follows, and the code that
9945        // jumps there arrives with a different stack than the fall-through path: that is
9946        // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
9947        // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
9948        // an empty stack. The store had already consumed the value it was supposed to
9949        // leave behind.
9950        if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
9951            new_op = put_op;
9952            end += 1;
9953            if opcode_at(insns, end) == Some(get_form_of(put_op))
9954                && !is_label_at(label_at, end)
9955                && insns[end]
9956                    .as_ref()
9957                    .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
9958            {
9959                new_op = set_form_of(put_op);
9960                end += 1;
9961            }
9962        }
9963        insns[index] = Some((new_op, vec![Op::Slot(slot)]));
9964        for entry in &mut insns[index + 1..end] {
9965            *entry = None;
9966        }
9967    }
9968}
9969
9970fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
9971    insns
9972        .get(index)
9973        .and_then(|entry| entry.as_ref())
9974        .map(|(op, _)| *op)
9975}
9976
9977/// The four `put_` families that have a `set_` twin. Deliberately not including
9978/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
9979/// these, and folding the others would produce instructions that do not exist.
9980fn is_foldable_put(op: Opcode) -> bool {
9981    matches!(
9982        op,
9983        Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
9984    )
9985}
9986
9987fn set_form_of(op: Opcode) -> Opcode {
9988    match op {
9989        Opcode::PutLoc => Opcode::SetLoc,
9990        Opcode::PutLocCheck => Opcode::SetLocCheck,
9991        Opcode::PutArg => Opcode::SetArg,
9992        Opcode::PutVarRef => Opcode::SetVarRef,
9993        other => other,
9994    }
9995}
9996
9997fn get_form_of(op: Opcode) -> Opcode {
9998    match op {
9999        Opcode::PutLoc => Opcode::GetLoc,
10000        Opcode::PutLocCheck => Opcode::GetLocCheck,
10001        Opcode::PutArg => Opcode::GetArg,
10002        Opcode::PutVarRef => Opcode::GetVarRef,
10003        other => other,
10004    }
10005}
10006
10007/// Atom interning, per function.
10008///
10009/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
10010/// identifiers, so the array-index rule applies here rather than at the handful of
10011/// call sites that build property keys.
10012fn intern_atom(state: &mut FnState, name: &str) -> u32 {
10013    intern_atom_value(state, Atom::from_text(name))
10014}
10015
10016/// [`intern_atom`] for an operand that is already an [`Atom`].
10017///
10018/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
10019/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
10020/// would have looked up.
10021fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
10022    if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
10023        return index as u32;
10024    }
10025    state.atoms.push(atom);
10026    state.atoms.len() as u32 - 1
10027}
10028
10029fn binary_opcode(op: BinaryOp) -> Opcode {
10030    match op {
10031        BinaryOp::Add => Opcode::Add,
10032        BinaryOp::Sub => Opcode::Sub,
10033        BinaryOp::Mul => Opcode::Mul,
10034        BinaryOp::Div => Opcode::Div,
10035        BinaryOp::Mod => Opcode::Mod,
10036        BinaryOp::Pow => Opcode::Pow,
10037        BinaryOp::BitOr => Opcode::Or,
10038        BinaryOp::BitXor => Opcode::Xor,
10039        BinaryOp::BitAnd => Opcode::And,
10040        BinaryOp::Shl => Opcode::Shl,
10041        BinaryOp::Shr => Opcode::Sar,
10042        BinaryOp::UShr => Opcode::Shr,
10043        BinaryOp::Lt => Opcode::Lt,
10044        BinaryOp::LtEq => Opcode::Lte,
10045        BinaryOp::Gt => Opcode::Gt,
10046        BinaryOp::GtEq => Opcode::Gte,
10047        BinaryOp::Eq => Opcode::Eq,
10048        BinaryOp::NotEq => Opcode::Neq,
10049        BinaryOp::StrictEq => Opcode::StrictEq,
10050        BinaryOp::StrictNotEq => Opcode::StrictNeq,
10051        BinaryOp::In => Opcode::In,
10052        BinaryOp::Instanceof => Opcode::Instanceof,
10053    }
10054}
10055
10056fn compound_opcode(op: AssignOp) -> Opcode {
10057    match op {
10058        AssignOp::Add => Opcode::Add,
10059        AssignOp::Sub => Opcode::Sub,
10060        AssignOp::Mul => Opcode::Mul,
10061        AssignOp::Div => Opcode::Div,
10062        AssignOp::Mod => Opcode::Mod,
10063        AssignOp::Pow => Opcode::Pow,
10064        AssignOp::Shl => Opcode::Shl,
10065        AssignOp::Shr => Opcode::Sar,
10066        AssignOp::UShr => Opcode::Shr,
10067        AssignOp::BitOr => Opcode::Or,
10068        AssignOp::BitXor => Opcode::Xor,
10069        AssignOp::BitAnd => Opcode::And,
10070        AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
10071    }
10072}
10073
10074/// Encode the resolved instruction stream, choosing short forms where possible.
10075///
10076/// The peephole pass leaves holes in the instruction list so that label indices
10077/// stay valid. A label names an *instruction index*, and an index that was
10078/// deleted has to resolve to the next surviving instruction, which is what
10079/// [`resolve_label`] does before the byte offsets are known.
10080fn assemble(
10081    insns: &mut [Option<(Opcode, Vec<Op>)>],
10082    insn_pos: &[Option<Position>],
10083    state: &mut FnState,
10084) -> (Vec<u8>, u32, Vec<LineCol>) {
10085    // Compaction: surviving instructions in order, plus the index mapping.
10086    //
10087    // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
10088    // point below where instructions are removed — otherwise a stack trace would point
10089    // at the wrong source line as soon as dead-code elimination kicked in.
10090    let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
10091    let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
10092    let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
10093    for (original, entry) in insns.iter_mut().enumerate() {
10094        if let Some((op, operands)) = entry.take() {
10095            original_to_kept[original] = Some(kept.len());
10096            kept.push((op, operands));
10097            spans.push(insn_pos.get(original).copied().flatten());
10098        }
10099    }
10100
10101    if std::env::var_os("QJS_DEBUG").is_some() {
10102        eprintln!("--- assemble entry --- {kept:?}");
10103    }
10104    // How many labels are real, as opposed to the per-instruction ones allocated
10105    // just below. Only a real label marks a spot in the source program.
10106    let real_labels = state.labels.len();
10107
10108    // Give every surviving instruction a label of its own. Jump cleanup below
10109    // redirects jumps to arbitrary instructions, and a jump target has to be a
10110    // label; pre-allocating one per index means a redirect never has to invent
10111    // anything.
10112    let existing = state.labels.len();
10113    let base = kept.len();
10114    let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
10115    for offset in 0..=kept.len() {
10116        state.labels.push(Some(0));
10117        index_label.push(Label((existing + offset) as u32));
10118    }
10119    // Point each pre-allocated label at its instruction, reusing the count from
10120    // `original_to_kept` so the mapping survives compaction.
10121    let place_index_labels = |state: &mut FnState,
10122                              original_to_kept: &[Option<usize>],
10123                              kept_len: usize,
10124                              index_label: &[Label]| {
10125        for (original, mapped) in original_to_kept.iter().enumerate() {
10126            if let Some(kept_index) = mapped {
10127                let label = index_label[*kept_index].0 as usize;
10128                state.labels[label] = Some(original);
10129            }
10130        }
10131        state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
10132    };
10133    place_index_labels(state, &original_to_kept, base, &index_label);
10134
10135    // Resolve every label to a kept index once; the placement table maps labels
10136    // to original indices, so a second hop lands in kept space.
10137    let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
10138    for (id, placed) in state.labels.iter().enumerate() {
10139        let Some(original) = placed else { continue };
10140        label_kept[id] = if *original == usize::MAX {
10141            Some(base)
10142        } else {
10143            (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
10144        };
10145    }
10146
10147    // Code after an unconditional transfer is unreachable, and the reference drops it
10148    // as it walks past the transfer — the `skip_dead_code` in its first pass. It
10149    // scans forward until it finds a label something still jumps to, so a run of
10150    // dead instructions between a `throw` and the next live target disappears.
10151    //
10152    // The scan repeats because dropping a jump lowers the reference count of the
10153    // label it pointed at, which can strand what follows. Only a real label keeps an
10154    // instruction alive here; the per-instruction labels allocated above belong to
10155    // this pass, not to the program.
10156    loop {
10157        let mut references = vec![false; kept.len() + 1];
10158        for (_, operands) in &kept {
10159            if let Some(target) = target_kept_index(operands, &label_kept)
10160                && target < references.len()
10161            {
10162                references[target] = true;
10163            }
10164        }
10165        let mut doomed = vec![false; kept.len()];
10166        let mut any = false;
10167        for (index, (op, _)) in kept.iter().enumerate() {
10168            if !is_transfer(*op) {
10169                continue;
10170            }
10171            for next in index + 1..kept.len() {
10172                if references[next] {
10173                    break;
10174                }
10175                doomed[next] = true;
10176                any = true;
10177            }
10178        }
10179        if !any {
10180            break;
10181        }
10182        (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
10183    }
10184
10185    // A label that lands on an unconditional jump stands for wherever that jump
10186    // goes, so retarget it once and every jump to the label follows for free.
10187    // This is what makes `continue` in a `for` head reach the loop top instead of
10188    // stopping at the update's trailing jump.
10189    let folded: Vec<Option<usize>> = label_kept
10190        .iter()
10191        .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
10192        .collect();
10193    label_kept = folded;
10194
10195    // Jump cleanup, in compacted index space. Two rewrites the reference also
10196    // applies while it resolves labels:
10197    //   * a jump whose destination is the very next instruction does nothing;
10198    //   * a jump to a jump is redirected to its final destination.
10199    // The second can expose the first, so this repeats until it settles.
10200    loop {
10201        let mut delete = vec![false; kept.len()];
10202        let mut changed = false;
10203        for index in 0..kept.len() {
10204            let (op, operands) = &kept[index];
10205            if !is_goto(*op) {
10206                continue;
10207            }
10208            let Some(immediate) = target_kept_index(operands, &label_kept) else {
10209                continue;
10210            };
10211            let target = follow_jump_chain(&kept, &label_kept, immediate);
10212            if target == index + 1 {
10213                delete[index] = true;
10214                changed = true;
10215            } else if matches!(
10216                kept.get(target).map(|(op, _)| *op),
10217                Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
10218            ) {
10219                // Jumping straight to a return or throw is the same as doing it
10220                // here, so the jump becomes that instruction.
10221                kept[index] = (kept[target].0, Vec::new());
10222                changed = true;
10223            } else if target != immediate {
10224                // Redirect to the end of the chain.
10225                let label = index_label[target];
10226                kept[index].1 = vec![Op::Label(label)];
10227                changed = true;
10228            }
10229        }
10230        if !changed {
10231            break;
10232        }
10233        if !delete.iter().any(|deleted| *deleted) {
10234            break;
10235        }
10236        // Drop the deleted instructions and renumber everything.
10237        let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
10238        let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
10239        let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
10240        for (old, entry) in kept.into_iter().enumerate() {
10241            if delete[old] {
10242                continue;
10243            }
10244            moved[old] = Some(next.len());
10245            next.push(entry);
10246            next_spans.push(spans[old]);
10247        }
10248        for (id, slot) in label_kept.iter_mut().enumerate() {
10249            let Some(old) = *slot else { continue };
10250            *slot = match moved.get(old).copied().flatten() {
10251                Some(new) => Some(new),
10252                // The target was deleted: the jump now lands on whatever follows.
10253                None => (old..moved.len())
10254                    .find_map(|i| moved[i])
10255                    .or(Some(next.len())),
10256            };
10257            let _ = id;
10258        }
10259        kept = next;
10260        spans = next_spans;
10261    }
10262
10263    // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
10264    // jump to the next instruction and is deleted, leaving the label at the end with
10265    // nothing pointing at it. If that also strands the last instruction, it goes
10266    // too — which is how a `try` whose body always returns ends on its `ret` rather
10267    // than an implicit `return_undef`.
10268    // Which instructions something still jumps to. Reading the surviving jumps is
10269    // what the reference's reference counts amount to: once a jump has been folded
10270    // away the label it named is unreferenced, even though the program still has a
10271    // label there.
10272    let mut references = vec![false; kept.len() + 1];
10273    let _ = real_labels;
10274    for (_, operands) in &kept {
10275        if let Some(target) = target_kept_index(operands, &label_kept)
10276            && target < references.len()
10277        {
10278            references[target] = true;
10279        }
10280    }
10281    let mut end = kept.len();
10282    while end > 0 {
10283        let last = end - 1;
10284        let reachable = references[last] || end < kept.len();
10285        if reachable {
10286            break;
10287        }
10288        let after_transfer = last
10289            .checked_sub(1)
10290            .map(|previous| {
10291                matches!(
10292                    kept[previous].0,
10293                    Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
10294                )
10295            })
10296            .unwrap_or(false);
10297        if !after_transfer {
10298            break;
10299        }
10300        end = last;
10301    }
10302    kept.truncate(end);
10303    spans.truncate(end);
10304
10305    // Choose an opcode for each instruction and its size, so label offsets can be
10306    // computed.
10307    let chosen = choose_opcodes(&kept, &label_kept);
10308    let offsets = instruction_offsets(&chosen);
10309    let offset = *offsets.last().unwrap_or(&0);
10310
10311    let mut code = Vec::with_capacity(offset);
10312    for (position, (_, operands)) in kept.iter().enumerate() {
10313        let op = chosen[position];
10314        code.push(op as u8);
10315        let operands = retarget_labels(operands, &label_kept, kept.len());
10316        encode_operands(&mut code, op, &operands, offsets[position], &offsets);
10317    }
10318    let stack_size = compute_stack_size(&code);
10319    // Keep only the offsets where the position actually changes: a run of
10320    // instructions on one line is one table entry, and the runtime binary searches
10321    // the table for the frame's pc.
10322    //
10323    // The table always starts at pc 0 with the *function's own* position, because the
10324    // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
10325    // last_line_num)` from `fd->source_pos`, the token the function definition starts at
10326    // (`function`, `async`, a method's property name). An instruction before the first
10327    // recorded operator therefore reports the function's own start, which is what makes a
10328    // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
10329    let mut positions: Vec<LineCol> = vec![LineCol {
10330        pc: 0,
10331        line: state.line,
10332        column: state.column,
10333    }];
10334    let mut last: Option<Position> = None;
10335    for (index, span) in spans.iter().enumerate() {
10336        let Some(pos) = *span else { continue };
10337        if last == Some(pos) {
10338            continue;
10339        }
10340        last = Some(pos);
10341        if pos.line == state.line && pos.column == state.column {
10342            // Already the seed entry above.
10343            continue;
10344        }
10345        positions.push(LineCol {
10346            pc: offsets[index] as u32,
10347            line: pos.line,
10348            column: pos.column,
10349        });
10350    }
10351    (code, stack_size, positions)
10352}
10353
10354/// Whether an instruction always transfers control away, so anything after it in the
10355/// same stream is unreachable.
10356fn is_transfer(op: Opcode) -> bool {
10357    matches!(
10358        op,
10359        Opcode::Goto
10360            | Opcode::Goto8
10361            | Opcode::Goto16
10362            | Opcode::Return
10363            | Opcode::ReturnUndef
10364            | Opcode::Throw
10365            | Opcode::ThrowError
10366            | Opcode::Ret
10367    )
10368}
10369
10370/// Remove the marked instructions and renumber the label table so it keeps pointing
10371/// at the same instructions. A label whose instruction went away moves to whatever
10372/// follows it, since a jump is never left with nowhere to land.
10373fn drop_instructions(
10374    kept: Vec<(Opcode, Vec<Op>)>,
10375    spans: Vec<Option<Position>>,
10376    label_kept: &mut [Option<usize>],
10377    doomed: &[bool],
10378) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
10379    let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
10380    let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
10381    let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
10382    for (old, entry) in kept.into_iter().enumerate() {
10383        if doomed.get(old).copied().unwrap_or(false) {
10384            continue;
10385        }
10386        moved[old] = Some(result.len());
10387        result.push(entry);
10388        result_spans.push(spans[old]);
10389    }
10390    for slot in label_kept.iter_mut() {
10391        let Some(old) = *slot else { continue };
10392        *slot = match moved.get(old).copied().flatten() {
10393            Some(new) => Some(new),
10394            None => (old..moved.len())
10395                .find_map(|i| moved[i])
10396                .or(Some(result.len())),
10397        };
10398    }
10399    (result, result_spans)
10400}
10401
10402fn is_goto(op: Opcode) -> bool {
10403    matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
10404}
10405
10406/// The kept index a jump operand points at.
10407fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
10408    let id = label_id(operands)?;
10409    label_kept.get(id as usize).copied().flatten()
10410}
10411
10412/// Follow a chain of unconditional jumps to its first real destination.
10413fn follow_jump_chain(
10414    kept: &[(Opcode, Vec<Op>)],
10415    label_kept: &[Option<usize>],
10416    start: usize,
10417) -> usize {
10418    let mut current = start;
10419    // `for(;;)` jumps to itself, so the walk has to be bounded.
10420    for _ in 0..kept.len() {
10421        let Some((op, operands)) = kept.get(current) else {
10422            return current;
10423        };
10424        if !is_goto(*op) {
10425            return current;
10426        }
10427        let Some(next) = target_kept_index(operands, label_kept) else {
10428            return current;
10429        };
10430        if next == current {
10431            return current;
10432        }
10433        current = next;
10434    }
10435    current
10436}
10437
10438/// Rewrite label operands from label ids to kept instruction indices.
10439fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
10440    operands
10441        .iter()
10442        .map(|operand| match operand {
10443            Op::Label(label) => {
10444                let target = label_kept
10445                    .get(label.0 as usize)
10446                    .copied()
10447                    .flatten()
10448                    .unwrap_or(kept_len);
10449                Op::Label(Label(target as u32))
10450            }
10451            other => other.clone(),
10452        })
10453        .collect()
10454}
10455
10456/// Encode the resolved instruction stream, choosing short forms where possible.
10457///
10458/// Compute the maximum value-stack depth by exploring the control-flow graph.
10459///
10460/// This is a breadth-first walk from the first instruction, tracking the stack
10461/// depth on entry to each instruction. Every instruction has at most two
10462/// successors (fall through, and a jump target), so a worklist over byte offsets
10463/// is enough. The reference does the same thing in `compute_stack_size`, which is
10464/// why the resulting numbers match exactly.
10465///
10466/// Instructions that pop a variable number of values (`call`, `array_from`, …)
10467/// encode that count in their operand, which is added to the static `n_pop`.
10468fn compute_stack_size(code: &[u8]) -> u32 {
10469    let mut depth_at = vec![u16::MAX; code.len()];
10470    // Each entry carries the enclosing `catch` levels, innermost last, because
10471    // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
10472    // offset and forgets that level.
10473    let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
10474    let mut max_depth = 0u32;
10475
10476    while let Some((pc, depth, catch_levels)) = worklist.pop() {
10477        if pc >= code.len() {
10478            continue;
10479        }
10480        if depth_at[pc] != u16::MAX {
10481            continue;
10482        }
10483        force_depth(&mut depth_at, pc, depth);
10484
10485        let Some(op) = Opcode::from_u8(code[pc]) else {
10486            break;
10487        };
10488        let info = op.info();
10489        let next = pc + info.size as usize;
10490        if next > code.len() {
10491            break;
10492        }
10493        let mut n_pop = info.n_pop as u32;
10494        let mut n_push = info.n_push as u32;
10495        // Variable-length forms carry their count in the operand.
10496        match info.format {
10497            crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
10498                n_pop += read_u16(code, pc + 1) as u32;
10499            }
10500            crate::opcode::OpFormat::Npopx => {
10501                n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
10502            }
10503            _ => {}
10504        }
10505        // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
10506        // are the `set_` variant; the table already records that, so nothing to
10507        // adjust here.
10508        let _ = &mut n_push;
10509
10510        // The depth before this instruction's own push, which is what a `catch`
10511        // records as its level.
10512        let depth_before = depth;
10513        let mut depth = depth.saturating_sub(n_pop) + n_push;
10514        let mut catch_levels = catch_levels;
10515        if op == Opcode::NipCatch {
10516            // Discard everything above the innermost catch offset, keeping the value
10517            // on top: the frame the code after this sees is the same shape it would
10518            // have had if the `try` were not there.
10519            if let Some(base) = catch_levels.pop() {
10520                depth = base + 1;
10521            }
10522        }
10523        max_depth = max_depth.max(depth);
10524
10525        // Successors.
10526        let target = jump_target_of(code, pc, op);
10527        match op {
10528            Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10529                if let Some(target) = target {
10530                    worklist.push((target, depth, catch_levels));
10531                }
10532            }
10533            Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
10534                if let Some(target) = target {
10535                    worklist.push((target, depth, catch_levels.clone()));
10536                }
10537                worklist.push((next, depth, catch_levels));
10538            }
10539            // A `catch` records an exception edge to the handler. The handler is
10540            // entered with the thrown value on top of the stack, in the slot the
10541            // catch offset occupies on the normal path — which is why the handler's
10542            // first instruction can `put_loc` the exception away, and why the depth
10543            // is the same on both paths.
10544            Opcode::Catch => {
10545                if let Some(target) = target {
10546                    // The handler is protected by the *enclosing* catch, not by this
10547                    // one: an error raised inside it is what the handler's own
10548                    // `catch` catches.
10549                    worklist.push((target, depth, catch_levels.clone()));
10550                }
10551                catch_levels.push(depth_before);
10552                worklist.push((next, depth, catch_levels));
10553            }
10554            // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
10555            // rewind past it too. Its level sits one slot higher than a `catch`'s:
10556            // the iterator and next-method slots occupy the offset's place.
10557            Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
10558                if let Some(target) = target {
10559                    worklist.push((target, depth, catch_levels.clone()));
10560                }
10561                catch_levels.push(depth_before + 1);
10562                worklist.push((next, depth, catch_levels));
10563            }
10564            // `gosub` calls a subroutine with the return address on top. The opcode
10565            // table records no push for it — `ret` is what pops the slot — so the
10566            // extra one is added here, where the depth of the subroutine's first
10567            // instruction is being computed.
10568            Opcode::Gosub => {
10569                if let Some(target) = target {
10570                    worklist.push((target, depth + 1, catch_levels.clone()));
10571                }
10572                worklist.push((next, depth, catch_levels));
10573            }
10574            // `ret` goes back to a `gosub`; nothing here follows it.
10575            Opcode::Ret
10576            | Opcode::Return
10577            | Opcode::ReturnUndef
10578            | Opcode::Throw
10579            | Opcode::ThrowError => {}
10580            _ => worklist.push((next, depth, catch_levels)),
10581        }
10582    }
10583    max_depth
10584}
10585
10586/// Record the stack depth on entry to `pc`, keeping the deeper value if the
10587/// instruction is reachable more than once.
10588fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
10589    let clamped = depth.min(u16::MAX as u32 - 1) as u16;
10590    if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
10591        depth_at[pc] = clamped;
10592    }
10593}
10594
10595fn read_u16(code: &[u8], at: usize) -> u16 {
10596    let mut value = 0u16;
10597    for i in 0..2 {
10598        value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
10599    }
10600    value
10601}
10602
10603/// The absolute target of a jump instruction, if it has one.
10604fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
10605    let info = op.info();
10606    let position = pc + 1;
10607    match info.format {
10608        crate::opcode::OpFormat::Label8 => {
10609            let offset = *code.get(position)? as i8 as i64;
10610            Some((position as i64 + offset) as usize)
10611        }
10612        crate::opcode::OpFormat::Label16 => {
10613            let offset = read_u16(code, position) as i16 as i64;
10614            Some((position as i64 + offset) as usize)
10615        }
10616        crate::opcode::OpFormat::Label => {
10617            let mut offset = 0i32;
10618            for i in 0..4 {
10619                offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
10620            }
10621            Some((position as i64 + offset as i64) as usize)
10622        }
10623        _ => None,
10624    }
10625}
10626
10627fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
10628    use Opcode::*;
10629    match (op, operands.first()) {
10630        (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
10631            op.short_form(*value as u32).unwrap_or(op)
10632        }
10633        (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
10634        (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
10635        (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
10636        | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
10637        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
10638        // A declared global is reached through its reference cell, so it shares
10639        // the `var_ref` encodings, short forms included.
10640        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
10641            op.short_form(*index).unwrap_or(op)
10642        }
10643        (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
10644            op.short_form(*count as u32).unwrap_or(op)
10645        }
10646        _ => op,
10647    }
10648}
10649
10650/// The byte offset each instruction will start at, plus the total code size.
10651fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
10652    let mut offsets = Vec::with_capacity(chosen.len() + 1);
10653    let mut offset = 0usize;
10654    for op in chosen {
10655        offsets.push(offset);
10656        offset += op.size() as usize;
10657    }
10658    offsets.push(offset);
10659    offsets
10660}
10661
10662/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
10663/// the offset actually fits.
10664///
10665/// The choice is circular: an instruction's size decides the offsets of everything after
10666/// it, and the offsets decide whether a jump may be short. So this starts with every jump
10667/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
10668/// Shrinking only ever *shortens* distances, so the loop converges.
10669///
10670/// Doing it in one pass instead — which is what this used to do — silently truncated any
10671/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
10672/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
10673/// with four closures in its body simply stopped, with no error and no output past the
10674/// first iteration.
10675fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
10676    let mut chosen: Vec<Opcode> = kept
10677        .iter()
10678        .map(|(op, operands)| choose_short_form(*op, operands))
10679        .collect();
10680    // A jump the compiler emitted in its widest form, and the forms it may shrink to.
10681    let candidates = |op: Opcode| match op {
10682        Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
10683        Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
10684        Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
10685        _ => None,
10686    };
10687    loop {
10688        let offsets = instruction_offsets(&chosen);
10689        let mut changed = false;
10690        for index in 0..kept.len() {
10691            let (op, operands) = &kept[index];
10692            let Some((short, medium, has_medium)) = candidates(*op) else {
10693                continue;
10694            };
10695            if chosen[index] == short {
10696                continue;
10697            }
10698            let Some(target) = target_kept_index(operands, label_kept) else {
10699                continue;
10700            };
10701            let Some(&target_offset) = offsets.get(target) else {
10702                continue;
10703            };
10704            // A jump is relative to the byte after its opcode, which is the convention
10705            // `jump_target_of` decodes with.
10706            let relative = target_offset as i64 - (offsets[index] as i64 + 1);
10707            if (-128..=127).contains(&relative) {
10708                chosen[index] = short;
10709                changed = true;
10710            } else if has_medium
10711                && chosen[index] == Opcode::Goto
10712                && (-32_768..=32_767).contains(&relative)
10713            {
10714                // Too far for 8 bits and close enough for 16. Only `goto` has a medium
10715                // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
10716                // the reference encodes them.
10717                chosen[index] = medium;
10718                changed = true;
10719            }
10720        }
10721        if !changed {
10722            return chosen;
10723        }
10724    }
10725}
10726
10727fn encode_operands(
10728    code: &mut Vec<u8>,
10729    op: Opcode,
10730    operands: &[Op],
10731    position: usize,
10732    offsets: &[usize],
10733) {
10734    use crate::opcode::OpFormat::*;
10735    let info = op.info();
10736    let write_slot = |code: &mut Vec<u8>, slot: Slot| {
10737        let index = match slot {
10738            Slot::Arg(i)
10739            | Slot::Loc(i)
10740            | Slot::VarRef(i)
10741            | Slot::Global(i)
10742            | Slot::GlobalDecl(i) => i,
10743        };
10744        code.extend_from_slice(&(index as u16).to_be_bytes());
10745    };
10746    match info.format {
10747        None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
10748        U8 | Const8 => {
10749            if let Some(value) = operands.first().and_then(operand_uint) {
10750                code.push(value as u8);
10751            }
10752        }
10753        // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
10754        // like their wide counterparts, only one byte wide.
10755        Loc8 => {
10756            if let Some(Op::Slot(slot)) = operands.first() {
10757                let index = match slot {
10758                    Slot::Arg(i)
10759                    | Slot::Loc(i)
10760                    | Slot::VarRef(i)
10761                    | Slot::Global(i)
10762                    | Slot::GlobalDecl(i) => *i,
10763                };
10764                code.push(index as u8);
10765            }
10766        }
10767        I8 => {
10768            if let Some(value) = operands.first().and_then(operand_int) {
10769                code.push(value as i8 as u8);
10770            }
10771        }
10772        U16 | Npop => {
10773            if let Some(value) = operands.first().and_then(operand_int) {
10774                code.extend_from_slice(&(value as u16).to_be_bytes());
10775            }
10776        }
10777        I16 => {
10778            if let Some(value) = operands.first().and_then(operand_int) {
10779                code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
10780            }
10781        }
10782        I32 => {
10783            if let Some(value) = operands.first().and_then(operand_int) {
10784                code.extend_from_slice(&value.to_be_bytes());
10785            }
10786        }
10787        U32 | Const => {
10788            if let Some(value) = operands.first().and_then(operand_uint) {
10789                code.extend_from_slice(&value.to_be_bytes());
10790            }
10791        }
10792        Loc | Arg | VarRef => {
10793            if let Some(Op::Slot(slot)) = operands.first() {
10794                write_slot(code, *slot);
10795            }
10796        }
10797        Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
10798            if let Some(Op::AtomId(index)) = operands.first() {
10799                code.extend_from_slice(&index.to_be_bytes());
10800            }
10801            // The trailing immediate means different things per format, and the
10802            // atom forms that carry a *label* have to resolve it like any other
10803            // jump, so they cannot share the `U8`/`U16` arms above.
10804            match info.format {
10805                AtomU8 | AtomLabelU8 => {
10806                    if let Some(value) = operands.get(1).and_then(operand_uint) {
10807                        code.push(value as u8);
10808                    }
10809                }
10810                AtomU16 | AtomLabelU16 => {
10811                    if let Some(value) = operands.get(1).and_then(operand_uint) {
10812                        code.extend_from_slice(&(value as u16).to_be_bytes());
10813                    }
10814                }
10815                _ => {}
10816            }
10817        }
10818        NpopU16 => {
10819            for operand in operands.iter().take(2) {
10820                if let Some(value) = operand_uint(operand) {
10821                    code.extend_from_slice(&(value as u16).to_be_bytes());
10822                }
10823            }
10824        }
10825        Label | Label8 | Label16 | LabelU16 => {
10826            if let Some(Op::Label(label)) = operands.first() {
10827                // Labels were already remapped to kept-instruction indices.
10828                let Some(&target) = offsets.get(label.0 as usize) else {
10829                    debug_assert!(false, "label {} is past the end", label.0);
10830                    return;
10831                };
10832                let relative = target as i64 - (position as i64 + 1);
10833                match info.format {
10834                    Label8 => code.push(relative as i8 as u8),
10835                    Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
10836                    // `label_u16` stores the target followed by an unrelated u16.
10837                    LabelU16 => {
10838                        code.extend_from_slice(&(relative as i32).to_be_bytes());
10839                        if let Some(value) = operands.get(1).and_then(operand_uint) {
10840                            code.extend_from_slice(&(value as u16).to_be_bytes());
10841                        }
10842                    }
10843                    _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
10844                }
10845            }
10846        }
10847    }
10848}
10849
10850fn operand_int(op: &Op) -> Option<i32> {
10851    match op {
10852        Op::Int(value) => Some(*value),
10853        _ => None,
10854    }
10855}
10856
10857fn operand_uint(op: &Op) -> Option<u32> {
10858    match op {
10859        Op::Const(value) | Op::AtomId(value) => Some(*value),
10860        Op::Int(value) => Some(*value as u32),
10861        _ => None,
10862    }
10863}
10864
10865/// Disassemble a compiled function.
10866pub fn disassemble(function: &CompiledFunction) -> String {
10867    disasm::disassemble_program(function)
10868}
10869
10870/// How many of an object pattern's keys are computed.
10871///
10872/// Only the count matters: a rest element needs a run-time key log exactly when at least one
10873/// key is not a literal, and the log is sized by walking the pattern anyway.
10874fn computed_key_count(properties: &[Option<PatternElement>]) -> usize {
10875    properties
10876        .iter()
10877        .flatten()
10878        .filter(|element| {
10879            matches!(
10880                element,
10881                PatternElement::Property {
10882                    key: PropName::Computed(_),
10883                    ..
10884                }
10885            )
10886        })
10887        .count()
10888}