Skip to main content

js_compile/
compiler.rs

1//! The bytecode compiler.
2//!
3//! Compilation is a single walk over the AST that emits *symbolic* instructions
4//! (jump targets are label ids, variable references are names), followed by a
5//! resolution pass that turns them into final bytecode. Splitting it this way
6//! keeps the emitter readable: nothing has to know slot indices or byte offsets
7//! while it is still discovering them.
8//!
9//! Variable resolution follows the reference implementation's model:
10//!
11//! * every function has a flat table of arguments and locals;
12//! * block scopes form a chain through [`VarDef::scope_next`], which is what makes
13//!   `let`/`const` bindings visible only inside their block and lets the runtime
14//!   put them back into the temporal dead zone on entry;
15//! * a name that is not in the current function is looked up in the enclosing
16//!   ones; if found, the variable is marked captured and reached through a
17//!   closure reference;
18//! * a name found nowhere is a global, reached through a closure entry as well.
19//!
20//! Emission order and instruction choice deliberately mirror `quickjs.c`: the
21//! differential test compares disassembly with the reference opcode by opcode, so
22//! an unnecessary `dup` or a differently chosen short form shows up immediately.
23
24use crate::bytecode::LineCol;
25use crate::bytecode::{
26    ANONYMOUS_BINDING, Atom, ClosureType, ClosureVar, Constant, EvalSite, EvalVisible, ExportEntry,
27    Function as CompiledFunction, FunctionKind, ImportEntry, ModuleMeta, ModuleRequest, VarDef,
28    VarKind,
29};
30use crate::disasm;
31use crate::opcode::Opcode;
32use js_parse::Position;
33use js_parse::Span;
34use js_parse::SyntaxError;
35use js_parse::Wtf8;
36use js_parse::ast::{self, *};
37
38/// A label id, local to the function being compiled.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub struct Label(u32);
41
42/// The name of the hidden local that carries a function's `[[HomeObject]]` for `super`.
43///
44/// The reference calls the variable `home_object` and prints it as `"<home_object>"`, which
45/// is why the brackets are part of the name; nothing a program writes can collide with it.
46const HOME_OBJECT: &str = "<home_object>";
47
48/// The local holding the function `super()` constructs from.
49///
50/// The reference's `JS_ATOM_this_active_func`. Unlike `<home_object>` this one is printed
51/// with its dots, because that is the atom's text: its dump shows `1: var this.active_func`.
52const ACTIVE_FUNC: &str = "this.active_func";
53
54/// The local holding `new.target`, likewise spelled the way the reference's dump shows it.
55const NEW_TARGET: &str = "new.target";
56
57/// Stand-in for a constant-pool index that is only known later in the instruction stream.
58///
59/// One user: the class constructor's `fclosure`, whose slot the reference assigns after the
60/// members have taken theirs. `u32::MAX` is not a reachable pool index — a class with four
61/// billion members is not a thing — and the compiler patches it before resolution runs, so a
62/// missed patch is a panic-free compiler error rather than a wrong jump.
63const CTOR_INDEX_PLACEHOLDER: u32 = u32::MAX;
64
65/// One step of a class's initialisation, in source order.
66///
67/// A static block is not a member the class keeps — it is a run of statements that executes
68/// at the point the class definition reaches it — so it belongs *inside* the initialiser
69/// function rather than alongside the fields as a separate pass. Merging the two is what
70/// makes `static a = 1; static {}` and `static {}; static a = 1` order-sensitive in the
71/// same way the reference is.
72enum StaticInitItem<'a> {
73    /// `static x = value`, or `x = value` for the instance half.
74    Field(FieldKey<'a>, Option<&'a Expr>),
75    /// `static { … }`
76    Block {
77        body: &'a [Stmt],
78        /// Position of the `{`, which is where the reference puts the function.
79        body_start: Position,
80    },
81}
82
83/// How one field names its property.
84///
85/// A computed key is *not* re-evaluated per instance: the reference evaluates it once at
86/// class definition and stores it in a `<computed_field>N` binding, because the key of a field
87/// is fixed when the class is created. Keeping the expression here instead made
88/// `class C { [k] = 1 }` re-read `k` on every `new`, which is a different program when `k`
89/// changes — and worse, the operand order was wrong, so `class C { ["a"] = 1 }` produced
90/// `{1: "a"}`.
91enum FieldKey<'a> {
92    /// `x`, `"x"`, `0` — the property name is static text.
93    Literal(&'a PropKey),
94    /// `#x`: the class-scope binding that holds the private symbol.
95    Private(String),
96    /// `[expr]`: the class-scope binding that holds the evaluated key.
97    Computed(String),
98}
99
100/// The `var_block` sentinel for a binding that lives at function scope.
101///
102/// It has to be a value a *real* block key can never take. Block keys are source
103/// offsets, so `0` is a perfectly ordinary key — the first block statement of a file
104/// gets it — and using `0` as the sentinel made `{ let y = 2 }` at offset zero look
105/// like a function-scoped `var`, which is how a top-level block's `let` leaked out of
106/// its block. The body block already uses `u64::MAX` to stay clear of offsets, so the
107/// sentinel takes the slot below it.
108const FUNCTION_SCOPE: u64 = u64::MAX - 3;
109
110/// The `var_block` sentinel for a binding of the parameter list.
111///
112/// A function whose parameter list contains a default expression gets *two* variable
113/// environments: one for the parameters and one for the body, so a `var` in the body
114/// that shares a name with a parameter is a different binding. The parameter bindings
115/// therefore need a scope key of their own: reachable while the defaults are
116/// evaluated, invisible to the body, and never merged with a body `var` of the same
117/// name.
118///
119/// Without this, `function f(a = 1, p = () => a) { var a = 2 }` made `p()` return 2:
120/// the closure and the body shared one slot, when only the parameters were in scope
121/// when it was created.
122const PARAM_SCOPE: u64 = u64::MAX - 4;
123
124/// The name of the hidden local a `using` declaration caches its dispose method in.
125///
126/// It has to be a name no source can produce, because a script may declare anything: the
127/// angle brackets keep it out of the identifier grammar, exactly like `<ret>`.
128fn using_method_name(name: &str) -> String {
129    format!("<using.method {name}>")
130}
131
132/// The `blocks` parent sentinel for "this block has no enclosing block".
133///
134/// Same reasoning as [`FUNCTION_SCOPE`]: `0` is a legal block key, and when it was
135/// also the terminator the chain walk from the script body reached the file's
136/// offset-zero block and treated it as an *enclosing* block — so that block's `let`
137/// leaked into the body scope.
138const NO_PARENT: u64 = u64::MAX - 2;
139
140/// The block key for a script body. Distinct from both sentinels and unreachable from
141/// any source offset.
142const SCRIPT_BODY: u64 = u64::MAX - 1;
143
144/// An operand of a symbolic instruction.
145#[derive(Debug, Clone, PartialEq)]
146enum Op {
147    /// An immediate integer.
148    Int(i32),
149    /// A jump target.
150    Label(Label),
151    /// A constant pool index.
152    Const(u32),
153    /// An atom, before interning.
154    Atom(Atom),
155    /// An interned atom, as an index into [`Function::atoms`].
156    AtomId(u32),
157    /// A resolved slot.
158    Slot(Slot),
159}
160
161/// Where a resolved variable lives.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163enum Slot {
164    Arg(u32),
165    Loc(u32),
166    VarRef(u32),
167    /// A global, by closure-var index.
168    Global(u32),
169    /// A global *declared* in this script. The reference keeps these bindings in
170    /// reference cells so that the script and any closure share one variable, so
171    /// a store goes through `put_var_ref` while a read uses `get_var`.
172    GlobalDecl(u32),
173}
174
175/// What a symbolic variable access does, which decides the final opcode.
176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177enum VarAction {
178    /// Read the value.
179    Get,
180    /// Read the value, yielding `undefined` for an undeclared global.
181    GetUndef,
182    /// Write, leaving nothing on the stack.
183    Put,
184    /// Write and initialise, leaving the value on the stack.
185    PutInit,
186    /// Write, leaving the value on the stack.
187    Set,
188    /// Initialise a binding that may only be initialised once, such as a derived
189    /// constructor's `this`.
190    PutInitChecked,
191    /// Initialise, leaving the value on the stack and without the `const` check.
192    ///
193    /// A class's own scope binding is a `const` that has to be initialised in the middle
194    /// of the definition — after the constructor exists but before the static fields run
195    /// — and the value has to survive for the outer store to use.
196    SetInit,
197    /// Write a binding that lives in a reference cell.
198    PutRef,
199}
200
201#[derive(Debug, Clone)]
202enum Insn {
203    /// A fully determined instruction.
204    Fixed { op: Opcode, operands: Vec<Op> },
205    /// A variable access, resolved in the second pass.
206    ///
207    /// `block` is the lexical block the access appears in, which is what makes
208    /// shadowing work: two bindings can share a name, and the one that wins is
209    /// whichever scope encloses the access.
210    Var {
211        action: VarAction,
212        name: String,
213        block: u64,
214        /// Whether the access was written in the parameter list; see
215        /// [`FnState::in_params`].
216        in_params: bool,
217    },
218    /// Close a binding *if* it turned out to be captured.
219    ///
220    /// Whether a `for (let i ...)` loop variable needs a fresh per-iteration cell is
221    /// only known once the body has been compiled — a closure created there is the
222    /// thing that makes it necessary. The reference emits `close_loc` exactly in that
223    /// case and nothing otherwise, so the decision is deferred to [`resolve`] instead
224    /// of emitted blind.
225    CloseCaptured { name: String, block: u64 },
226    /// `delete name`, which can only answer `false` once the binding is known.
227    ///
228    /// It is not a `Var` action because `delete_var` carries an *atom*: the runtime
229    /// looks the name up on the global object, which is what distinguishes an implicit
230    /// global (configurable, deletable) from a declared one (a binding, always `false`).
231    DeleteVar { name: String },
232    /// An instruction that dead-code elimination removed. It keeps its slot so
233    /// that label indices stay valid, and resolves to no bytecode.
234    Dead,
235}
236
237/// Where `break` and `continue` jump to.
238///
239/// Targets are stacked as the compiler enters loops and labelled statements, so a
240/// bare `break` needs no analysis: it is simply the innermost target. A labelled
241/// one searches outward by name.
242#[derive(Debug, Clone)]
243struct JumpTarget {
244    /// The labels attached to this target. `l: for(;;)` gives one name; a bare
245    /// loop gives none; `a: b: for(;;)` gives two, because both labels name the
246    /// same statement and `break a` must reach the same place as `break b`.
247    names: Vec<String>,
248    /// Where `break` lands. `None` for a construct `break` may only leave, not
249    /// target — a `try`, whose entry exists purely to unwind.
250    break_label: Option<Label>,
251    /// Where `continue` lands. `None` for anything that is not a loop.
252    continue_label: Option<Label>,
253    /// Stack slots to discard when control leaves this construct by a jump.
254    ///
255    /// Both `switch` and `try` leave something on the value stack for the duration
256    /// of the construct — the discriminant, or the `catch` offset — and a jump out
257    /// has to take it with it. A loop leaves nothing.
258    drop_count: u32,
259    /// The finalizer to run when control leaves this construct.
260    ///
261    /// Set on a `try` even when it has no `finally`: the label is always emitted and
262    /// the empty-subroutine removal cleans up afterwards, so the code that unwinds
263    /// does not have to know whether a finalizer exists.
264    finally_label: Option<Label>,
265    /// Whether this is a labelled non-loop statement, which an unlabelled `break`
266    /// does not reach.
267    is_regular_stmt: bool,
268    /// Whether leaving this construct has to close an iterator.
269    ///
270    /// A `for`/`of` loop keeps an iterator on the value stack, and leaving early has
271    /// to run its `return` method. `for`/`in` keeps only an enumeration object, which
272    /// is dropped rather than closed.
273    has_iterator: bool,
274    /// Whether that iterator speaks the *async* protocol.
275    ///
276    /// An async close has to `await` the inner `return`, so it is an inline instruction
277    /// sequence rather than one opcode — the reference's `emit_iterator_close`.
278    is_async_iterator: bool,
279}
280
281/// Whether a named property read should be `get_field2` rather than `dup; get_field`.
282///
283/// Both leave `source value` on the stack, so this is purely which spelling the reference
284/// picked, and it picked it by whether it had to build a *reference* for the target:
285///
286/// * a target that is itself a pattern starts by boxing the value, so the copy is what it
287///   consumes — `get_field2` (and a default does not change that: `{a: {b} = {}}` still
288///   destructures);
289/// * a `let`/`const` binding needs no reference, so the reference takes the short form;
290/// * a `var`, and any assignment target, go through `dup; get_field`, because the
291///   reference builds a reference for them — which is what `with` needs.
292fn reads_with_get_field2(decl: Option<VarDeclKind>, value: &Pattern) -> bool {
293    nests_a_pattern(value) || matches!(decl, Some(VarDeclKind::Let) | Some(VarDeclKind::Const))
294}
295
296/// Whether binding this pattern starts by boxing the value it was handed.
297fn nests_a_pattern(pattern: &Pattern) -> bool {
298    match &pattern.kind {
299        PatternKind::Array { .. } | PatternKind::Object { .. } => true,
300        PatternKind::Assign { target, .. } => nests_a_pattern(target),
301        _ => false,
302    }
303}
304
305/// `copy_data_properties` flags for an object-literal spread.
306///
307/// The byte packs three fields: the low bits are the stack offset of the source,
308/// the next three the offset of the exclusion list, and bit 2 asks for symbol keys
309/// as well as string keys. A spread passes a literal `null` exclusion list right
310/// below the source, so that field stays zero and only the source offset and the
311/// symbol bit are set — hence `{...v}` copies symbols, which the flag name says.
312const COPY_ALL_PROPERTIES: i32 = 2 | (1 << 2);
313
314/// The expression a `...` introduces.
315///
316/// The parser marks the spread in two places — the element/property variant and an
317/// [`ExprKind::Spread`] wrapper around the argument — so the wrapper has to be
318/// stepped through before the argument can be compiled.
319fn spread_argument(spread: &Expr) -> &Expr {
320    match &spread.kind {
321        ExprKind::Spread(inner) => inner,
322        _ => spread,
323    }
324}
325
326/// The flag byte `define_method` takes.
327///
328/// The low two bits pick value/getter/setter; bit 2 marks the property
329/// enumerable, which every object-literal method is.
330/// What kind of class constructor a function is being compiled as.
331///
332/// A constructor is not an ordinary method: a base one materialises `this` and refuses
333/// to run without `new`, and a derived one starts with `this` in the dead zone until
334/// `super()` produces it.
335#[derive(Debug, Clone, Copy, PartialEq, Eq)]
336enum CtorKind {
337    /// Not a class constructor.
338    None,
339    /// A constructor of a class without `extends`.
340    Base,
341    /// A constructor of a class with `extends`.
342    Derived,
343}
344
345/// The flag byte `define_method` takes for a class member.
346///
347/// The low two bits pick value/getter/setter; bit 2 marks the property enumerable, which
348/// a class method is *not* — that is the whole difference from an object-literal method,
349/// and the reason `Object.keys(C.prototype)` stays empty.
350fn class_method_flags(kind: MethodKind) -> i32 {
351    match kind {
352        MethodKind::Constructor | MethodKind::Method => 0,
353        MethodKind::Get => 1,
354        MethodKind::Set => 2,
355    }
356}
357
358fn define_method_flags(kind: PropertyKind) -> i32 {
359    let base = match kind {
360        PropertyKind::Value | PropertyKind::Method => 0,
361        PropertyKind::Get => 1,
362        PropertyKind::Set => 2,
363    };
364    base | 4
365}
366
367/// Convert a numeric property key to the text an atom would be made from.
368///
369/// Only the range where Rust and JavaScript agree on the spelling is accepted.
370/// Both print the shortest representation that round-trips, so plain decimal
371/// digits match; they diverge at the extremes, where JavaScript switches to an
372/// exponent (`1e-7`, `1e+21`) and Rust does not. Rather than emit an atom that
373/// differs from the reference, those keys are rejected.
374fn numeric_key_text(value: f64, span: Span) -> Result<String, SyntaxError> {
375    if !value.is_finite() {
376        return Err(SyntaxError::new(
377            "a non-finite numeric property key is not supported by the compiler yet",
378            span,
379        ));
380    }
381    if value == value.trunc() && value.abs() < 1e21 {
382        return Ok(format!("{}", value as i64));
383    }
384    if value.abs() >= 1e-6 && value.abs() < 1e21 {
385        return Ok(format!("{value}"));
386    }
387    Err(SyntaxError::new(
388        "a numeric property key outside [1e-6, 1e21) is not supported by the compiler yet",
389        span,
390    ))
391}
392
393/// Collect the operands of a same-operator logical run, in source order.
394///
395/// Recurses down the left spine only: `((a || b) || c)` contributes `a`, `b`, then
396/// the caller appends `c`. A node with a different operator is one operand.
397fn collect_same_operator<'a>(op: LogicalOp, expr: &'a Expr, out: &mut Vec<&'a Expr>) {
398    if let ExprKind::Logical {
399        op: inner_op,
400        left,
401        right,
402    } = &expr.kind
403        && *inner_op == op
404    {
405        collect_same_operator(op, left, out);
406        out.push(right);
407        return;
408    }
409    out.push(expr);
410}
411
412/// The jump a logical assignment or `??` takes when the value is kept.
413///
414/// `||` and `&&` branch on truthiness, so the same opcode serves both the operator
415/// and `??` once [`Compiler::emit_logical_test`] has pushed a boolean. `??` keeps
416/// the value when it is *not* null-ish, so it is the `if_false` side.
417fn logical_jump(op: AssignOp) -> Opcode {
418    match op {
419        AssignOp::Or => Opcode::IfTrue,
420        AssignOp::And | AssignOp::Coalesce => Opcode::IfFalse,
421        _ => Opcode::IfFalse,
422    }
423}
424
425/// Whether a loop enumerates keys or values.
426#[derive(Debug, Clone, Copy, PartialEq, Eq)]
427enum ForLoopKind {
428    /// `for (x in o)` — the keys of an object.
429    In,
430    /// `for (x of o)` — the values of an iterable.
431    Of,
432    /// `for await (x of o)` — the values of an async iterable, or of a sync one.
433    AwaitOf,
434}
435
436/// Which part of a `try` statement a block key refers to.
437#[derive(Debug, Clone, Copy)]
438enum TryPart {
439    /// The guarded block.
440    Block = 0,
441    /// The handler body, excluding the catch parameter.
442    Catch = 1,
443    /// The finalizer block.
444    Finally = 2,
445    /// The catch parameter's own scope.
446    Param = 3,
447}
448
449/// A lexical scope, identified while hoisting and numbered at the end.
450///
451/// Scope identity is needed in two passes that must agree: declarations are
452/// hoisted in source order (so slots come out in source order, as in the
453/// reference), but a binding belongs to the block it was written in, which is only
454/// entered later. Blocks are therefore keyed by the source position of their
455/// opening brace, which is stable across both walks.
456#[derive(Debug, Clone, Copy)]
457struct Block {
458    /// Source position of the block.
459    key: u64,
460    /// The block this one is nested in; `0` for the function scope.
461    parent: u64,
462}
463
464/// One function under construction.
465struct FnState {
466    /// The function's own source range, used to record its text for
467    /// `Function.prototype.toString`.
468    span: Option<(usize, usize)>,
469    name: String,
470    kind: FunctionKind,
471    strict: bool,
472    args: Vec<VarDef>,
473    vars: Vec<VarDef>,
474    closure_vars: Vec<ClosureVar>,
475    cpool: Vec<Constant>,
476    atoms: Vec<Atom>,
477    /// Every lexical scope, in creation order.
478    blocks: Vec<Block>,
479    /// The block currently being parsed or compiled.
480    current_block: u64,
481    /// The block a *nested* function was created in, so a capture made from here can be
482    /// resolved against the enclosing function's lexical scopes rather than against a
483    /// flat name table. Without it, `function f(){ class S{} }` capturing `S` found the
484    /// function's own `let S` instead of the class body's `const S`.
485    created_in_block: u64,
486    /// The block each local was declared in, parallel to `vars`. `0` means the
487    /// function scope, where `var` bindings live.
488    var_block: Vec<u64>,
489    /// Set when the expression just compiled left no value on the stack.
490    ///
491    /// Only a store can do that: `put_field` consumes the object and the value, so
492    /// an assignment whose result is unused emits nothing extra. The expression
493    /// statement then has nothing to drop.
494    no_value: bool,
495    /// Whether a label was placed since the last instruction was emitted.
496    ///
497    /// The `put`/`get` fold is only valid when the two are adjacent in the final
498    /// stream; a label in between means a jump can land on the read, so the store has
499    /// to keep consuming its value. A flag is enough and avoids having to reason about
500    /// which index a label recorded.
501    label_since_insn: bool,
502    /// Whether the value of the expression being compiled is thrown away.
503    ///
504    /// Only an expression *statement* discards its value, and only the outermost
505    /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
506    /// still has to produce a value. Consumed by [`Compiler::assign`], which is
507    /// the one construct whose bytecode depends on it.
508    discard_value: bool,
509    /// The block that holds the function body.
510    body_block: u64,
511    /// Head of each scope's binding chain, indexed by level. Filled in by
512    /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
513    block_heads: Vec<i32>,
514    /// Enclosing `break`/`continue` targets, innermost last.
515    jump_targets: Vec<JumpTarget>,
516    insns: Vec<Insn>,
517    labels: Vec<Option<usize>>,
518    /// Captured locals, which need a reference cell.
519    var_ref_count: u32,
520    line: u32,
521    column: u32,
522    /// Whether this is a script body. A script's top-level declarations create
523    /// global properties rather than locals, which is why they show up as
524    /// closure variables with `[global_decl]`.
525    is_script: bool,
526    /// Whether this is a module body.
527    ///
528    /// A module body is a script in every respect that matters here — no `arguments`,
529    /// no `this` of its own — but its top-level declarations are *module*-scoped
530    /// instead of global, which is what this flag changes.
531    is_module: bool,
532    /// Whether the function is an arrow, which never gets its own `arguments`.
533    is_arrow: bool,
534    /// The name a *named function expression* binds inside its own body.
535    /// How many parameters count towards `.length`.
536    defined_args: u32,
537    /// Parameters that are not a plain name, with the argument slot each came from.
538    param_prologue: Vec<(usize, Pattern)>,
539    /// What kind of class constructor this function is, if any.
540    ctor_kind: CtorKind,
541    /// Whether the class has instance fields, so the constructor has to run their
542    /// initialiser before it returns.
543    /// What the nested function about to be compiled should be told about its class.
544    class_ctor_pending: Option<CtorKind>,
545    /// Whether this function needs the hidden `this` local, because an arrow inside it
546    /// refers to `this`.
547    ///
548    /// An arrow has no `this` of its own, so the reference materialises the enclosing
549    /// function's receiver into a local and lets the arrow capture it as an ordinary
550    /// closure variable. Declaring the local is not enough on its own: the store that
551    /// fills it has to be prepended to the body, which is what this flag arranges.
552    needs_this_local: bool,
553    /// The same, for `arguments`.
554    needs_arguments_local: bool,
555    /// The same, for `new.target`.
556    needs_new_target_local: bool,
557    /// Whether the body already opens by filling a `this` local, which
558    /// [`Compiler::begin_this_local`] does for a constructor and a field initialiser.
559    has_this_prologue: bool,
560    /// The same, for `<home_object>`: the object `super` resolves against.
561    ///
562    /// An arrow and a static block have no home object of their own — only the method or
563    /// initialiser they were written in does — so `super.x` inside one is a read of the
564    /// enclosing function's `[[HomeObject]]`. The value is materialised into a local there
565    /// by `special_object 4`, the same way `this` is.
566    needs_home_object_local: bool,
567    /// The same, for `this.active_func`: the function `super()` constructs from.
568    ///
569    /// An arrow has no `super` of its own, so it reads the enclosing function's — and that
570    /// is a *lexical* relationship, not a stack one. The reference keeps `this_active_func`
571    /// as a local of the enclosing function; an arrow that escaped the constructor
572    /// (`iter.return = () => super()`) then finds it in its closure even with the
573    /// constructor nowhere on the call stack.
574    needs_active_func_local: bool,
575    /// Hidden locals of the `with` blocks currently open, innermost last.
576    with_names: Vec<String>,
577    /// Set while a with-guard is being emitted, so the guard's own accesses are not
578    /// wrapped in another guard.
579    emitting_with_guard: bool,
580    self_name: Option<String>,
581    /// Where the function body starts, in source order; see [`Function::body_start`].
582    body_start: (u32, u32),
583    /// Whether the body contains a *direct* `eval(...)` call.
584    ///
585    /// A direct eval sees every binding of the function that called it, including ones
586    /// no other code mentions. It also hands those bindings to any closure it creates,
587    /// which can outlive the function. Both need the bindings to live in cells, so this
588    /// flag makes the function treat all of them as captured.
589    has_direct_eval: bool,
590    /// Whether the parameter list contains a default expression, which is what gives
591    /// the function a second variable environment (see [`PARAM_SCOPE`]).
592    has_parameter_expressions: bool,
593    /// `IsSimpleParameterList`: every parameter is a plain binding identifier.
594    simple_parameter_list: bool,
595    /// Whether the instructions being emitted belong to the parameter list.
596    ///
597    /// References made here must not see the body's `var`s: the body has not run yet,
598    /// and the reference's own model keeps the two scopes apart.
599    in_params: bool,
600    /// Whether an arrow created in this function's parameter list needs the parameter
601    /// scope's `arguments` binding.
602    needs_param_arguments: bool,
603    /// Whether this function was *created* inside a parameter list.
604    ///
605    /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
606    /// arrow too. The name reference is the arrow's, but the scope it must not see
607    /// belongs to the function the arrow was born in.
608    created_in_params: bool,
609    /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
610    ///
611    /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
612    /// final while the body is still being compiled: a named function expression declares
613    /// its own name binding *after* the body, and that binding is exactly what
614    /// `eval("myfunc = 1")` has to find.
615    eval_sites: Vec<EvalSite>,
616    /// Direct `eval` call sites seen so far: where, and the block that was current.
617    pending_eval_sites: Vec<(Span, u64, bool)>,
618    /// Whether this body contains `await`.
619    ///
620    /// For a *module* this decides whether its body is an async function: top-level
621    /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
622    /// to survive to the compiled function rather than being a local of the compiler.
623    has_await: bool,
624    /// The module tables, when this body is a module.
625    ///
626    /// Only the top-level state ever has one: `export` and `import` are top-level
627    /// statements, so nothing nested can add to these tables.
628    module: Option<ModuleMeta>,
629    /// Whether the self-name prologue (`special_object 2` then the store) has been
630    /// emitted for this function.
631    ///
632    /// A *nested* function's lookup declares the binding early (see
633    /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
634    /// prologue is still needed — the binding existing is not the same as it being
635    /// initialised.
636    self_name_initialized: bool,
637    /// Whether the code emitted so far leaves the program's result on the stack.
638    /// The reference tracks this for the hidden `<ret>` local of an eval script.
639    leaves_value: bool,
640    /// Statement nesting depth, used to tell top-level statements apart.
641    stmt_depth: u32,
642    /// Function declarations waiting to be instantiated at scope entry, as
643    /// (target slot, constant pool index). The reference emits these from
644    /// `instantiate_hoisted_definitions` rather than at the statement, because a
645    /// declaration is visible before it is reached.
646    hoisted: Vec<(u64, HoistTarget, u32)>,
647    /// Function declarations whose bodies are compiled only once the enclosing scope
648    /// has finished hoisting, as (owning block, declaration).
649    ///
650    /// Compiling a body at the declaration makes the result depend on source order: in
651    /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
652    /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
653    /// names first and the bodies second is what removes that dependence.
654    deferred_funcs: Vec<(u64, Box<ast::Function>)>,
655    /// The source position of the node being compiled. Every instruction emitted
656    /// takes it, which is how the position table that feeds stack traces is built.
657    cur_pos: Option<Position>,
658    /// One position per entry in `insns`, index-aligned.
659    insn_pos: Vec<Option<Position>>,
660}
661
662/// Where a hoisted function declaration is stored.
663#[derive(Debug, Clone)]
664enum HoistTarget {
665    Arg(u32),
666    Loc(u32),
667    /// A global, which the resolver looks up by name.
668    Global(String),
669}
670
671impl FnState {
672    /// Whether this function suspends: a generator or an async function.
673    ///
674    /// A suspending function's `return` is a `return_async` and its body starts with an
675    /// `initial_yield`, so almost every statement that touches control flow asks this.
676    fn is_suspending(&self) -> bool {
677        self.kind.is_generator() || self.kind.is_async()
678    }
679
680    fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
681        FnState {
682            span: None,
683            name: name.into(),
684            kind,
685            strict: false,
686            args: Vec::new(),
687            vars: Vec::new(),
688            closure_vars: Vec::new(),
689            cpool: Vec::new(),
690            atoms: Vec::new(),
691            blocks: Vec::new(),
692            current_block: 0,
693            created_in_block: NO_PARENT,
694            var_block: Vec::new(),
695            no_value: false,
696            label_since_insn: false,
697            discard_value: false,
698            body_block: 0,
699            block_heads: Vec::new(),
700            jump_targets: Vec::new(),
701            insns: Vec::new(),
702            labels: Vec::new(),
703            var_ref_count: 0,
704            line: 1,
705            column: 1,
706            is_script: false,
707            is_module: false,
708            is_arrow: false,
709            defined_args: 0,
710            param_prologue: Vec::new(),
711            ctor_kind: CtorKind::None,
712            class_ctor_pending: None,
713            needs_this_local: false,
714            needs_arguments_local: false,
715            needs_new_target_local: false,
716            has_this_prologue: false,
717            needs_home_object_local: false,
718            needs_active_func_local: false,
719            with_names: Vec::new(),
720            emitting_with_guard: false,
721            self_name: None,
722            has_direct_eval: false,
723            body_start: (0, 0),
724            has_parameter_expressions: false,
725            simple_parameter_list: true,
726            in_params: false,
727            needs_param_arguments: false,
728            created_in_params: false,
729            eval_sites: Vec::new(),
730            pending_eval_sites: Vec::new(),
731            has_await: false,
732            module: None,
733            self_name_initialized: false,
734            leaves_value: false,
735            stmt_depth: 0,
736            hoisted: Vec::new(),
737            deferred_funcs: Vec::new(),
738            cur_pos: None,
739            insn_pos: Vec::new(),
740        }
741    }
742
743    /// The scope a declaration lands in: a script's top-level declarations are
744    /// globals, everything else gets a slot.
745    /// Whether a binding declared *now* becomes a property of the global object.
746    ///
747    /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
748    /// The `var` case is decided by the keyword rather than by the cursor position:
749    /// `var` is function-scoped, so a `var i` in a `for` head is still the same
750    /// binding as a `var i` in the body, even though the head has its own block.
751    fn declares_globally(&self, def: &VarDef) -> bool {
752        // A module's top-level declarations are *module*-scoped: they live in the module
753        // record, never on the global object. Two modules can both declare `var x`
754        // without seeing each other, which is the whole point.
755        if self.is_module {
756            return false;
757        }
758        self.is_script && (!def.is_lexical || self.current_block == self.body_block)
759    }
760}
761
762/// The compiler's entry point.
763pub struct Compiler {
764    /// The text being compiled, kept so each function can record its own slice for
765    /// `Function.prototype.toString`.
766    source: Option<String>,
767    module: bool,
768    /// Whether the program itself is the body of an `async` function.
769    ///
770    /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
771    /// completion value is wrapped so a returned promise is not adopted.
772    async_body: bool,
773    /// Enclosing functions, outermost first. The last entry is the current one.
774    stack: Vec<FnState>,
775    /// The private names visible at this point, innermost class body last.
776    ///
777    /// A stack rather than a field of `FnState` because a private name is *lexically* scoped
778    /// to the class body: a method, an arrow inside it and a class nested inside that arrow
779    /// all resolve against the same entries, and the parser accepts exactly that set
780    /// (`self.private` in `parser.rs`). `FnState` is per-function, so it would lose the outer
781    /// class's names the moment a method started.
782    private_scopes: Vec<std::collections::HashMap<String, PrivateUse>>,
783}
784
785/// How a use site of a private name compiles.
786///
787/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
788/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
789/// of a setter-only accessor pair.
790#[derive(Clone, Copy, PartialEq, Eq)]
791enum PrivateKind {
792    /// `#x = 1`: an own property keyed by the symbol in the binding.
793    Field,
794    /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
795    Method,
796    /// `get #a() {}`: the binding holds the getter, and a read calls it.
797    Getter,
798    /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
799    /// the same `TypeError` as reading an uninitialised `const`.
800    Setter,
801}
802
803/// What the compiler knows about one `#name` where it is used.
804#[derive(Clone)]
805struct PrivateUse {
806    kind: PrivateKind,
807    /// `#a<set>` when the class defines a setter for this name.
808    ///
809    /// A second binding, not a second field of the first: the reference stores the setter
810    /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
811    setter: Option<String>,
812}
813
814/// The class-scope bindings one class body needs, in declaration order.
815#[derive(Default)]
816struct ClassPlan {
817    /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
818    /// at class entry, in member order.
819    bindings: Vec<String>,
820    /// The private names, for the use sites inside the body.
821    uses: std::collections::HashMap<String, PrivateUse>,
822    /// Computed field keys, by element index, so the emission pass does not have to redo the
823    /// per-half counter that names them.
824    computed: std::collections::HashMap<usize, String>,
825    /// Whether the instance initialiser has to add the brand to `this`.
826    instance_brand: bool,
827    /// Whether the constructor itself has to carry the brand.
828    static_brand: bool,
829}
830
831impl ClassPlan {
832    /// Walk a class body once and decide every class-scope binding it needs.
833    ///
834    /// Order is the reference's: a member's binding is created when the member is parsed, so
835    /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
836    /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
837    /// the disassembly stops matching even when every instruction is right.
838    fn build(class: &Class) -> ClassPlan {
839        let mut plan = ClassPlan::default();
840        let mut instance_keys = 0usize;
841        let mut static_keys = 0usize;
842        for (index, element) in class.elements.iter().enumerate() {
843            match element {
844                ClassElement::Method {
845                    key: PropName::Private(ident),
846                    kind,
847                    is_static,
848                    ..
849                } => {
850                    let name = format!("#{}", ident.name);
851                    let first = !plan.uses.contains_key(&name);
852                    if first {
853                        plan.bindings.push(name.clone());
854                        plan.uses.insert(
855                            name.clone(),
856                            PrivateUse {
857                                kind: match kind {
858                                    MethodKind::Get => PrivateKind::Getter,
859                                    MethodKind::Set => PrivateKind::Setter,
860                                    _ => PrivateKind::Method,
861                                },
862                                setter: None,
863                            },
864                        );
865                    }
866                    match kind {
867                        MethodKind::Set => {
868                            let binding = format!("{name}<set>");
869                            plan.bindings.push(binding.clone());
870                            if let Some(use_) = plan.uses.get_mut(&name) {
871                                use_.setter = Some(binding);
872                            }
873                        }
874                        // A getter is what makes the name readable, so a pair that started
875                        // as a setter becomes readable once the getter arrives.
876                        MethodKind::Get => {
877                            if let Some(use_) = plan.uses.get_mut(&name) {
878                                use_.kind = PrivateKind::Getter;
879                            }
880                        }
881                        _ => {}
882                    }
883                    if *is_static {
884                        plan.static_brand = true;
885                    } else {
886                        plan.instance_brand = true;
887                    }
888                }
889                ClassElement::Method {
890                    key: PropName::Computed(_),
891                    ..
892                } => {}
893                ClassElement::Method { .. } => {}
894                ClassElement::Field {
895                    key: PropName::Private(ident),
896                    ..
897                } => {
898                    let name = format!("#{}", ident.name);
899                    if !plan.uses.contains_key(&name) {
900                        plan.bindings.push(name.clone());
901                        plan.uses.insert(
902                            name,
903                            PrivateUse {
904                                kind: PrivateKind::Field,
905                                setter: None,
906                            },
907                        );
908                    }
909                }
910                ClassElement::Field {
911                    key: PropName::Computed(_),
912                    is_static,
913                    ..
914                } => {
915                    let index_in_half = if *is_static {
916                        static_keys += 1;
917                        static_keys - 1
918                    } else {
919                        instance_keys += 1;
920                        instance_keys - 1
921                    };
922                    let binding = computed_field_binding(index_in_half, *is_static);
923                    plan.bindings.push(binding.clone());
924                    plan.computed.insert(index, binding);
925                }
926                ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
927            }
928        }
929        plan
930    }
931
932    /// How a private name used inside the body compiles, or `None` if no enclosing class
933    /// declares it.
934    fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
935        compiler
936            .private_scopes
937            .iter()
938            .rev()
939            .find_map(|scope| scope.get(name))
940    }
941}
942
943impl Compiler {
944    /// The exact source text of a function, for `Function.prototype.toString`.
945    ///
946    /// §20.2.3.5 requires the *original* text: a function must stringify back to what
947    /// was written, comments and odd spacing included. Slicing the recorded span out of
948    /// the whole source is the only way to get that — rebuilding it from the AST would
949    /// normalise the text, and answering `[native code]` for a script function (which is
950    /// what this engine used to do) makes the result useless for feature detection and
951    /// for libraries that read their own source.
952    ///
953    /// Top-level bodies have no single expression span, so their `source` stays `None`
954    /// and `toString` falls back to the calling convention the spec allows.
955    fn function_source(
956        &self,
957        span: Option<(usize, usize)>,
958        line: u32,
959        column: u32,
960    ) -> Option<String> {
961        let source = self.source.as_ref()?;
962        let span = span?;
963        let bytes = source.as_bytes();
964        let start = span.0;
965        let end = span.1;
966        if start >= bytes.len() || end > bytes.len() || start >= end {
967            let _ = (line, column);
968            return None;
969        }
970        Some(source.get(start..end)?.to_string())
971    }
972}
973
974/// Compile a script.
975pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
976    Compiler::new(false).compile(program)
977}
978
979/// Compile a script, keeping its text so `Function.prototype.toString` can answer with
980/// the original source.
981///
982/// The separate entry point rather than a parameter on [`compile_script`] because the
983/// tests and the disassembler compile from an AST they built themselves and have no
984/// source to give; they keep the `None` behaviour they already relied on.
985pub fn compile_script_with_source(
986    program: &Program,
987    source: &str,
988) -> Result<CompiledFunction, SyntaxError> {
989    let mut compiler = Compiler::new(false);
990    compiler.source = Some(source.to_string());
991    compiler.compile(program)
992}
993
994/// [`compile_script_with_source`] for a module.
995pub fn compile_module_with_source(
996    program: &Program,
997    source: &str,
998) -> Result<CompiledFunction, SyntaxError> {
999    let mut compiler = Compiler::new(true);
1000    compiler.source = Some(source.to_string());
1001    compiler.compile(program)
1002}
1003
1004/// Compile a script whose top level is the body of an `async` function.
1005///
1006/// The body is an ordinary script in every other way — it still reports a completion value
1007/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
1008/// it answers a promise instead of a value. The wrapper is what keeps that promise from
1009/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
1010/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
1011/// documents.
1012pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1013    Compiler::for_suspensible_script().compile(program)
1014}
1015
1016/// Compile a module.
1017pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1018    Compiler::new(true).compile(program)
1019}
1020
1021impl Compiler {
1022    /// Create a compiler.
1023    pub fn new(module: bool) -> Compiler {
1024        Compiler {
1025            source: None,
1026            module,
1027            async_body: false,
1028            stack: Vec::new(),
1029            private_scopes: Vec::new(),
1030        }
1031    }
1032
1033    /// Create a compiler for a script whose top level is an `async` function body.
1034    fn for_suspensible_script() -> Compiler {
1035        Compiler {
1036            source: None,
1037            module: false,
1038            async_body: true,
1039            stack: Vec::new(),
1040            private_scopes: Vec::new(),
1041        }
1042    }
1043
1044    /// Compile a whole program into its top-level function.
1045    pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
1046        let mut state = FnState::new("<eval>", FunctionKind::Normal);
1047        // A module body is *not* a script: it has no completion value, so no hidden
1048        // `<ret>` local and no `put_loc0` before each statement. What it shares with one
1049        // is having no `arguments` of its own and no receiver — see `is_module`.
1050        state.is_script = !self.module;
1051        state.is_module = self.module;
1052        if self.module {
1053            state.module = Some(ModuleMeta::default());
1054        }
1055        state.strict = program.strict || self.module;
1056        state.line = program.span.start.line;
1057        state.column = program.span.start.column;
1058        // Locals are numbered in declaration order; `<ret>` is always slot 0.
1059        //
1060        // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
1061        // slot that only appears in one of the two arrays shifts every later
1062        // binding's block and silently loses the temporal-dead-zone marking for
1063        // the script's own blocks. A function frame has no `<ret>`, which is why
1064        // the misalignment only showed up at the top level.
1065        if !self.module {
1066            state.vars.push(VarDef::var("<ret>"));
1067            state.var_block.push(FUNCTION_SCOPE);
1068        }
1069        self.stack.push(state);
1070        // The body is its own scope, keyed by the position of the program.
1071        // The script body needs a key no statement can produce. Statement keys are
1072        // source offsets, and the program's own start offset is `0` — which is also
1073        // the offset of the first statement, so a top-level `{ let x }` or
1074        // `for (let i …)` used to share the body's block and lose its scope.
1075        let body_key = SCRIPT_BODY;
1076        self.push_block(body_key, NO_PARENT);
1077        self.state().body_block = body_key;
1078        // A module body opens with a re-entry guard. The host evaluates a module exactly
1079        // once, so the guard never fires in practice — but the reference emits it, and a
1080        // module function called a second time (through `eval` of its own source, say)
1081        // must not run its body again.
1082        let module_guard = self.module.then(|| self.new_label());
1083        if let Some(body) = module_guard {
1084            // The guard wraps the *hoisting* too: a second evaluation of the same module
1085            // body must not even re-create its function declarations.
1086            self.emit(Opcode::PushThis, &[]);
1087            self.emit_jump(Opcode::IfFalse, body, &[]);
1088        }
1089        self.hoist(&program.body, body_key)?;
1090        // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
1091        // come before the guard's `return_undef`: the reference's jump target sits past
1092        // both, and a second evaluation therefore re-creates nothing.
1093        self.emit_scope_enter(body_key);
1094        if let Some(body) = module_guard {
1095            self.emit(Opcode::ReturnUndef, &[]);
1096            self.place_label(body);
1097        }
1098        // Through `stmts` rather than the loop, so a `using` region at the top level of an
1099        // eval'd body or a module gets its disposal epilogue like any other block.
1100        self.stmts(&program.body)?;
1101        if self.module {
1102            // A module has no completion value; its body simply ends.
1103            self.emit(Opcode::Undefined, &[]);
1104            self.emit(Opcode::ReturnAsync, &[]);
1105            // Top-level `await` makes the body an async function, so the host runs it as
1106            // a coroutine and waits. Without this the `await` opcode would suspend in a
1107            // body that nothing knows how to resume — which is what "a generator body ran
1108            // as an ordinary call" was reporting.
1109            if self.cur().has_await {
1110                self.state().kind = FunctionKind::Async;
1111            }
1112        } else if self.async_body {
1113            // An async body reports its completion value the same way, but through an
1114            // object: the function answers a promise, and resolving that promise *with*
1115            // the completion value would adopt a promise completion instead of reporting
1116            // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
1117            // resolve to `{value: <promise>}` rather than to `7`.
1118            //
1119            // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
1120            // value in an object so that promises can be safely returned").
1121            self.emit(Opcode::Object, &[]);
1122            self.emit(Opcode::Dup, &[]);
1123            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1124            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
1125            self.emit(Opcode::Return, &[]);
1126            self.state().kind = FunctionKind::Async;
1127        } else {
1128            // The program's value is whatever the last expression statement stored in
1129            // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
1130            // case into a single `set_loc0`.
1131            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1132            self.emit(Opcode::Return, &[]);
1133        }
1134        Ok(self.finish_current())
1135    }
1136
1137    // -- emitting ----------------------------------------------------------
1138
1139    fn state(&mut self) -> &mut FnState {
1140        self.stack.last_mut().expect("a function is being compiled")
1141    }
1142
1143    fn cur(&self) -> &FnState {
1144        self.stack.last().expect("a function is being compiled")
1145    }
1146
1147    fn emit(&mut self, op: Opcode, operands: &[Op]) {
1148        self.state().label_since_insn = false;
1149        let pos = self.cur().cur_pos;
1150        self.state().insns.push(Insn::Fixed {
1151            op,
1152            operands: operands.to_vec(),
1153        });
1154        self.state().insn_pos.push(pos);
1155    }
1156
1157    /// Reset the script's hidden return value to `undefined`.
1158    ///
1159    /// Called at the start of every statement that does not itself produce the
1160    /// program's value, which is how the reference keeps `if`/loop results from
1161    /// leaking into an eval result.
1162    fn reset_value(&mut self) {
1163        if !self.cur().is_script {
1164            return;
1165        }
1166        self.emit(Opcode::Undefined, &[]);
1167        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1168        self.state().leaves_value = false;
1169    }
1170
1171    /// Whether `name` is a local or argument slot rather than a global.
1172    fn is_slot(&self, name: &str) -> bool {
1173        self.cur().vars.iter().any(|v| v.name == name)
1174            || self.cur().args.iter().any(|a| a.name == name)
1175    }
1176
1177    /// `with (object) body`
1178    ///
1179    /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
1180    /// what makes the object reachable from a closure created inside the block, and it
1181    /// is also what lets an `eval` find it: the runtime collects the active `With`
1182    /// locals of every frame and resolves names against them before the realm.
1183    ///
1184    /// Inside the block every name reference is spelled as "look in the with objects
1185    /// first", innermost outwards, and falls through to the ordinary access. The test is
1186    /// `in`, which is `HasProperty` — the same question the spec's Object Environment
1187    /// Record asks.
1188    fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
1189        let name = self.next_with_name();
1190        // The object expression is evaluated *outside* the scope it introduces, so no
1191        // wrapper may be emitted for the names it mentions.
1192        let saved = std::mem::take(&mut self.state().with_names);
1193        self.expr(object)?;
1194        self.state().with_names = saved;
1195        self.emit(Opcode::ToObject, &[]);
1196        self.declare_hidden_local(&name, VarKind::With);
1197        // Pushed before the store so the store itself is not guarded by an *outer*
1198        // `with` — the object being stored is the new one, not something to look up.
1199        self.state().with_names.push(name.clone());
1200        self.emit_var(VarAction::Put, &name);
1201        let result = self.stmt(body);
1202        self.state().with_names.pop();
1203        result
1204    }
1205
1206    /// A hidden-local name for one `with` block, distinct from every enclosing one.
1207    fn next_with_name(&self) -> String {
1208        let depth = self.cur().with_names.len();
1209        if depth == 0 {
1210            "<with>".to_string()
1211        } else {
1212            format!("<with{depth}>")
1213        }
1214    }
1215
1216    /// Declare a hidden local that must stay a *local* even in a script.
1217    ///
1218    /// A script's `var` is a property of the global object, but the `with` object is not
1219    /// part of the source program's name space at all — it only exists for the compiler
1220    /// and the runtime — so it goes straight into the frame's slot list.
1221    fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
1222        let state = self.state();
1223        if state.vars.iter().any(|v| v.name == name) {
1224            return;
1225        }
1226        state.var_block.push(FUNCTION_SCOPE);
1227        state.vars.push(VarDef {
1228            kind,
1229            ..VarDef::var(name)
1230        });
1231    }
1232
1233    /// Emit a name access, guarded by every active `with` object.
1234    ///
1235    /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
1236    /// the read itself; the outer guards and the plain access are what the `if_false`
1237    /// jumps to, so the innermost object wins.
1238    fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
1239        let names = self.cur().with_names.clone();
1240        let done = self.new_label();
1241        let mut starts = Vec::new();
1242        // Innermost object first: the last `with` opened is the one that shadows the
1243        // others, so its guard has to be the first chance to satisfy the name.
1244        for with_name in names.iter().rev() {
1245            let next = self.new_label();
1246            // `in` takes the key then the object.
1247            self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1248            self.emit_var(VarAction::Get, with_name);
1249            self.emit(Opcode::In, &[]);
1250            self.emit_jump(Opcode::IfFalse, next, &[]);
1251            starts.push(next);
1252            match action {
1253                // A store keeps the value under the receiver, which is where
1254                // `put_field` expects it.
1255                VarAction::Put | VarAction::PutInit => {
1256                    self.emit_var(VarAction::Get, with_name);
1257                    self.emit(Opcode::Swap, &[]);
1258                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(name))]);
1259                }
1260                _ => {
1261                    self.emit_var(VarAction::Get, with_name);
1262                    self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1263                    self.emit(Opcode::GetArrayEl, &[]);
1264                }
1265            }
1266            self.emit_jump(Opcode::Goto, done, &[]);
1267            self.place_label(next);
1268        }
1269        self.emit_var(action, name);
1270        self.place_label(done);
1271    }
1272
1273    fn emit_var(&mut self, action: VarAction, name: &str) {
1274        // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
1275        // stores and keeps the value in one instruction. The reference does this
1276        // in a post-pass; folding it at emit time keeps instruction indices
1277        // stable, which matters because labels are recorded as indices.
1278        //
1279        // Only slots have a `set_` form: a global is stored with `put_var` and
1280        // read with `get_var`, and the reference does not fold those.
1281        //
1282        // A label between the two cancels the fold. `set_x v` leaves the value on
1283        // the stack, which is only equivalent when the read immediately follows the
1284        // store; when a jump target sits in between, the store must *consume* the
1285        // value and the read must fetch it afresh. A loop head is exactly that
1286        // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
1287        // condition re-reads it — and folding across the label would make the
1288        // condition compare whatever the previous iteration left on the stack.
1289        if action == VarAction::Get {
1290            let is_slot = self.is_slot(name);
1291            let at_label = std::mem::take(&mut self.state().label_since_insn);
1292            //
1293            // `arguments` is excluded because the reference treats it as a special
1294            // binding: it is initialised once and read many times, and folding its
1295            // initialisation into a `set_` would leave the object on the stack where
1296            // the reference leaves nothing.
1297            if is_slot
1298                && name != "arguments"
1299                && !at_label
1300                && let Some(Insn::Var {
1301                    action: previous,
1302                    name: previous_name,
1303                    ..
1304                }) = self.state().insns.last_mut()
1305                && *previous == VarAction::Put
1306                && previous_name == name
1307            {
1308                *previous = VarAction::Set;
1309                return;
1310            }
1311        }
1312        // Inside a `with`, every name lookup consults the with objects first. The
1313        // hidden `<with…>` locals themselves are exempt, or the guard would recurse.
1314        let guarded = !self.cur().with_names.is_empty()
1315            && !self.cur().with_names.iter().any(|hidden| hidden == name)
1316            && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1317            && !self.state().emitting_with_guard;
1318        if guarded {
1319            self.state().emitting_with_guard = true;
1320            self.emit_with_guarded(action, name);
1321            self.state().emitting_with_guard = false;
1322            return;
1323        }
1324        let block = self.cur().current_block;
1325        self.state().label_since_insn = false;
1326        let pos = self.cur().cur_pos;
1327        let in_params = self.cur().in_params;
1328        self.state().insns.push(Insn::Var {
1329            action,
1330            name: name.to_string(),
1331            block,
1332            in_params,
1333        });
1334        self.state().insn_pos.push(pos);
1335    }
1336
1337    fn new_label(&mut self) -> Label {
1338        let state = self.state();
1339        state.labels.push(None);
1340        Label(state.labels.len() as u32 - 1)
1341    }
1342
1343    fn place_label(&mut self, label: Label) {
1344        let index = self.cur().insns.len();
1345        self.state().label_since_insn = true;
1346        self.state().labels[label.0 as usize] = Some(index);
1347    }
1348
1349    fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1350        let mut operands = vec![Op::Label(label)];
1351        operands.extend_from_slice(extra);
1352        self.emit(op, &operands);
1353    }
1354
1355    // -- scopes ------------------------------------------------------------
1356
1357    /// Start a new lexical scope inside `parent`.
1358    fn push_block(&mut self, key: u64, parent: u64) {
1359        let state = self.state();
1360        if !state.blocks.iter().any(|b| b.key == key) {
1361            state.blocks.push(Block { key, parent });
1362        }
1363        state.current_block = key;
1364    }
1365
1366    /// Emit the code that runs when a lexical scope is entered.
1367    ///
1368    /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1369    /// so entering its block marks it uninitialised. Hoisted function
1370    /// declarations are created here instead, which is why a call before the
1371    /// declaration still works.
1372    ///
1373    /// The order is not obvious: bindings are emitted in *reverse* declaration
1374    /// order, because the reference walks its scope chain, which is built by
1375    /// prepending.
1376    fn emit_scope_enter(&mut self, block: u64) {
1377        // Only *this* scope's hoisted declarations are consumed here; the rest stay in the
1378        // list for the scope that owns them. `std::mem::take` used to empty the whole list,
1379        // so entering an outer scope threw away every nested block's function
1380        // declarations: `function h(){ { function k(){} } return k; }` answered
1381        // `undefined`, and `{ function g(){} }` was `undefined` even *inside* the block.
1382        // That is one Annex B rule the engine otherwise implements (a sloppy-mode function
1383        // in a block is also a `var` of the enclosing function), and it is what makes the
1384        // `for (const ctor of ctors) { function f(){} … }` shape in test262 work.
1385        let mut hoisted = std::mem::take(&mut self.state().hoisted);
1386        let mut rest = Vec::with_capacity(hoisted.len());
1387        let mut mine: Vec<(HoistTarget, u32)> = Vec::new();
1388        for (owner, target, pool_index) in hoisted.drain(..) {
1389            if owner == block {
1390                mine.push((target, pool_index));
1391            } else {
1392                rest.push((owner, target, pool_index));
1393            }
1394        }
1395        self.state().hoisted = rest;
1396        mine.sort_by_key(|(target, _)| match target {
1397            HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1398            HoistTarget::Global(_) => u32::MAX,
1399        });
1400        for (target, pool_index) in mine {
1401            self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1402            match target {
1403                HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1404                HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1405                HoistTarget::Global(name) => {
1406                    // A global binding lives in a reference cell, so the store
1407                    // goes through `put_var_ref` while reads use `get_var`.
1408                    let block = self.cur().current_block;
1409                    let pos = self.cur().cur_pos;
1410                    let in_params = self.cur().in_params;
1411                    self.state().insns.push(Insn::Var {
1412                        action: VarAction::PutRef,
1413                        name,
1414                        block,
1415                        in_params,
1416                    });
1417                    self.state().insn_pos.push(pos);
1418                }
1419            }
1420        }
1421        for index in self.block_vars_reversed(block) {
1422            self.emit(
1423                Opcode::SetLocUninitialized,
1424                &[Op::Slot(Slot::Loc(index as u32))],
1425            );
1426        }
1427    }
1428
1429    /// Emit the code that runs when a lexical scope is exited.
1430    ///
1431    /// A captured binding has to be closed: detaching its reference cell freezes
1432    /// the value the binding had when the block ended, which is what a closure
1433    /// created inside the block must keep seeing.
1434    fn emit_scope_leave(&mut self, block: u64) {
1435        for index in self.block_vars_reversed(block) {
1436            if self.cur().vars[index].is_captured {
1437                self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1438            }
1439        }
1440    }
1441
1442    /// Locals declared in `block`, in reverse declaration order.
1443    fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1444        let state = self.cur();
1445        let mut out: Vec<usize> = (0..state.vars.len())
1446            .filter(|index| {
1447                state.var_block.get(*index).copied() == Some(block)
1448                    && state.vars[*index].is_lexical
1449                    // A derived constructor's `this` is lexical but is not initialised by
1450                    // entering the scope: `check_ctor` proves it, so its dead-zone marker
1451                    // was emitted with the constructor's own prologue.
1452                    && state.vars[*index].name != "this"
1453            })
1454            .collect();
1455        out.reverse();
1456        out
1457    }
1458
1459    /// Declare a local, even at the top level of a script.
1460    ///
1461    /// A `catch` parameter is always a local: the reference puts it in the
1462    /// function's own variable list (`1: catch e`), never in the global object,
1463    /// because it only exists while the handler runs.
1464    fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1465        let state = self.state();
1466        let index = state.vars.len() as u32;
1467        // A `catch` parameter belongs to a scope even though it is not lexical: the
1468        // runtime instantiates it per handler entry, but it never sits in the
1469        // temporal dead zone.
1470        let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1471            state.current_block
1472        } else {
1473            0
1474        };
1475        state.var_block.push(block);
1476        state.vars.push(def);
1477        index
1478    }
1479
1480    fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1481        if self.cur().is_module
1482            && self.cur().current_block == self.cur().body_block
1483            && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1484        {
1485            // Only the body's own block: a `let` inside a module-level `{}` is still an
1486            // ordinary local of that block, not a module variable.
1487            //
1488            // A `using` binding is excluded on purpose, and the reference excludes it in
1489            // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1490            // "'using' variables are currently not exported in modules"): a module-level
1491            // `using` is an ordinary *local* of the module body function, not a module
1492            // cell. Two things follow, and both are what the reference does — `export {a}`
1493            // of a `using` binding is "exported variable 'a' does not exist", and
1494            // disposal works, because the disposal epilogue addresses locals by slot.
1495            //
1496            // The hidden dispose-method variable is excluded for a stronger reason: it is
1497            // *always* a local (`add_scope_var` in the reference), and it must sit
1498            // immediately after its value so `using_dispose` can find it at `slot + 1`.
1499            return self.declare_module(name, &def);
1500        }
1501        if self.cur().declares_globally(&def) {
1502            self.declare_global(name, &def);
1503            return 0;
1504        }
1505        let state = self.state();
1506        let index = state.vars.len() as u32;
1507        let block = if def.is_lexical {
1508            state.current_block
1509        } else {
1510            0
1511        };
1512        state.var_block.push(block);
1513        state.vars.push(def);
1514        index
1515    }
1516
1517    /// Declare a `using` binding and its cached dispose method, returning both slots.
1518    ///
1519    /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1520    /// `(value, value + 1)` — the reference does the same and documents the constraint.
1521    fn declare_using(&mut self, name: &str) -> (u32, u32) {
1522        let mut def = VarDef::lexical(name);
1523        def.kind = VarKind::Using;
1524        let value = self.declare(name, def);
1525        let mut method = VarDef::lexical(using_method_name(name));
1526        method.kind = VarKind::UsingMethod;
1527        let method_slot = self.declare(&using_method_name(name), method);
1528        (value, method_slot)
1529    }
1530
1531    /// The slot a `using` binding's dispose method lives in.
1532    fn using_method_slot(&self, name: &str) -> Option<u32> {
1533        let hidden = using_method_name(name);
1534        self.cur()
1535            .vars
1536            .iter()
1537            .position(|var| var.name == hidden)
1538            .map(|index| index as u32)
1539    }
1540
1541    // -- statements --------------------------------------------------------
1542
1543    fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1544        self.stmt_labelled(stmt, &[])
1545    }
1546
1547    /// Compile a statement that a chain of labels names.
1548    ///
1549    /// Only a loop consumes `labels`; every other statement ignores them (the
1550    /// parser has already rejected a label on a statement that cannot use it).
1551    fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1552        // Only a *top-level* expression statement supplies the program's value.
1553        let saved = self.cur().leaves_value;
1554        self.state().leaves_value =
1555            matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1556        self.state().stmt_depth += 1;
1557        let result = self.stmt_inner(stmt, labels);
1558        self.state().stmt_depth -= 1;
1559        // A nested statement never contributes the program's value, so the flag
1560        // the wrapper set above is what survives.
1561        let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1562        self.state().leaves_value = produced;
1563        let _ = saved;
1564        result
1565    }
1566
1567    fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1568        match &stmt.kind {
1569            StmtKind::Empty | StmtKind::Debugger => {}
1570            StmtKind::Expr(expr) => {
1571                // The statement's first token is a position the reference records: an
1572                // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1573                // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1574                // is why an error from a construct with no position of its own (`[...it]`
1575                // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1576                let saved = self.cur().cur_pos;
1577                self.state().cur_pos = Some(expr.span.start);
1578                // An expression statement's value is thrown away — except in a
1579                // script, where it becomes the program's result. `assign` reads this
1580                // and clears it, so a nested assignment still produces a value.
1581                self.state().discard_value = !self.cur().is_script;
1582                let result = self.expr(expr);
1583                self.state().discard_value = false;
1584                result?;
1585                if std::mem::take(&mut self.state().no_value) {
1586                    // A store whose value was discarded left nothing to drop.
1587                } else if self.cur().is_script {
1588                    // The program's value lands in the hidden `<ret>` local.
1589                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1590                } else {
1591                    self.emit(Opcode::Drop, &[]);
1592                }
1593                // Restored last: the trailing `drop` is part of the statement, and in the
1594                // reference it simply inherits whatever the expression last recorded.
1595                self.state().cur_pos = saved;
1596            }
1597            StmtKind::Block(body) => {
1598                // The block's declarations were hoisted with its enclosing
1599                // statement list, so there is nothing left to declare here.
1600                let key = stmt.span.start.offset as u64;
1601                let parent = self.cur().current_block;
1602                self.push_block(key, parent);
1603                self.emit_scope_enter(key);
1604                // A block is where a `using` region lives, so its statements have to go
1605                // through `stmts`: that is what emits the disposal epilogue.
1606                self.stmts(body)?;
1607                self.emit_scope_leave(key);
1608                self.state().current_block = parent;
1609            }
1610            StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1611            // A function declaration was already instantiated when its scope was
1612            // entered, so the statement itself emits nothing.
1613            StmtKind::FuncDecl(_) => {}
1614            StmtKind::If { test, cons, alt } => {
1615                self.reset_value();
1616                let else_label = self.new_label();
1617                let end_label = self.new_label();
1618                self.expr(test)?;
1619                self.emit_jump(Opcode::IfFalse, else_label, &[]);
1620                self.stmt(cons)?;
1621                if alt.is_some() {
1622                    self.emit_jump(Opcode::Goto, end_label, &[]);
1623                }
1624                self.place_label(else_label);
1625                if let Some(alt) = alt {
1626                    self.stmt(alt)?;
1627                    self.place_label(end_label);
1628                }
1629            }
1630            StmtKind::While { test, body } => {
1631                self.reset_value();
1632                let top = self.new_label();
1633                let end = self.new_label();
1634                self.place_label(top);
1635                self.expr(test)?;
1636                // The condition's false branch and `break` share one target,
1637                // which is why a `while` loop needs only one end label.
1638                self.emit_jump(Opcode::IfFalse, end, &[]);
1639                self.loop_body(body, labels, top, end)?;
1640                self.emit_jump(Opcode::Goto, top, &[]);
1641                self.place_label(end);
1642            }
1643            StmtKind::DoWhile { body, test } => {
1644                self.reset_value();
1645                let top = self.new_label();
1646                let cont = self.new_label();
1647                let end = self.new_label();
1648                self.place_label(top);
1649                // `continue` in a `do…while` runs the test, so it lands on `cont`
1650                // rather than on the loop head.
1651                self.loop_body(body, labels, cont, end)?;
1652                self.place_label(cont);
1653                self.expr(test)?;
1654                self.emit_jump(Opcode::IfTrue, top, &[]);
1655                self.place_label(end);
1656            }
1657            StmtKind::For {
1658                init,
1659                test,
1660                update,
1661                body,
1662            } => {
1663                self.reset_value();
1664                let for_key = stmt.span.start.offset as u64;
1665                let for_parent = self.cur().current_block;
1666                self.push_block(for_key, for_parent);
1667                self.emit_scope_enter(for_key);
1668                if let Some(init) = init {
1669                    match init {
1670                        ForInit::VarDecl(decl) => {
1671                            self.var_decl(decl)?;
1672                        }
1673                        ForInit::Expr(expr) => {
1674                            // The head's value is discarded. Saying so lets an
1675                            // assignment store with `put` instead of `dup`+`put`, which
1676                            // is what the reference emits — and the difference matters:
1677                            // a `dup`/`drop` pair around the store gives the peephole a
1678                            // chance to fold the store into the *condition's* read.
1679                            self.state().discard_value = true;
1680                            let result = self.expr(expr);
1681                            self.state().discard_value = false;
1682                            result?;
1683                            if !std::mem::take(&mut self.state().no_value) {
1684                                self.emit(Opcode::Drop, &[]);
1685                            }
1686                        }
1687                    }
1688                }
1689                // A `let`/`const` in the head gets a *fresh binding per iteration*,
1690                // so a closure made in the body captures that iteration's value
1691                // instead of sharing one. The reference expresses this with
1692                // `close_loc`, which swaps in a new reference cell holding the
1693                // current value; the three points below are the ones it uses — after
1694                // the initialiser, before the update, and after the loop.
1695                let loop_bindings = match init {
1696                    Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
1697                        let mut names: Vec<String> = Vec::new();
1698                        for declarator in &decl.declarators {
1699                            let mut idents = Vec::new();
1700                            declarator.target.bound_names(&mut idents);
1701                            names.extend(idents.into_iter().map(|ident| ident.name));
1702                        }
1703                        names
1704                    }
1705                    _ => Vec::new(),
1706                };
1707                // The reference also closes right after the initialiser, so the first
1708                // iteration's closures get their own cell rather than sharing the one
1709                // the initialiser wrote into.
1710                for name in &loop_bindings {
1711                    let pos = self.cur().cur_pos;
1712                    self.state().insns.push(Insn::CloseCaptured {
1713                        name: name.clone(),
1714                        block: for_key,
1715                    });
1716                    self.state().insn_pos.push(pos);
1717                }
1718                let top = self.new_label();
1719                let cont = self.new_label();
1720                let end = self.new_label();
1721                self.place_label(top);
1722                if let Some(test) = test {
1723                    self.expr(test)?;
1724                    self.emit_jump(Opcode::IfFalse, end, &[]);
1725                }
1726                // `continue` runs the update expression first, so it lands on
1727                // `cont`, which sits just before the update.
1728                self.loop_body(body, labels, cont, end)?;
1729                self.place_label(cont);
1730                // Each iteration ends with a fresh cell, so the closures the body just
1731                // created keep the cell they captured and the update writes to a new
1732                // one. Without this every closure in the loop shares one binding.
1733                let binding_block = for_key;
1734                for name in &loop_bindings {
1735                    let pos = self.cur().cur_pos;
1736                    self.state().insns.push(Insn::CloseCaptured {
1737                        name: name.clone(),
1738                        block: binding_block,
1739                    });
1740                    self.state().insn_pos.push(pos);
1741                }
1742                if let Some(update) = update {
1743                    self.state().discard_value = true;
1744                    let result = self.expr(update);
1745                    self.state().discard_value = false;
1746                    result?;
1747                    if !std::mem::take(&mut self.state().no_value) {
1748                        self.emit(Opcode::Drop, &[]);
1749                    }
1750                }
1751                self.emit_jump(Opcode::Goto, top, &[]);
1752                self.place_label(end);
1753                self.emit_scope_leave(for_key);
1754                self.state().current_block = for_parent;
1755            }
1756            StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1757            StmtKind::Throw(expr) => {
1758                self.expr(expr)?;
1759                self.emit(Opcode::Throw, &[]);
1760            }
1761            StmtKind::Break(_) | StmtKind::Continue(_) => {
1762                // Labels and loops are wired up in a later milestone; a bare
1763                // break/continue jumps to the innermost enclosing target, which
1764                // the loop helpers register.
1765                self.control_transfer(stmt)?;
1766            }
1767            StmtKind::Labeled { label, body } => {
1768                self.labeled(label, body, stmt)?;
1769            }
1770            StmtKind::Switch {
1771                discriminant,
1772                cases,
1773            } => {
1774                self.switch(discriminant, cases, stmt)?;
1775            }
1776            StmtKind::Try {
1777                block,
1778                handler,
1779                finalizer,
1780            } => {
1781                self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
1782            }
1783            StmtKind::ForIn { left, right, body } => {
1784                self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
1785            }
1786            StmtKind::ForOf {
1787                left,
1788                right,
1789                body,
1790                is_await,
1791            } => {
1792                let kind = if *is_await {
1793                    ForLoopKind::AwaitOf
1794                } else {
1795                    ForLoopKind::Of
1796                };
1797                self.for_in_of(stmt, left, right, body, kind, labels)?;
1798            }
1799            StmtKind::With { object, body } => self.with_stmt(object, body)?,
1800            StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
1801            // `import` emits nothing: hoisting already bound its names, and the host
1802            // fills their cells before the body runs.
1803            StmtKind::Import(_) => {}
1804            StmtKind::Export(decl) => self.export_stmt(decl)?,
1805        }
1806        Ok(())
1807    }
1808
1809    /// Compile `return`, running every enclosing finalizer on the way out.
1810    ///
1811    /// `nip_catch` is what makes this possible: it discards everything on the stack
1812    /// down to and including the `catch` offset while keeping the return value on
1813    /// top, so the frame the finalizer sees has the same shape as on the normal
1814    /// path.
1815    fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
1816        let mut has_value = value.is_some();
1817        if let Some(expr) = value {
1818            // `return f(x)` is a tail call *only* when nothing has to happen to the
1819            // value afterwards. A `finally` or an open iterator in scope forces the
1820            // normal path, because the cleanup has to run after the call returns —
1821            // which is exactly what a tail call refuses to do.
1822            let plain = self
1823                .cur()
1824                .jump_targets
1825                .iter()
1826                .all(|target| target.finally_label.is_none() && !target.has_iterator);
1827            if plain && self.expr_if_tail_call(expr)? {
1828                return Ok(());
1829            }
1830            self.expr(expr)?;
1831        }
1832        // `return v` in an *async generator* awaits `v` before anything else happens —
1833        // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
1834        // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
1835        // exactly that reason ("the await must be done before handling the finally in case
1836        // it raises an exception").
1837        if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
1838            self.emit(Opcode::Await, &[]);
1839            self.state().has_await = true;
1840        }
1841        has_value = self.emit_unwind_for_return(has_value);
1842        // A generator or async function does not return to its caller: it either
1843        // finishes, and the value becomes `{value, done: true}`, or it suspends.
1844        // `return_async` is the "finished" half, and it reads the value off the stack
1845        // rather than carrying it, which is what the resume machinery expects.
1846        if self.cur().is_suspending() {
1847            if !has_value {
1848                self.emit(Opcode::Undefined, &[]);
1849            }
1850            self.emit(Opcode::ReturnAsync, &[]);
1851            return Ok(());
1852        }
1853        if has_value {
1854            self.emit(Opcode::Return, &[]);
1855        } else {
1856            self.emit(Opcode::ReturnUndef, &[]);
1857        }
1858        Ok(())
1859    }
1860
1861    /// Close an iterator: the reference's `emit_iterator_close`.
1862    ///
1863    /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
1864    /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
1865    /// sequence, and three details in it are load-bearing:
1866    ///
1867    /// * the iterator object is compared against `undefined` first, because a loop that
1868    ///   ran to completion clears that slot rather than closing an exhausted iterator;
1869    /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
1870    /// * `preserve_completion` keeps whatever was underneath (the return value of the
1871    ///   function being left), which is why one branch ends on `nip` and the other on `drop`.
1872    fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
1873        if !is_async {
1874            if preserve_completion {
1875                self.emit(Opcode::Rot3r, &[]);
1876                self.emit(Opcode::Undefined, &[]);
1877            }
1878            self.emit(Opcode::IteratorClose, &[]);
1879            return;
1880        }
1881        if preserve_completion {
1882            // `iter next completion -> completion iter`
1883            self.emit(Opcode::Nip, &[]);
1884            self.emit(Opcode::Swap, &[]);
1885        } else {
1886            // `iter next catch_offset -> iter`
1887            self.emit(Opcode::Drop, &[]);
1888            self.emit(Opcode::Drop, &[]);
1889        }
1890        let done = self.new_label();
1891        let no_return = self.new_label();
1892        self.emit(Opcode::Dup, &[]);
1893        self.emit(Opcode::IsUndefined, &[]);
1894        self.emit_jump(Opcode::IfTrue, done, &[]);
1895        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
1896        self.emit(Opcode::Dup, &[]);
1897        self.emit(Opcode::IsUndefinedOrNull, &[]);
1898        self.emit_jump(Opcode::IfTrue, no_return, &[]);
1899        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
1900        self.emit(Opcode::Await, &[]);
1901        self.state().has_await = true;
1902        self.emit_jump(Opcode::Goto, done, &[]);
1903        self.place_label(no_return);
1904        self.emit(Opcode::Drop, &[]);
1905        self.place_label(done);
1906        self.emit(Opcode::Drop, &[]);
1907    }
1908
1909    /// Emit the finalizer/iterator cleanup for leaving the current position with a
1910    /// return, and report whether a value is now on the stack for it to carry.
1911    ///
1912    /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
1913    /// enclosing `finally` at once, and the two used to be separate — the `yield` path
1914    /// simply emitted `return_async`, so `it.return()` ended the generator without ever
1915    /// running `finally` blocks the body was sitting inside.
1916    fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
1917        let targets = self.cur().jump_targets.clone();
1918        for target in targets.iter().rev() {
1919            if target.finally_label.is_none() && !target.has_iterator {
1920                continue;
1921            }
1922            if !has_value {
1923                // The cleanup expects a value to pass through; with nothing to
1924                // return, `undefined` stands in.
1925                self.emit(Opcode::Undefined, &[]);
1926                has_value = true;
1927            }
1928            self.emit(Opcode::NipCatch, &[]);
1929            if target.has_iterator {
1930                // Rewind to the loop's own slots and hand the close a dummy catch offset:
1931                // the loop is being abandoned, so there is nothing left to catch.
1932                self.emit_iterator_close(target.is_async_iterator, true);
1933            } else if let Some(finally) = target.finally_label {
1934                self.emit_jump(Opcode::Gosub, finally, &[]);
1935            }
1936        }
1937        has_value
1938    }
1939
1940    /// Compile a statement list, stopping at the first statement that cannot
1941    /// fall through.
1942    fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
1943        for (index, stmt) in body.iter().enumerate() {
1944            // A `using` declaration is not just a binding: everything after it, to the end
1945            // of the list, runs inside its disposal region. Compiling the rest of the list
1946            // recursively is what gives nested regions their innermost-first order.
1947            if Self::using_declaration(stmt).is_some() {
1948                return self.using_region(stmt, &body[index + 1..]);
1949            }
1950            self.stmt(stmt)?;
1951            if Self::terminates(stmt) {
1952                break;
1953            }
1954        }
1955        Ok(())
1956    }
1957
1958    /// The declaration a `using` statement carries, if it is one.
1959    fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
1960        match &stmt.kind {
1961            StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
1962            _ => None,
1963        }
1964    }
1965
1966    /// Compile `decl` and then the rest of its block, disposing when the block ends.
1967    ///
1968    /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
1969    /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
1970    /// exception — and this engine already funnels all of those through `catch` plus
1971    /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
1972    /// `return` and `break` dispose without knowing anything about `using`.
1973    ///
1974    /// ```text
1975    ///   <declaration>              value -> x, method -> x+1
1976    ///   catch CATCH                <- an exception in the rest lands here
1977    /// REST:
1978    ///   <the rest of the block>
1979    ///   drop                       <- the catch offset, on the fall-through path
1980    ///   undefined; gosub DISPOSE; drop
1981    ///   goto END
1982    /// CATCH:
1983    ///   using_dispose x            <- merges the failure into the pending exception
1984    ///   throw
1985    /// DISPOSE:
1986    ///   using_dispose_init
1987    ///   using_dispose x
1988    ///   using_dispose_end          <- rethrows if a dispose failed
1989    ///   ret
1990    /// END:
1991    /// ```
1992    fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
1993        let Some(decl) = Self::using_declaration(stmt) else {
1994            unreachable!("using_region is only called for a using declaration");
1995        };
1996        // `using` binds exactly one name and has no pattern form, which the parser
1997        // enforces; the region still has to know *which* slot to dispose.
1998        let name = decl
1999            .declarators
2000            .first()
2001            .and_then(|declarator| match &declarator.target.kind {
2002                PatternKind::Ident(ident) => Some(ident.name.clone()),
2003                _ => None,
2004            });
2005        self.stmt(stmt)?;
2006        let Some(name) = name else {
2007            // Unreachable for a well-formed `using`, but a bare `using` with no declarator
2008            // must not make the compiler panic.
2009            return self.stmts(rest);
2010        };
2011        let Some(value_slot) = self.using_value_slot(&name) else {
2012            // Declared globally, which the parser rules out for a script; a module's
2013            // top level is a scope, and there the disposal stays a known gap.
2014            return self.stmts(rest);
2015        };
2016        // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
2017        // exit path already disposed.
2018        let live = !rest.last().is_some_and(Self::terminates);
2019        self.using_region_around(value_slot, live, |compiler| compiler.stmts(rest))
2020    }
2021
2022    /// The slot a `using` binding's value lives in.
2023    fn using_value_slot(&self, name: &str) -> Option<u32> {
2024        self.cur()
2025            .vars
2026            .iter()
2027            .position(|var| var.name == name && var.kind == VarKind::Using)
2028            .map(|index| index as u32)
2029    }
2030
2031    /// Wrap `inside` in a disposal region for the resource in `value_slot`.
2032    ///
2033    /// Shared between a `using` statement — which owns the rest of its block — and a
2034    /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
2035    /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
2036    /// the end, `return`, `break`, `continue`, and an exception — and this engine already
2037    /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
2038    /// target with a `finally_label` is what makes `return` and `break` dispose without
2039    /// knowing anything about `using`.
2040    ///
2041    /// ```text
2042    ///   catch CATCH                <- an exception inside lands here
2043    ///   <inside>
2044    ///   drop                       <- the catch offset, on the fall-through path
2045    ///   undefined; gosub DISPOSE; drop
2046    ///   goto END
2047    /// CATCH:
2048    ///   using_dispose slot         <- merges the failure into the pending exception
2049    ///   throw
2050    /// DISPOSE:
2051    ///   using_dispose_init
2052    ///   using_dispose slot
2053    ///   using_dispose_end          <- rethrows if a dispose failed
2054    ///   ret
2055    /// END:
2056    /// ```
2057    fn using_region_around(
2058        &mut self,
2059        value_slot: u32,
2060        live: bool,
2061        inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
2062    ) -> Result<(), SyntaxError> {
2063        let catch_label = self.new_label();
2064        let end_label = self.new_label();
2065        let dispose_label = self.new_label();
2066
2067        self.emit_jump(Opcode::Catch, catch_label, &[]);
2068        self.push_jump_target(JumpTarget {
2069            names: Vec::new(),
2070            break_label: None,
2071            continue_label: None,
2072            // The catch offset is the one thing on the stack that leaving has to remove.
2073            drop_count: 1,
2074            finally_label: Some(dispose_label),
2075            is_regular_stmt: false,
2076            has_iterator: false,
2077            is_async_iterator: false,
2078        });
2079        inside(self)?;
2080        self.pop_jump_target();
2081
2082        if live {
2083            self.emit(Opcode::Drop, &[]);
2084            self.emit(Opcode::Undefined, &[]);
2085            self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2086            self.emit(Opcode::Drop, &[]);
2087            self.emit_jump(Opcode::Goto, end_label, &[]);
2088        }
2089
2090        // An exception unwinds to here with the thrown value on the stack, which is exactly
2091        // the shape `using_dispose` expects as its error state.
2092        self.place_label(catch_label);
2093        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2094        self.emit(Opcode::Throw, &[]);
2095
2096        self.place_label(dispose_label);
2097        // Inside the subroutine the return value and the `gosub` return address are both
2098        // live, and neither an outer finalizer nor another region may run before this one
2099        // has finished.
2100        self.push_jump_target(JumpTarget {
2101            names: Vec::new(),
2102            break_label: None,
2103            continue_label: None,
2104            drop_count: 2,
2105            finally_label: None,
2106            is_regular_stmt: false,
2107            has_iterator: false,
2108            is_async_iterator: false,
2109        });
2110        self.emit(Opcode::UsingDisposeInit, &[]);
2111        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2112        self.emit(Opcode::UsingDisposeEnd, &[]);
2113        self.pop_jump_target();
2114        self.emit(Opcode::Ret, &[]);
2115        self.place_label(end_label);
2116        Ok(())
2117    }
2118
2119    /// Declare every name a statement list introduces, before compiling any of
2120    /// it, so a reference that appears textually before a declaration still
2121    /// resolves.
2122    ///
2123    /// Declarations are walked in source order because that is the order the
2124    /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2125    /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2126    /// declarations hoist out to the function scope; lexical names belong to the
2127    /// block they were written in, which `block` records.
2128    fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2129        let saved = self.cur().current_block;
2130        self.state().current_block = block;
2131        let result = self.hoist_list(body);
2132        // Only now is every binding of this scope known, so the deferred function
2133        // bodies can be compiled against the finished list. Compiled at its own
2134        // declaration instead, a body that names a `var` written further down would
2135        // have resolved that name as a global.
2136        if result.is_ok() {
2137            let deferred = std::mem::take(&mut self.state().deferred_funcs);
2138            let mut outcome = Ok(());
2139            for (owner, func) in deferred {
2140                let previous = self.cur().current_block;
2141                self.state().current_block = owner;
2142                outcome = self.func_decl(&func);
2143                self.state().current_block = previous;
2144                if outcome.is_err() {
2145                    break;
2146                }
2147            }
2148            self.state().current_block = saved;
2149            return outcome;
2150        }
2151        // `current_block` is restored by the caller for a block statement, since
2152        // it needs it set while compiling; only clean up on the hoist path.
2153        self.state().current_block = saved;
2154        result
2155    }
2156
2157    fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2158        for stmt in body {
2159            self.hoist_stmt(stmt)?;
2160        }
2161        Ok(())
2162    }
2163
2164    /// Whether a statement always transfers control away, making everything after
2165    /// it in the same list unreachable.
2166    ///
2167    /// The reference drops such statements in `skip_dead_code`, so `return 1;
2168    /// let x = 2;` compiles to the same bytecode as `return 1;`.
2169    fn terminates(stmt: &Stmt) -> bool {
2170        matches!(
2171            stmt.kind,
2172            StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2173        )
2174    }
2175
2176    fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2177        match &stmt.kind {
2178            StmtKind::VarDecl(decl) => {
2179                for declarator in &decl.declarators {
2180                    let mut names = Vec::new();
2181                    declarator.target.bound_names(&mut names);
2182                    for name in names {
2183                        let text = name.name.clone();
2184                        if decl.kind == VarDeclKind::Var {
2185                            let def = VarDef::var(text.clone());
2186                            self.declare_var(&text, def);
2187                        } else if decl.kind.is_using() {
2188                            // Two adjacent slots: the resource, then the dispose method
2189                            // snapshotted at declaration. `using_dispose` reads them as a
2190                            // pair `(slot, slot + 1)`, so nothing may be declared between
2191                            // them — which is why both are declared here, in one step,
2192                            // rather than the method being added at emission time.
2193                            self.declare_using(&text);
2194                        } else {
2195                            let def = if decl.kind == VarDeclKind::Const {
2196                                VarDef::constant(text.clone())
2197                            } else {
2198                                VarDef::lexical(text.clone())
2199                            };
2200                            self.declare(&text, def);
2201                        }
2202                    }
2203                }
2204            }
2205            StmtKind::FuncDecl(func) => {
2206                if let Some(name) = &func.name {
2207                    // A function declaration is a `var` binding that happens to
2208                    // hold a function, not a lexical one.
2209                    let def = VarDef::var(name.name.clone());
2210                    self.declare_var(&name.name.clone(), def);
2211                }
2212                // The function object is created when the scope is entered, so it
2213                // exists before the declaration is reached. Its body is compiled
2214                // *after* this scope's hoisting finishes, so a name it uses resolves
2215                // even when the `var` that declares it comes later in the source.
2216                let owner = self.cur().current_block;
2217                self.state().deferred_funcs.push((owner, func.clone()));
2218            }
2219            StmtKind::ClassDecl(class) => {
2220                if let Some(name) = &class.name {
2221                    self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2222                }
2223            }
2224            // A module's imports are bound before any of its code runs, and its exports
2225            // declare the very bindings they export — so both hoist the declarations
2226            // their `StmtKind` arm will later emit code for.
2227            StmtKind::Import(decl) => self.hoist_import(decl)?,
2228            StmtKind::Export(decl) => self.hoist_export(decl)?,
2229            StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2230            StmtKind::If { cons, alt, .. } => {
2231                self.hoist_stmt(cons)?;
2232                if let Some(alt) = alt {
2233                    self.hoist_stmt(alt)?;
2234                }
2235            }
2236            StmtKind::While { body, .. }
2237            | StmtKind::DoWhile { body, .. }
2238            | StmtKind::Labeled { body, .. }
2239            | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2240            StmtKind::For { init, body, .. } => {
2241                // A `for` head gets its own scope even when it declares nothing,
2242                // because `let` in the head is scoped to the loop.
2243                let key = stmt.span.start.offset as u64;
2244                let parent = self.cur().current_block;
2245                self.push_block(key, parent);
2246                if let Some(init) = init
2247                    && let ForInit::VarDecl(decl) = init
2248                {
2249                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2250                }
2251                self.hoist_stmt(body)?;
2252                self.state().current_block = parent;
2253            }
2254            StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
2255                let key = stmt.span.start.offset as u64;
2256                let parent = self.cur().current_block;
2257                self.push_block(key, parent);
2258                if let ForHead::VarDecl(decl) = left {
2259                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2260                }
2261                self.hoist_stmt(body)?;
2262                self.state().current_block = parent;
2263            }
2264            StmtKind::Try {
2265                block,
2266                handler,
2267                finalizer,
2268            } => {
2269                self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2270                let try_parent = self.cur().current_block;
2271                if let Some(handler) = handler {
2272                    // The catch parameter belongs to the function scope, not to a
2273                    // block: it is a `catch` binding rather than a `let`, so it is
2274                    // never in the temporal dead zone and `emit_scope_enter` must
2275                    // not mark it uninitialised. It still has to be declared before
2276                    // the handler body is hoisted, so it takes the slot the
2277                    // reference gives it (bindings are numbered in source order).
2278                    if let Some(pattern) = &handler.param {
2279                        // The parameter gets its own scope, so entering the handler
2280                        // does not have to re-declare it. It is not lexical, so it
2281                        // is never marked uninitialised.
2282                        let key = Self::try_block_key(stmt, TryPart::Param);
2283                        let parent = self.cur().current_block;
2284                        self.push_block(key, parent);
2285                        // A destructuring parameter binds several names, one slot each,
2286                        // in the order they are written. The reference declares those as
2287                        // `let`s rather than as one `catch` binding — its dump prints
2288                        // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2289                        // so the kind follows the shape of the parameter.
2290                        //
2291                        // Neither form is in the dead zone: the stores run as the handler
2292                        // is entered, so both use the unchecked `put_loc`.
2293                        let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2294                        let mut names = Vec::new();
2295                        pattern.bound_names(&mut names);
2296                        for name in names {
2297                            let def = VarDef {
2298                                name: name.name.clone(),
2299                                is_const: false,
2300                                is_lexical: destructures,
2301                                kind: if destructures {
2302                                    crate::bytecode::VarKind::LexicalCatch
2303                                } else {
2304                                    crate::bytecode::VarKind::Catch
2305                                },
2306                                is_captured: false,
2307                                scope_level: 0,
2308                                scope_next: None,
2309                            };
2310                            self.declare_local(&name.name.clone(), def);
2311                        }
2312                        // The handler body nests inside the parameter's scope, so the
2313                        // body's bindings chain on to the parameter (the reference
2314                        // prints `let y [next:1]`, pointing at `e`).
2315                        self.state().current_block = key;
2316                    }
2317                    self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2318                    // Back to the block the `try` itself lives in, so the finalizer
2319                    // is a sibling of the handler rather than nested in it.
2320                    self.state().current_block = try_parent;
2321                }
2322                if let Some(finalizer) = finalizer {
2323                    self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2324                }
2325            }
2326            StmtKind::Switch { cases, .. } => {
2327                let key = stmt.span.start.offset as u64;
2328                let parent = self.cur().current_block;
2329                self.push_block(key, parent);
2330                for case in cases {
2331                    self.hoist_list(&case.body)?;
2332                }
2333                self.state().current_block = parent;
2334            }
2335            _ => {}
2336        }
2337        Ok(())
2338    }
2339
2340    /// Hoist a nested statement list, which is its own lexical scope.
2341    fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2342        let parent = self.cur().current_block;
2343        self.push_block(key, parent);
2344        self.hoist_list(body)?;
2345        self.state().current_block = parent;
2346        Ok(())
2347    }
2348
2349    /// A block key for one part of a `try` statement.
2350    ///
2351    /// The three parts are three separate scopes, so they cannot share the key a
2352    /// statement's own offset would give them: the try block, the handler body and
2353    /// the finalizer would then look like one scope, and their `let` bindings would
2354    /// be marked uninitialised only on entering the first of them.
2355    fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2356        (stmt.span.start.offset as u64) * 4 + part as u64
2357    }
2358
2359    /// Declare a `var`: it lives in the function's own scope, not the block's.
2360    fn declare_var(&mut self, name: &str, def: VarDef) {
2361        if self.cur().is_module {
2362            self.declare_module(name, &def);
2363            return;
2364        }
2365        if self.cur().declares_globally(&def) {
2366            self.declare_global(name, &def);
2367            return;
2368        }
2369        let state = self.state();
2370        // A binding of the *parameter* scope does not count: the body's `var` of the
2371        // same name is a different binding and needs a slot of its own.
2372        if state.vars.iter().enumerate().any(|(index, v)| {
2373            v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
2374        }) {
2375            return;
2376        }
2377        // A `var` belongs to the function scope, never to the enclosing block.
2378        state.var_block.push(FUNCTION_SCOPE);
2379        state.vars.push(def);
2380    }
2381
2382    /// Declare `name` as a binding of the parameter scope, returning its slot.
2383    fn declare_param_var(&mut self, name: &str) -> u32 {
2384        declare_param_var_at(self.state(), name)
2385    }
2386
2387    /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2388    ///
2389    /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2390    /// so each points at the one declared before it and the oldest ends the chain with
2391    /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2392    /// runtime walks when it instantiates them.
2393    fn declare_param_binding(&mut self, name: &str) -> u32 {
2394        let state = self.state();
2395        let previous = state
2396            .vars
2397            .iter()
2398            .enumerate()
2399            .rev()
2400            .find(|(index, var)| {
2401                state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2402            })
2403            .map(|(index, _)| index as i32);
2404        let index = state.vars.len() as u32;
2405        state.var_block.push(PARAM_SCOPE);
2406        let mut def = VarDef::lexical(name);
2407        // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2408        // the function's, and its bindings are initialised one by one rather than all at
2409        // once — which is exactly what the dead zone needs.
2410        def.scope_level = 1;
2411        def.scope_next = Some(previous.unwrap_or(-2));
2412        state.vars.push(def);
2413        index
2414    }
2415
2416    /// The slot of a parameter-list binding, if the list has one by that name.
2417    fn param_binding_slot(&self, name: &str) -> Option<u32> {
2418        let state = self.cur();
2419        state
2420            .vars
2421            .iter()
2422            .enumerate()
2423            .position(|(index, var)| {
2424                var.name == name
2425                    && var.is_lexical
2426                    && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2427            })
2428            .map(|index| index as u32)
2429    }
2430
2431    /// Every parameter-list binding, in declaration order.
2432    fn param_binding_names(&self) -> Vec<String> {
2433        let state = self.cur();
2434        state
2435            .vars
2436            .iter()
2437            .enumerate()
2438            .filter(|(index, var)| {
2439                var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2440            })
2441            .map(|(_, var)| var.name.clone())
2442            .collect()
2443    }
2444
2445    /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2446    fn body_var_slot(&self, name: &str) -> Option<u32> {
2447        let state = self.cur();
2448        state
2449            .vars
2450            .iter()
2451            .enumerate()
2452            .find(|(index, var)| {
2453                var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2454            })
2455            .map(|(index, _)| index as u32)
2456    }
2457
2458    /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2459    /// one.
2460    ///
2461    /// With parameter expressions the reference creates two: an unmapped one in the
2462    /// argument scope, for the defaults and anything they close over, and the body's own.
2463    /// They are separate bindings, which is what makes
2464    /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2465    /// report 1 from `p` and 2 from the body.
2466    fn provide_param_arguments(&mut self) {
2467        if !self.cur().has_parameter_expressions {
2468            return;
2469        }
2470        let mentioned = self.cur().needs_param_arguments
2471            || self
2472                .cur()
2473                .insns
2474                .iter()
2475                .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2476        if !mentioned {
2477            return;
2478        }
2479        let slot = self.declare_param_var("arguments");
2480        let magic = if self.cur().strict || !self.cur().simple_parameter_list {
2481            0
2482        } else {
2483            1
2484        };
2485        self.prepend_initialiser_to(
2486            slot,
2487            Insn::Fixed {
2488                op: Opcode::SpecialObject,
2489                operands: vec![Op::Int(magic)],
2490            },
2491        );
2492    }
2493
2494    /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2495    fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2496        let current = self.stack.len() - 1;
2497        let init = [
2498            producer,
2499            Insn::Fixed {
2500                op: Opcode::PutLoc,
2501                operands: vec![Op::Slot(Slot::Loc(slot))],
2502            },
2503        ];
2504        let inserted = init.len();
2505        for (index, instruction) in init.into_iter().enumerate() {
2506            self.stack[current].insns.insert(index, instruction);
2507        }
2508        for placed in self.stack[current].labels.iter_mut().flatten() {
2509            *placed += inserted;
2510        }
2511        self.state().label_since_insn = false;
2512    }
2513
2514    /// Give the function an `arguments` binding if its body mentions one.
2515    ///
2516    /// The check runs on the *instruction* stream rather than the AST: by this point
2517    /// every reference has become an `Insn::Var`, so scanning is exact and needs no
2518    /// AST walker. Declaring lazily matters for more than tidiness — always declaring
2519    /// would renumber every later local slot and stop the bytecode matching the
2520    /// reference, which only adds the binding when the body uses it.
2521    ///
2522    /// `arguments` is a local, initialised at the top of the body by
2523    /// `special_object`; that is the reference's shape, so the disassembly agrees.
2524    fn provide_arguments(&mut self) {
2525        let current = self.stack.len() - 1;
2526        if self.stack[current].is_script || self.stack[current].is_module {
2527            // A module has no `arguments` binding; referring to it is a ReferenceError,
2528            // which is exactly what an unbound name produces.
2529            return;
2530        }
2531        // An arrow has no `arguments` of its own: the binding belongs to the enclosing
2532        // function, which is why `() => arguments` sees the caller's arguments.
2533        if self.stack[current].is_arrow {
2534            if self.mentions("arguments") {
2535                self.ensure_enclosing_arguments();
2536            }
2537            return;
2538        }
2539        // Only a *body* mention needs the body's binding: the parameter list has one of
2540        // its own (see [`Compiler::provide_param_arguments`]).
2541        //
2542        // `delete arguments` counts too: it compiles to `DeleteVar`, which is not a
2543        // `Var`, so without this the body got no binding at all — the name resolved to
2544        // the global object and `delete` answered `true` for a binding that cannot be
2545        // deleted. The reference answers `false`.
2546        let mentioned = self.cur().insns.iter().any(|insn| match insn {
2547            Insn::Var {
2548                name, in_params, ..
2549            } => name == "arguments" && !*in_params,
2550            Insn::DeleteVar { name } => name == "arguments",
2551            _ => false,
2552        });
2553        if !mentioned && !self.cur().needs_arguments_local {
2554            return;
2555        }
2556        // The request may have come only from a parameter-list arrow, in which case the
2557        // parameter scope's binding already answers for it and the body needs none.
2558        if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
2559            return;
2560        }
2561        // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`.
2562        //
2563        // With parameter expressions the list and the body are separate environments, so
2564        // an assignment to a parameter cannot be reflected into `arguments` at all — the
2565        // arguments object is unmapped whatever the mode, which is why the reference emits
2566        // `special_object 0` here even in sloppy code.
2567        // A non-simple parameter list (`[a]`, `...rest`, `a = 1`) makes the arguments
2568        // object unmapped whatever the mode — §10.4.4 keys the decision on
2569        // `IsSimpleParameterList`, not on strictness alone.
2570        let magic = if self.stack[current].strict || !self.stack[current].simple_parameter_list {
2571            0
2572        } else {
2573            1
2574        };
2575        // A mapped `arguments` shares storage with the parameters: `arguments[0] = 2`
2576        // has to be visible as `a`, and assigning `a` has to be visible as `arguments[0]`.
2577        // The only storage both sides can see is a reference cell, so every parameter the
2578        // object maps gets one — even a parameter no closure captured. Without this the
2579        // slot holds a plain copy and the mapping has nothing to write through.
2580        if magic == 1 {
2581            for arg in &mut self.stack[current].args {
2582                arg.is_captured = true;
2583            }
2584        }
2585        self.prepend_binding("arguments", magic);
2586    }
2587
2588    /// Whether a *body* instruction refers to `arguments`.
2589    fn body_mentions_arguments(&self) -> bool {
2590        self.cur()
2591            .insns
2592            .iter()
2593            .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
2594    }
2595
2596    /// Whether the function body's instruction stream refers to `name`.
2597    fn mentions(&self, name: &str) -> bool {
2598        let current = self.stack.len() - 1;
2599        // A binding of the parameter scope does not answer for the body: the body's own
2600        // `arguments` (or self-name) still has to be provided for it.
2601        if self.stack[current]
2602            .vars
2603            .iter()
2604            .enumerate()
2605            .any(|(index, v)| {
2606                v.name == name
2607                    && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
2608            })
2609        {
2610            return false;
2611        }
2612        self.stack[current]
2613            .insns
2614            .iter()
2615            .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
2616    }
2617
2618    /// Bind the name a named function expression uses to refer to itself.
2619    ///
2620    /// The value is `special_object 2`, the function currently running, so the binding
2621    /// is the closure itself and not a copy. It is a local of this function, which is
2622    /// what keeps `g` out of the enclosing scope.
2623    /// Give the function a local `this`, for an arrow inside it to capture.
2624    fn provide_this_local(&mut self) {
2625        let current = self.stack.len() - 1;
2626        if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
2627            return;
2628        }
2629        if !self.stack[current]
2630            .vars
2631            .iter()
2632            .any(|var| var.name == "this")
2633        {
2634            self.declare_hidden_local("this", VarKind::Normal);
2635        }
2636        self.prepend_initialiser(
2637            "this",
2638            Insn::Fixed {
2639                op: Opcode::PushThis,
2640                operands: vec![],
2641            },
2642        );
2643    }
2644
2645    /// Give the function a local `<home_object>`, for an arrow or a static block inside it
2646    /// to read through `super`.
2647    fn provide_home_object_local(&mut self) {
2648        let current = self.stack.len() - 1;
2649        if !self.stack[current].needs_home_object_local {
2650            return;
2651        }
2652        if !self.stack[current]
2653            .vars
2654            .iter()
2655            .any(|var| var.name == HOME_OBJECT)
2656        {
2657            self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
2658        }
2659        self.prepend_initialiser(
2660            HOME_OBJECT,
2661            Insn::Fixed {
2662                op: Opcode::SpecialObject,
2663                operands: vec![Op::Int(4)],
2664            },
2665        );
2666    }
2667
2668    fn provide_self_name(&mut self) {
2669        let current = self.stack.len() - 1;
2670        let Some(name) = self.stack[current].self_name.clone() else {
2671            return;
2672        };
2673        if self.stack[current].self_name_initialized {
2674            return;
2675        }
2676        // Either the body refers to the name, or a nested function already forced the
2677        // binding into existence while being resolved. A direct `eval` can name it
2678        // without mentioning it, so its presence is a third reason: in strict mode
2679        // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
2680        // that only happens if the binding exists.
2681        let declared = self.stack[current].vars.iter().any(|v| v.name == name);
2682        if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
2683            return;
2684        }
2685        self.stack[current].self_name_initialized = true;
2686        self.prepend_binding_with(&name, 2, VarKind::FunctionName);
2687    }
2688
2689    /// Insert `special_object magic` plus the store to `name` at the top of the body.
2690    ///
2691    /// Prepending shifts every label that has been placed, so they are all moved by
2692    /// the number of instructions inserted.
2693    fn prepend_binding(&mut self, name: &str, magic: i32) {
2694        self.prepend_binding_with(name, magic, VarKind::Normal);
2695    }
2696
2697    /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
2698    fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
2699        let current = self.stack.len() - 1;
2700        // A function-expression's own name is immutable in strict mode, which is what
2701        // makes `f = 1` inside a strict body throw instead of being dropped.
2702        let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
2703        self.declare_var(
2704            name,
2705            VarDef {
2706                kind,
2707                is_const,
2708                ..VarDef::var(name)
2709            },
2710        );
2711        let init = [
2712            Insn::Fixed {
2713                op: Opcode::SpecialObject,
2714                operands: vec![Op::Int(magic)],
2715            },
2716            Insn::Var {
2717                // An initialisation, not an assignment: sloppy mode drops stores to a
2718                // function-expression's own name, and the prologue is what puts the
2719                // value there in the first place.
2720                action: if kind == VarKind::FunctionName {
2721                    VarAction::PutInit
2722                } else {
2723                    VarAction::Put
2724                },
2725                name: name.to_string(),
2726                block: 0,
2727                in_params: false,
2728            },
2729        ];
2730        let inserted = init.len();
2731        for (index, instruction) in init.into_iter().enumerate() {
2732            self.stack[current].insns.insert(index, instruction);
2733        }
2734        for placed in self.stack[current].labels.iter_mut().flatten() {
2735            *placed += inserted;
2736        }
2737        // A store sits at the insertion point now, so the `put`/`get` fold must not
2738        // reach across it.
2739        self.stack[current].label_since_insn = true;
2740    }
2741
2742    /// Record a top-level script declaration as a global.
2743    ///
2744    /// A script's top-level `var`/`let`/`function` create properties of the
2745    /// global object, not slots in the script's frame, so they show up as closure
2746    /// variables instead.
2747    fn declare_global(&mut self, name: &str, def: &VarDef) {
2748        let state = self.state();
2749        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2750            // The name was already referenced, from a function compiled before this
2751            // declaration was reached — `function a(){ b() } function b(){}` resolves
2752            // `b` while `b` is still unknown, and that guess has to be corrected here.
2753            // Leaving it as a plain global meant the declaration was never registered,
2754            // so the binding did not exist at run time and `a()` threw
2755            // `b is not defined`.
2756            if matches!(existing.closure_type, ClosureType::Global) {
2757                existing.closure_type = ClosureType::GlobalDecl;
2758                existing.is_const = def.is_const;
2759                existing.is_lexical = def.is_lexical;
2760            }
2761            return;
2762        }
2763        state.closure_vars.push(ClosureVar {
2764            name: name.to_string(),
2765            is_const: def.is_const,
2766            is_lexical: def.is_lexical,
2767            closure_type: ClosureType::GlobalDecl,
2768            var_idx: 0,
2769        });
2770    }
2771
2772    /// Record a module-level declaration as a module variable.
2773    ///
2774    /// The binding is a closure variable of the module body, so reads and writes are
2775    /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
2776    /// *who fills the cell*: the module record does, before the body runs, and an import
2777    /// points its cell at the exporting module's, which is what makes bindings live and
2778    /// cycles work.
2779    fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
2780        let state = self.state();
2781        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2782            // The name may have been referenced before this declaration was hoisted,
2783            // which resolved it as a plain global. Correct that here, the way
2784            // `declare_global` does.
2785            if matches!(existing.closure_type, ClosureType::Global) {
2786                existing.closure_type = ClosureType::ModuleDecl;
2787                existing.is_const = def.is_const;
2788                existing.is_lexical = def.is_lexical;
2789            }
2790            return 0;
2791        }
2792        state.closure_vars.push(ClosureVar {
2793            name: name.to_string(),
2794            is_const: def.is_const,
2795            is_lexical: def.is_lexical,
2796            closure_type: ClosureType::ModuleDecl,
2797            var_idx: 0,
2798        });
2799        0
2800    }
2801
2802    /// Declare a module variable and answer its closure-variable index.
2803    ///
2804    /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
2805    /// module variable is not one. The import table needs the real index instead, because
2806    /// that is the position the host writes the cell into.
2807    fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
2808        self.declare_module(name, def);
2809        self.cur()
2810            .closure_vars
2811            .iter()
2812            .position(|c| c.name == name)
2813            .map(|index| index as u32)
2814            .unwrap_or(0)
2815    }
2816
2817    /// Declare one imported binding as a module variable.
2818    ///
2819    /// Returns the closure-variable index, which is what the import table records: the
2820    /// host writes the exporter's cell into that slot before the body runs.
2821    fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
2822        let state = self.state();
2823        if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
2824            // Keep the slot, fix the kind: the name may already have been referenced.
2825            state.closure_vars[index].closure_type = ClosureType::ModuleImport;
2826            state.closure_vars[index].is_const = is_const;
2827            return index as u32;
2828        }
2829        state.closure_vars.push(ClosureVar {
2830            name: name.to_string(),
2831            // An imported binding cannot be assigned: `x = 1` on an import is a
2832            // `TypeError` at run time, which the const flag is what produces.
2833            is_const: true,
2834            // Lexical, so reads go through `get_var_ref_check`: before linking has filled
2835            // the cell an import is in its dead zone, and reading it there must say so
2836            // rather than answer `undefined`.
2837            is_lexical: true,
2838            closure_type: ClosureType::ModuleImport,
2839            var_idx: 0,
2840        });
2841        state.closure_vars.len() as u32 - 1
2842    }
2843
2844    /// Emit the code an `export` needs.
2845    ///
2846    /// Only `export default <expr>` has any: everything else is a table entry whose
2847    /// binding is declared elsewhere. The expression is stored into the hidden
2848    /// `*default*` variable rather than returned, because the module body has no value
2849    /// to speak of.
2850    fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2851        match &decl.kind {
2852            ExportKind::Declaration(stmt) => self.stmt(stmt),
2853            ExportKind::Default(expr) => {
2854                // A named default function/class is already a module binding; the export
2855                // points at it and there is nothing to evaluate.
2856                if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some())
2857                    || matches!(&expr.kind, ExprKind::Class(class) if class.name.is_some())
2858                {
2859                    return Ok(());
2860                }
2861                self.expr(expr)?;
2862                let index = self.declare_export_default();
2863                self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
2864                Ok(())
2865            }
2866            ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
2867        }
2868    }
2869
2870    /// A module name as the string it denotes.
2871    fn module_name_text(name: &ModuleName) -> &str {
2872        match name {
2873            ModuleName::Ident(ident) => &ident.name,
2874            ModuleName::Str(text) => text,
2875        }
2876    }
2877
2878    /// Bind `import`'s local names and record where each one comes from.
2879    ///
2880    /// Nothing is emitted: an import is not an instruction, it is a promise that the
2881    /// binding's cell will be filled before the body runs. The cell lands in the module's
2882    /// environment at a fixed index, and the host fills it from the exporter's cell —
2883    /// which is why a cyclic import can bind before the other module has evaluated.
2884    fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
2885        let request = self.module_request(&decl.source, &decl.attributes);
2886        for specifier in &decl.specifiers {
2887            let (local, name, is_star) = match specifier {
2888                ImportSpecifier::Default(ident) => {
2889                    (ident.name.clone(), "default".to_string(), false)
2890                }
2891                ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
2892                ImportSpecifier::Named { imported, local } => (
2893                    local.name.clone(),
2894                    Self::module_name_text(imported).to_string(),
2895                    false,
2896                ),
2897            };
2898            // `import * as ns` is *not* a live binding of another module's variable —
2899            // it is a value of its own, which is why the reference declares it like a
2900            // module variable and the host stores the namespace object in that cell.
2901            let var_idx = if is_star {
2902                // `const`: a namespace object is a value, and the binding is immutable.
2903                self.declare_module_var(&local, &VarDef::constant(local.clone()))
2904            } else {
2905                self.declare_import(&local, true)
2906            };
2907            self.module_meta().imports.push(ImportEntry {
2908                module: request,
2909                name,
2910                var_idx,
2911                is_star,
2912            });
2913        }
2914        Ok(())
2915    }
2916
2917    /// Record what an `export` offers, declaring the binding it exports.
2918    ///
2919    /// `export var x = 1` is a declaration like any other; only the table entry is extra.
2920    fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2921        match &decl.kind {
2922            ExportKind::Declaration(stmt) => {
2923                // The inner declaration keeps its own hoisting, then every name it binds
2924                // becomes an export of the same name.
2925                self.hoist_stmt(stmt)?;
2926                let mut names = Vec::new();
2927                Self::declared_names(stmt, &mut names);
2928                for name in names {
2929                    let var_idx = self.module_binding_index(&name);
2930                    self.exports_local(&name, var_idx);
2931                }
2932            }
2933            ExportKind::Default(expr) => {
2934                // The reference puts a default export in a hidden `*default*` variable,
2935                // so `export default function f(){}` can export a *value* while `f` stays
2936                // a binding of the module.
2937                if let ExprKind::Function(func) = &expr.kind
2938                    && let Some(name) = &func.name
2939                {
2940                    let text = name.name.clone();
2941                    self.hoist_stmt(&Stmt {
2942                        kind: StmtKind::FuncDecl(func.clone()),
2943                        span: expr.span,
2944                    })?;
2945                    let var_idx = self.module_binding_index(&text);
2946                    self.module_meta().exports.push(ExportEntry::Local {
2947                        export_name: "default".to_string(),
2948                        var_idx,
2949                    });
2950                    return Ok(());
2951                }
2952                if let ExprKind::Class(class) = &expr.kind
2953                    && let Some(name) = &class.name
2954                {
2955                    let text = name.name.clone();
2956                    self.hoist_stmt(&Stmt {
2957                        kind: StmtKind::ClassDecl(class.clone()),
2958                        span: expr.span,
2959                    })?;
2960                    let var_idx = self.module_binding_index(&text);
2961                    let _ = var_idx;
2962                }
2963                let var_idx = self.declare_export_default();
2964                self.module_meta().exports.push(ExportEntry::Local {
2965                    export_name: "default".to_string(),
2966                    var_idx,
2967                });
2968            }
2969            ExportKind::Named {
2970                specifiers,
2971                source,
2972                attributes,
2973            } => match source {
2974                Some(source) => {
2975                    let request = self.module_request(source, attributes);
2976                    for specifier in specifiers {
2977                        self.module_meta().exports.push(ExportEntry::Indirect {
2978                            export_name: Self::module_name_text(&specifier.exported).to_string(),
2979                            module: request,
2980                            import_name: Self::module_name_text(&specifier.local).to_string(),
2981                        });
2982                    }
2983                }
2984                None => {
2985                    for specifier in specifiers {
2986                        let local = Self::module_name_text(&specifier.local).to_string();
2987                        let var_idx = self.module_binding_index(&local);
2988                        let export_name = Self::module_name_text(&specifier.exported).to_string();
2989                        self.module_meta().exports.push(ExportEntry::Local {
2990                            export_name,
2991                            var_idx,
2992                        });
2993                    }
2994                }
2995            },
2996            ExportKind::All {
2997                source,
2998                exported,
2999                attributes,
3000            } => {
3001                let request = self.module_request(source, attributes);
3002                match exported {
3003                    Some(name) => {
3004                        self.module_meta().exports.push(ExportEntry::StarAs {
3005                            export_name: Self::module_name_text(name).to_string(),
3006                            module: request,
3007                        });
3008                    }
3009                    None => {
3010                        self.module_meta()
3011                            .exports
3012                            .push(ExportEntry::Star { module: request });
3013                    }
3014                }
3015            }
3016        }
3017        Ok(())
3018    }
3019
3020    /// The names a declaration binds, which is what `export <decl>` exports.
3021    fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
3022        match &stmt.kind {
3023            StmtKind::VarDecl(decl) => {
3024                for declarator in &decl.declarators {
3025                    let mut names = Vec::new();
3026                    declarator.target.bound_names(&mut names);
3027                    out.extend(names.into_iter().map(|name| name.name));
3028                }
3029            }
3030            StmtKind::FuncDecl(func) => {
3031                if let Some(name) = &func.name {
3032                    out.push(name.name.clone());
3033                }
3034            }
3035            StmtKind::ClassDecl(class) => {
3036                if let Some(name) = &class.name {
3037                    out.push(name.name.clone());
3038                }
3039            }
3040            _ => {}
3041        }
3042    }
3043
3044    /// The closure-variable index of a module binding, declaring it if the name was
3045    /// exported without being declared here.
3046    ///
3047    /// `export { x }` where `x` is not declared in the module is a link-time
3048    /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
3049    fn module_binding_index(&mut self, name: &str) -> u32 {
3050        if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
3051            return index as u32;
3052        }
3053        self.declare_module_var(name, &VarDef::lexical(name.to_string()))
3054    }
3055
3056    fn exports_local(&mut self, export_name: &str, var_idx: u32) {
3057        self.module_meta().exports.push(ExportEntry::Local {
3058            export_name: export_name.to_string(),
3059            var_idx,
3060        });
3061    }
3062
3063    /// The hidden `*default*` binding `export default <expr>` stores into.
3064    fn declare_export_default(&mut self) -> u32 {
3065        const DEFAULT: &str = "*default*";
3066        if let Some(index) = self
3067            .cur()
3068            .closure_vars
3069            .iter()
3070            .position(|c| c.name == DEFAULT)
3071        {
3072            return index as u32;
3073        }
3074        self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
3075    }
3076
3077    /// The module tables, which only the top-level state has.
3078    fn module_meta(&mut self) -> &mut ModuleMeta {
3079        self.state()
3080            .module
3081            .as_mut()
3082            .expect("module tables are only touched while compiling a module")
3083    }
3084
3085    /// The index of `specifier`'s request, adding it if it is new.
3086    ///
3087    /// Deduplicated on the specifier *and* its attributes: the same file imported once as
3088    /// JSON and once as text is two modules with two different contents, which is exactly
3089    /// what `hello_module.js` does.
3090    fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
3091        let attributes: Vec<(String, String)> = attributes
3092            .iter()
3093            .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
3094            .collect();
3095        let meta = self.module_meta();
3096        if let Some(index) = meta
3097            .requests
3098            .iter()
3099            .position(|request| request.specifier == specifier && request.attributes == attributes)
3100        {
3101            return index as u32;
3102        }
3103        meta.requests.push(ModuleRequest {
3104            specifier: specifier.to_string(),
3105            attributes,
3106        });
3107        meta.requests.len() as u32 - 1
3108    }
3109
3110    /// Compile a loop body with a `break`/`continue` target pushed for it.
3111    fn loop_body(
3112        &mut self,
3113        body: &Stmt,
3114        labels: &[String],
3115        continue_label: Label,
3116        break_label: Label,
3117    ) -> Result<(), SyntaxError> {
3118        self.push_jump_target(JumpTarget {
3119            names: labels.to_vec(),
3120            break_label: Some(break_label),
3121            continue_label: Some(continue_label),
3122            // A loop leaves nothing of its own on the value stack.
3123            drop_count: 0,
3124            finally_label: None,
3125            is_regular_stmt: false,
3126            has_iterator: false,
3127            is_async_iterator: false,
3128        });
3129        let result = self.stmt(body);
3130        self.pop_jump_target();
3131        result
3132    }
3133
3134    fn push_jump_target(&mut self, target: JumpTarget) {
3135        self.state().jump_targets.push(target);
3136    }
3137
3138    fn pop_jump_target(&mut self) {
3139        self.state().jump_targets.pop();
3140    }
3141
3142    fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3143        let (label, is_break) = match &stmt.kind {
3144            StmtKind::Break(label) => (label.as_ref(), true),
3145            StmtKind::Continue(label) => (label.as_ref(), false),
3146            _ => unreachable!("control_transfer is only called for break and continue"),
3147        };
3148
3149        // Walk outward from the innermost construct. Everything considered before
3150        // the match is a construct control is leaving, and leaving it has a cost:
3151        // its stack slots go, and its finalizer runs.
3152        let targets = self.cur().jump_targets.clone();
3153        for target in targets.iter().rev() {
3154            let destination = match (label, is_break) {
3155                // An unlabelled `break` skips a labelled non-loop statement: `break`
3156                // may name one, but the bare form only means "leave the loop".
3157                (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3158                (None, false) => target.continue_label,
3159                (Some(name), true) => target
3160                    .break_label
3161                    .filter(|_| target.names.contains(&name.name)),
3162                (Some(name), false) => target
3163                    .continue_label
3164                    .filter(|_| target.names.contains(&name.name)),
3165            };
3166
3167            if let Some(destination) = destination {
3168                self.emit_jump(Opcode::Goto, destination, &[]);
3169                return Ok(());
3170            }
3171
3172            // Closing the iterator consumes the three slots the loop keeps on the
3173            // stack (iterator, next method, catch offset), so those are not dropped
3174            // again below.
3175            let mut remaining = target.drop_count;
3176            if target.has_iterator {
3177                self.emit_iterator_close(target.is_async_iterator, false);
3178                remaining = remaining.saturating_sub(3);
3179            }
3180            for _ in 0..remaining {
3181                self.emit(Opcode::Drop, &[]);
3182            }
3183            if let Some(finally) = target.finally_label {
3184                // The finalizer runs as a subroutine and is handed a dummy return
3185                // value, which is dropped afterwards to keep the stack the depth it
3186                // had before.
3187                self.emit(Opcode::Undefined, &[]);
3188                self.emit_jump(Opcode::Gosub, finally, &[]);
3189                self.emit(Opcode::Drop, &[]);
3190            }
3191        }
3192
3193        // The parser rejects a break/continue with no target, so reaching here
3194        // means the compiler's own bookkeeping is wrong.
3195        Err(SyntaxError::new(
3196            if is_break {
3197                "break has no enclosing loop or switch"
3198            } else {
3199                "continue has no enclosing loop"
3200            },
3201            stmt.span,
3202        ))
3203    }
3204
3205    /// Compile a labelled statement.
3206    ///
3207    /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3208    /// that loop's targets, so the chain is collected and handed to the loop. A
3209    /// label on a non-loop statement only provides a `break` target, because
3210    /// `continue` may not target it.
3211    fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3212        let mut names = vec![label.name.clone()];
3213        let mut inner = body;
3214        while let StmtKind::Labeled {
3215            label: next,
3216            body: deeper,
3217        } = &inner.kind
3218        {
3219            names.push(next.name.clone());
3220            inner = deeper;
3221        }
3222        if Self::is_loop(inner) {
3223            return self.stmt_labelled(inner, &names);
3224        }
3225        let end = self.new_label();
3226        self.push_jump_target(JumpTarget {
3227            names,
3228            break_label: Some(end),
3229            continue_label: None,
3230            drop_count: 0,
3231            finally_label: None,
3232            is_regular_stmt: true,
3233            has_iterator: false,
3234            is_async_iterator: false,
3235        });
3236        let result = self.stmt(inner);
3237        self.pop_jump_target();
3238        result?;
3239        self.place_label(end);
3240        let _ = stmt;
3241        Ok(())
3242    }
3243
3244    /// Whether a statement is a loop, i.e. a valid target for `continue`.
3245    fn is_loop(stmt: &Stmt) -> bool {
3246        matches!(
3247            stmt.kind,
3248            StmtKind::While { .. }
3249                | StmtKind::DoWhile { .. }
3250                | StmtKind::For { .. }
3251                | StmtKind::ForIn { .. }
3252                | StmtKind::ForOf { .. }
3253        )
3254    }
3255
3256    /// Compile `switch`.
3257    ///
3258    /// The discriminant is evaluated once and stays on the value stack while the
3259    /// clauses compare against copies of it, so it is dropped at the end — which is
3260    /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3261    /// clause's body jumps over the *next* clause's tests straight into its body.
3262    ///
3263    /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3264    /// the next run's tests. Only the last run's miss reaches the `default` body, or
3265    /// the end of the switch when there is no `default`. That failure path can point
3266    /// backwards (`default` written first), so the runs and their labels are worked
3267    /// out before any code is emitted.
3268    fn switch(
3269        &mut self,
3270        discriminant: &Expr,
3271        cases: &[SwitchCase],
3272        stmt: &Stmt,
3273    ) -> Result<(), SyntaxError> {
3274        self.reset_value();
3275        // The discriminant is evaluated outside the switch's block scope, before
3276        // any `case` clause exists.
3277        self.expr(discriminant)?;
3278
3279        let switch_key = stmt.span.start.offset as u64;
3280        let switch_parent = self.cur().current_block;
3281        self.push_block(switch_key, switch_parent);
3282        self.emit_scope_enter(switch_key);
3283
3284        let break_label = self.new_label();
3285        self.push_jump_target(JumpTarget {
3286            names: Vec::new(),
3287            break_label: Some(break_label),
3288            // `switch` is a valid `break` target but not a `continue` target.
3289            continue_label: None,
3290            // The discriminant stays on the value stack for the whole statement, so
3291            // a `break` aimed further out has to discard it.
3292            drop_count: 1,
3293            finally_label: None,
3294            is_regular_stmt: false,
3295            has_iterator: false,
3296            is_async_iterator: false,
3297        });
3298
3299        // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3300        // its label to the clause after it, so both tests reach the same body.
3301        let mut runs: Vec<(usize, usize)> = Vec::new();
3302        let mut scan = 0;
3303        while scan < cases.len() {
3304            if cases[scan].test.is_some() {
3305                let mut last = scan;
3306                while last + 1 < cases.len()
3307                    && cases[last].test.is_some()
3308                    && cases[last].body.is_empty()
3309                    && cases[last + 1].test.is_some()
3310                {
3311                    last += 1;
3312                }
3313                runs.push((scan, last));
3314                scan = last + 1;
3315            } else {
3316                scan += 1;
3317            }
3318        }
3319
3320        let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3321        let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3322        let default_at = cases.iter().position(|case| case.test.is_none());
3323        // Where the last run sends control when nothing matched.
3324        let miss_target = match default_at {
3325            Some(index) => body_labels[index],
3326            None => break_label,
3327        };
3328
3329        // When `default` comes first, control has to jump over it to reach the
3330        // tests. It only needs to when some clause actually has a test; otherwise
3331        // the default body is the entry point.
3332        let mut entry = None;
3333        if default_at == Some(0) && !runs.is_empty() {
3334            self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3335            entry = Some(run_labels[0]);
3336        }
3337
3338        let mut index = 0;
3339        let mut run = 0;
3340        let result = (|| -> Result<(), SyntaxError> {
3341            while index < cases.len() {
3342                if cases[index].test.is_some() {
3343                    let (first, last) = runs[run];
3344                    // Reaching these tests from the preceding body is a
3345                    // fallthrough, which continues inside the body and skips them.
3346                    if index > 0 {
3347                        self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3348                    }
3349                    if let Some(label) = entry.take() {
3350                        self.place_label(label);
3351                    }
3352                    self.place_label(run_labels[run]);
3353
3354                    for (offset, case) in cases[first..=last].iter().enumerate() {
3355                        let test = case.test.as_ref().unwrap();
3356                        self.emit(Opcode::Dup, &[]);
3357                        self.expr(test)?;
3358                        self.emit(Opcode::StrictEq, &[]);
3359                        if first + offset < last {
3360                            self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3361                        } else {
3362                            // Hand over to the next run's tests, or give up.
3363                            let next = match runs.get(run + 1) {
3364                                Some(_) => run_labels[run + 1],
3365                                None => miss_target,
3366                            };
3367                            self.emit_jump(Opcode::IfFalse, next, &[]);
3368                        }
3369                    }
3370
3371                    self.place_label(body_labels[index]);
3372                    for case in &cases[first..=last] {
3373                        self.stmts(&case.body)?;
3374                    }
3375                    index = last + 1;
3376                    run += 1;
3377                } else {
3378                    // `default`: control arrives here either by falling through or
3379                    // because every test missed.
3380                    self.place_label(body_labels[index]);
3381                    self.stmts(&cases[index].body)?;
3382                    index += 1;
3383                }
3384            }
3385            Ok(())
3386        })();
3387
3388        if result.is_ok() {
3389            self.place_label(break_label);
3390            // Discard the discriminant now that no test needs it.
3391            self.emit(Opcode::Drop, &[]);
3392        }
3393
3394        self.pop_jump_target();
3395        self.emit_scope_leave(switch_key);
3396        self.state().current_block = switch_parent;
3397        result
3398    }
3399
3400    /// Compile `try`/`catch`/`finally`.
3401    ///
3402    /// The shape is an exception table built out of `catch` instructions, each of
3403    /// which records where control goes if the instructions that follow raise:
3404    ///
3405    /// ```text
3406    /// catch HANDLER            <- if the guarded block throws, jump to HANDLER
3407    ///   <guarded block>
3408    ///   drop                   <- discard the catch offset
3409    ///   undefined; gosub FINALLY; drop
3410    ///   goto END
3411    /// HANDLER:
3412    ///   <bind the catch parameter>
3413    ///   catch CATCH2           <- if the handler itself throws, go to CATCH2
3414    ///   <handler body>
3415    ///   drop; undefined; gosub FINALLY; drop; goto END
3416    /// CATCH2:
3417    ///   gosub FINALLY; throw   <- run the finalizer, then let the error out
3418    /// FINALLY:
3419    ///   <finalizer>
3420    ///   ret                    <- return to the `gosub`
3421    /// END:
3422    /// ```
3423    ///
3424    /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
3425    /// of the finalizer serves the normal path, the handler path and the
3426    /// propagating-exception path.
3427    ///
3428    /// The `undefined` before each `gosub` is a dummy return value: the finalizer
3429    /// runs with `ret_value` on the stack, and the normal path has no value to
3430    /// keep, so it pushes one to keep the stack depth identical on every path.
3431    fn try_stmt(
3432        &mut self,
3433        stmt: &Stmt,
3434        block: &[Stmt],
3435        handler: &Option<CatchClause>,
3436        finalizer: Option<&[Stmt]>,
3437    ) -> Result<(), SyntaxError> {
3438        self.reset_value();
3439
3440        let catch_label = self.new_label();
3441        let catch2_label = self.new_label();
3442        let finally_label = self.new_label();
3443        let end_label = self.new_label();
3444
3445        self.emit_jump(Opcode::Catch, catch_label, &[]);
3446
3447        // The guarded block. `break` may not target it, so its entry exists purely
3448        // to unwind: a jump out has to discard the catch offset and run the
3449        // finalizer.
3450        self.push_jump_target(JumpTarget {
3451            names: Vec::new(),
3452            break_label: None,
3453            continue_label: None,
3454            drop_count: 1,
3455            finally_label: Some(finally_label),
3456            is_regular_stmt: false,
3457            has_iterator: false,
3458            is_async_iterator: false,
3459        });
3460
3461        let block_key = Self::try_block_key(stmt, TryPart::Block);
3462        let block_parent = self.cur().current_block;
3463        self.push_block(block_key, block_parent);
3464        self.emit_scope_enter(block_key);
3465        self.stmts(block)?;
3466        self.emit_scope_leave(block_key);
3467        self.state().current_block = block_parent;
3468        // A guarded block that ends in a `return`/`throw` never reaches the
3469        // epilogue, so the reference does not emit one.
3470        self.pop_jump_target();
3471        let block_live = !block.last().is_some_and(Self::terminates);
3472
3473        if block_live {
3474            self.emit(Opcode::Drop, &[]);
3475            self.emit(Opcode::Undefined, &[]);
3476            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3477            self.emit(Opcode::Drop, &[]);
3478            self.emit_jump(Opcode::Goto, end_label, &[]);
3479        }
3480
3481        if let Some(handler) = handler {
3482            self.place_label(catch_label);
3483            // The thrown value is on top of the stack: bind it, or discard it for
3484            // `catch { }`.
3485            match &handler.param {
3486                Some(pattern) => {
3487                    // The stores resolve the names, so they have to run inside the
3488                    // parameter's own scope; otherwise a same-named `catch` further out
3489                    // could win. A `catch` binding is never in the dead zone, so the store
3490                    // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
3491                    let param_key = Self::try_block_key(stmt, TryPart::Param);
3492                    let param_parent = self.cur().current_block;
3493                    self.push_block(param_key, param_parent);
3494                    self.destructure(pattern, Some(VarDeclKind::Var))?;
3495                    self.state().current_block = param_parent;
3496                }
3497                None => self.emit(Opcode::Drop, &[]),
3498            }
3499            self.emit_jump(Opcode::Catch, catch2_label, &[]);
3500
3501            self.push_jump_target(JumpTarget {
3502                names: Vec::new(),
3503                break_label: None,
3504                continue_label: None,
3505                drop_count: 1,
3506                finally_label: Some(finally_label),
3507                is_regular_stmt: false,
3508                has_iterator: false,
3509                is_async_iterator: false,
3510            });
3511            let catch_key = Self::try_block_key(stmt, TryPart::Catch);
3512            let catch_parent = self.cur().current_block;
3513            self.push_block(catch_key, catch_parent);
3514            self.emit_scope_enter(catch_key);
3515            self.stmts(&handler.body)?;
3516            self.emit_scope_leave(catch_key);
3517            self.state().current_block = catch_parent;
3518            self.pop_jump_target();
3519            let handler_live = !handler.body.last().is_some_and(Self::terminates);
3520
3521            if handler_live {
3522                self.emit(Opcode::Drop, &[]);
3523                self.emit(Opcode::Undefined, &[]);
3524                self.emit_jump(Opcode::Gosub, finally_label, &[]);
3525                self.emit(Opcode::Drop, &[]);
3526                self.emit_jump(Opcode::Goto, end_label, &[]);
3527            }
3528
3529            // An error raised inside the handler still has to run the finalizer.
3530            self.place_label(catch2_label);
3531            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3532            self.emit(Opcode::Throw, &[]);
3533        } else {
3534            // `try`/`finally` with no handler: the finalizer runs, then the error
3535            // keeps propagating.
3536            self.place_label(catch_label);
3537            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3538            self.emit(Opcode::Throw, &[]);
3539        }
3540
3541        self.place_label(finally_label);
3542        // Inside the finalizer, leaving has a different cost: the return value and
3543        // the `gosub` return address are both on the stack, and neither finalizer nor
3544        // any outer one may run before the block has finished.
3545        self.push_jump_target(JumpTarget {
3546            names: Vec::new(),
3547            break_label: None,
3548            continue_label: None,
3549            drop_count: 2,
3550            finally_label: None,
3551            is_regular_stmt: false,
3552            has_iterator: false,
3553            is_async_iterator: false,
3554        });
3555        if let Some(finalizer) = finalizer {
3556            let finally_key = Self::try_block_key(stmt, TryPart::Finally);
3557            let finally_parent = self.cur().current_block;
3558            self.push_block(finally_key, finally_parent);
3559            self.emit_scope_enter(finally_key);
3560            self.stmts(finalizer)?;
3561            self.emit_scope_leave(finally_key);
3562            self.state().current_block = finally_parent;
3563        }
3564        self.pop_jump_target();
3565        self.emit(Opcode::Ret, &[]);
3566        self.place_label(end_label);
3567        Ok(())
3568    }
3569
3570    /// Compile `for`/`in` and `for`/`of`.
3571    ///
3572    /// Both keep an enumeration record on the value stack for the whole loop, which
3573    /// is what makes leaving early expensive: the record has to be dropped, or the
3574    /// iterator closed. The layout is
3575    ///
3576    /// ```text
3577    ///   <iterated expression>
3578    ///   for_in_start | for_of_start      <- pushes the record
3579    ///   goto TEST
3580    /// NEXT:
3581    ///   <bind the loop variable>
3582    ///   <body>
3583    /// TEST:
3584    ///   for_in_next | for_of_next 0
3585    ///   if_false NEXT                    <- not finished: next iteration
3586    ///   drop                             <- finished: discard the leftover value
3587    /// BREAK:
3588    ///   drop | iterator_close            <- the one cleanup `break` also uses
3589    /// ```
3590    ///
3591    /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
3592    /// normal exit share one copy — which is why `break` inside the loop emits nothing
3593    /// of its own, and only a jump that passes *through* the loop pays for its record.
3594    fn for_in_of(
3595        &mut self,
3596        stmt: &Stmt,
3597        left: &ForHead,
3598        right: &Expr,
3599        body: &Stmt,
3600        kind: ForLoopKind,
3601        labels: &[String],
3602    ) -> Result<(), SyntaxError> {
3603        self.reset_value();
3604
3605        let loop_key = stmt.span.start.offset as u64;
3606        let loop_parent = self.cur().current_block;
3607        self.push_block(loop_key, loop_parent);
3608        self.emit_scope_enter(loop_key);
3609
3610        // The iterated expression is evaluated inside the loop's scope, after the
3611        // bindings exist in the temporal dead zone.
3612        self.expr(right)?;
3613
3614        let next = self.new_label();
3615        let test = self.new_label();
3616        let break_target = self.new_label();
3617
3618        let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
3619        match kind {
3620            ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
3621            ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
3622            ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
3623        }
3624        self.emit_jump(Opcode::Goto, test, &[]);
3625
3626        self.push_jump_target(JumpTarget {
3627            // `outer: for (x of xs) … break outer` needs the name here. Without it the
3628            // loop had no label to break to, and the compiler reported "break has no
3629            // enclosing loop" for a loop that was plainly enclosing it.
3630            names: labels.to_vec(),
3631            break_label: Some(break_target),
3632            continue_label: Some(test),
3633            // Passing through the loop has to dispose of its record. A `for`/`of`
3634            // record is three slots, and closing the iterator consumes all of them.
3635            drop_count: if has_iterator { 3 } else { 1 },
3636            finally_label: None,
3637            is_regular_stmt: false,
3638            has_iterator,
3639            is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
3640        });
3641
3642        self.place_label(next);
3643        self.bind_loop_variable(left)?;
3644
3645        // The reference marks the body with its own label here. Nothing jumps to it
3646        // once the loop is laid out, but it is not decoration: a label between the
3647        // store and the body is why `put_loc v; get_loc v` does *not* fold into
3648        // `set_loc v` when the body starts by reading the loop variable.
3649        let body_label = self.new_label();
3650        self.place_label(body_label);
3651        // `for (using x of …)` disposes once per iteration, so the body is a disposal
3652        // region rather than the whole loop: the resource is the element that this
3653        // iteration produced.
3654        let using_slot = match left {
3655            ForHead::VarDecl(decl) if decl.kind.is_using() => {
3656                decl.declarators
3657                    .first()
3658                    .and_then(|declarator| match &declarator.target.kind {
3659                        PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
3660                        _ => None,
3661                    })
3662            }
3663            _ => None,
3664        };
3665        match using_slot {
3666            Some(slot) => {
3667                let live = !Self::terminates(body);
3668                self.using_region_around(slot, live, |compiler| compiler.stmt(body))?;
3669            }
3670            None => self.stmt(body)?,
3671        }
3672
3673        // §14.7.5.6 `ForIn/OfBodyEvaluation` step 6: a `let`/`const` head gets a **fresh
3674        // binding each iteration**, so a closure the body creates keeps that iteration's
3675        // value. `CloseCaptured` is the same instruction the C-style `for` uses: it swaps in
3676        // a new reference cell holding the current value.
3677        //
3678        // The position is the *end* of the body, not the start: closing before the body
3679        // would leave the closures pointing at the cell the next `put_loc` overwrites, and
3680        // `for (const x of [1,2,3]) fs.push(() => x)` answered `2,3,3` instead of `1,2,3`.
3681        for name in Self::loop_binding_names(left) {
3682            let pos = self.cur().cur_pos;
3683            self.state().insns.push(Insn::CloseCaptured {
3684                name,
3685                block: loop_key,
3686            });
3687            self.state().insn_pos.push(pos);
3688        }
3689        self.place_label(test);
3690        match kind {
3691            ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
3692            ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
3693            ForLoopKind::AwaitOf => {
3694                // The reference's shape: step, `await` the result, then unpack it.
3695                self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
3696                self.emit(Opcode::Await, &[]);
3697                self.state().has_await = true;
3698                self.emit(Opcode::IteratorGetValueDone, &[]);
3699            }
3700        }
3701        self.emit_jump(Opcode::IfFalse, next, &[]);
3702        // The loop is finished; `for_xx_next` left an `undefined` behind.
3703        self.emit(Opcode::Drop, &[]);
3704
3705        self.pop_jump_target();
3706        self.place_label(break_target);
3707        if has_iterator {
3708            // A loop that ran to completion finds its iterator slot already cleared (see
3709            // `iterator_get_value_done`), so this closes only an iterator abandoned by a
3710            // `break` that jumped here.
3711            self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
3712        } else {
3713            self.emit(Opcode::Drop, &[]);
3714        }
3715
3716        self.emit_scope_leave(loop_key);
3717        self.state().current_block = loop_parent;
3718        Ok(())
3719    }
3720
3721    /// The names a `for (let … of/in …)` head declares, which need a fresh cell per
3722    /// iteration. An assignment head (`for (x of …)`) declares nothing, so it is empty.
3723    fn loop_binding_names(left: &ForHead) -> Vec<String> {
3724        let ForHead::VarDecl(decl) = left else {
3725            return Vec::new();
3726        };
3727        if decl.kind == VarDeclKind::Var {
3728            return Vec::new();
3729        }
3730        let mut names = Vec::new();
3731        for declarator in &decl.declarators {
3732            let mut idents = Vec::new();
3733            declarator.target.bound_names(&mut idents);
3734            names.extend(idents.into_iter().map(|ident| ident.name));
3735        }
3736        names
3737    }
3738
3739    /// Store the value `for_xx_next` left on the stack into the loop variable.
3740    fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
3741        // A declaration *initialises* the binding, which is what takes a `let` out of
3742        // the temporal dead zone, so the store is the unchecked form. Assigning to a
3743        // binding declared elsewhere is an ordinary write and keeps its check.
3744        let (pattern, action) = match left {
3745            ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
3746            ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
3747        };
3748        match &pattern.kind {
3749            PatternKind::Ident(name) => {
3750                // `for (using x of …)` validates and snapshots each iteration's value
3751                // before the body runs, which is what makes a non-disposable element fail
3752                // on the iteration that produced it rather than at the end of the loop.
3753                if let ForHead::VarDecl(decl) = left
3754                    && decl.kind.is_using()
3755                {
3756                    let method_slot = self
3757                        .using_method_slot(&name.name)
3758                        .expect("a using binding was declared during hoisting");
3759                    self.emit(
3760                        Opcode::UsingCheck,
3761                        &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3762                    );
3763                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3764                }
3765                self.emit_var(action, &name.name);
3766                Ok(())
3767            }
3768            // Every other target stores through the same path an assignment pattern
3769            // uses, which is what makes `for (a[0] in obj)` write each key into the
3770            // property instead of refusing the loop outright.
3771            _ => self.destructure(
3772                pattern,
3773                match left {
3774                    ForHead::VarDecl(decl) => Some(decl.kind),
3775                    ForHead::Assign(_) => None,
3776                },
3777            ),
3778        }
3779    }
3780
3781    fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
3782        for declarator in &decl.declarators {
3783            let Some(init) = &declarator.init else {
3784                // `var x;` stays `undefined`. A lexical binding is different: it
3785                // has to be *initialised* to leave the temporal dead zone, so the
3786                // compiler supplies an explicit `undefined`.
3787                if decl.kind.is_lexical() {
3788                    // A lexical binding has to be *initialised* to leave the temporal
3789                    // dead zone, and a destructuring one is no different — `let {a}`
3790                    // with no initialiser is a syntax error, but `let [a] = []` still
3791                    // needs `a` to be initialised from an empty source, which the
3792                    // pattern does on its own.
3793                    self.emit(Opcode::Undefined, &[]);
3794                    self.destructure(&declarator.target, Some(decl.kind))?;
3795                }
3796                continue;
3797            };
3798            match &declarator.target.kind {
3799                PatternKind::Ident(name) => {
3800                    self.expr(init)?;
3801                    self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
3802                    if decl.kind.is_using() {
3803                        // `using_check` validates the value and snapshots its dispose
3804                        // method: `value -> value, method`. The snapshot is what makes a
3805                        // later change to `Symbol.dispose` irrelevant, and validating here
3806                        // is what keeps the body from running at all when the value is not
3807                        // disposable.
3808                        let method_slot = self
3809                            .using_method_slot(&name.name)
3810                            .expect("a using binding was declared during hoisting");
3811                        self.emit(
3812                            Opcode::UsingCheck,
3813                            &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3814                        );
3815                        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3816                        self.emit_var(VarAction::PutInit, &name.name);
3817                        continue;
3818                    }
3819                    // A declaration statement produces no value, so nothing is
3820                    // duplicated onto the stack.
3821                    match decl.kind {
3822                        VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
3823                        _ => self.emit_var(VarAction::PutInit, &name.name),
3824                    }
3825                }
3826                _ => {
3827                    // A destructuring declaration keeps nothing on the stack: the
3828                    // pattern consumes the initialiser.
3829                    self.expr(init)?;
3830                    self.destructure(&declarator.target, Some(decl.kind))?;
3831                }
3832            }
3833        }
3834        Ok(())
3835    }
3836
3837    /// Bind a destructuring pattern from the value on top of the stack.
3838    ///
3839    /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
3840    /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
3841    /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
3842    /// *assignment*, where a member expression is a legal target and the store is an
3843    /// ordinary property write.
3844    ///
3845    /// The value is consumed. An assignment expression's own result is the right-hand
3846    /// side, which the caller keeps separately — the spec does not make the pattern's
3847    /// last store produce it.
3848    fn destructure(
3849        &mut self,
3850        pattern: &Pattern,
3851        decl: Option<VarDeclKind>,
3852    ) -> Result<(), SyntaxError> {
3853        match &pattern.kind {
3854            PatternKind::Ident(name) => {
3855                match decl {
3856                    Some(VarDeclKind::Var) | None => {
3857                        self.emit_var(VarAction::Put, &name.name);
3858                    }
3859                    Some(_) => self.emit_var(VarAction::PutInit, &name.name),
3860                }
3861                Ok(())
3862            }
3863            PatternKind::Assign { target, default } => {
3864                // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
3865                // keeps `null`.
3866                //
3867                // The shape is the reference's: test for `undefined`, and when the value is
3868                // present fall **through** to a single store both paths share. The
3869                // alternatives — branching to the store on each side — need a second store
3870                // and a jump between them, which is what the dump used to show.
3871                let has_value = self.new_label();
3872                self.emit(Opcode::Dup, &[]);
3873                self.emit(Opcode::IsUndefined, &[]);
3874                self.emit_jump(Opcode::IfFalse, has_value, &[]);
3875                self.emit(Opcode::Drop, &[]);
3876                self.expr(default)?;
3877                // `var {f = function(){}} = {}` names the function `f`, like a plain
3878                // `var f = function(){}` does. Both pattern forms do it:
3879                // `BindingInitialization` names the value for a *binding* target, and since
3880                // ES2018 `DestructuringAssignmentEvaluation` does the same, so
3881                // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
3882                // no name to give, which is why only an identifier qualifies.
3883                if let PatternKind::Ident(name) = &target.kind {
3884                    self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
3885                }
3886                self.place_label(has_value);
3887                self.destructure(target, decl)
3888            }
3889            PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
3890            PatternKind::Object { properties, rest } => {
3891                self.destructure_object(properties, rest, decl, pattern)
3892            }
3893            PatternKind::Member(member) if decl.is_none() => {
3894                // An assignment pattern may store into a property. The value is on the
3895                // stack, so the receiver and the key go above it and `rot3l`/`swap2`
3896                // put the three in the order `put_array_el`/`put_field` expect.
3897                self.expr(&member.object)?;
3898                match &member.property {
3899                    MemberProp::Ident(name) => {
3900                        // `value obj` -> `obj value`, the order `put_field` takes.
3901                        // Nothing needs to be left behind: a pattern element's value is
3902                        // consumed by its own store.
3903                        self.emit(Opcode::Swap, &[]);
3904                        self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
3905                    }
3906                    MemberProp::Computed(index) => {
3907                        self.expr(index)?;
3908                        // `value obj key` -> `obj key value`.
3909                        self.emit(Opcode::Rot3l, &[]);
3910                        self.emit(Opcode::PutArrayEl, &[]);
3911                    }
3912                    MemberProp::Private(name) => {
3913                        // `value obj` -> `obj value`, and the store half of the assignment is
3914                        // the same one `obj.#x = value` uses — only without `insert2`,
3915                        // because a pattern element's value is not wanted back.
3916                        let binding = format!("#{}", name.name);
3917                        let (kind, setter) = self.private_use(&binding, member.span)?;
3918                        self.emit(Opcode::Swap, &[]);
3919                        self.private_store(&binding, kind, setter.as_deref())?;
3920                    }
3921                }
3922                Ok(())
3923            }
3924            PatternKind::Rest(inner) => self.destructure(inner, decl),
3925            PatternKind::Invalid(expr) => {
3926                Err(SyntaxError::new("invalid assignment target", expr.span))
3927            }
3928            _ => Err(SyntaxError::new(
3929                "this destructuring target is not supported by the compiler yet",
3930                pattern.span,
3931            )),
3932        }
3933    }
3934
3935    /// `[…]` on the left: drain an iterator, binding one target per element.
3936    fn destructure_array(
3937        &mut self,
3938        elements: &[Option<PatternElement>],
3939        rest: &Option<Box<RestElement>>,
3940        decl: Option<VarDeclKind>,
3941    ) -> Result<(), SyntaxError> {
3942        // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
3943        // pattern accepts any iterable and closes the iterator when the pattern ends
3944        // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
3945        // first because it is on top.
3946        self.emit(Opcode::ForOfStart, &[]);
3947        for element in elements {
3948            self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
3949            self.emit(Opcode::Drop, &[]);
3950            match element {
3951                Some(PatternElement::Pattern(pattern)) => self.destructure(pattern, decl)?,
3952                Some(PatternElement::Property { span, .. }) => {
3953                    return Err(SyntaxError::new(
3954                        "a property pattern is not a valid array element",
3955                        *span,
3956                    ));
3957                }
3958                // An elision skips the value, which is already on the stack.
3959                None => self.emit(Opcode::Drop, &[]),
3960            }
3961        }
3962        if let Some(rest) = rest {
3963            // The remaining values go into a fresh array. The target and its running
3964            // index stay on the stack above the iterator, which is what the operand of
3965            // `for_of_next` accounts for: two values sit above the iterator triple.
3966            self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
3967            self.emit(Opcode::Push0, &[]);
3968            let top = self.new_label();
3969            self.place_label(top);
3970            self.emit(Opcode::ForOfNext, &[Op::Int(2)]);
3971            let done = self.new_label();
3972            self.emit_jump(Opcode::IfTrue, done, &[]);
3973            self.emit(Opcode::DefineArrayEl, &[]);
3974            self.emit(Opcode::Inc, &[]);
3975            self.emit_jump(Opcode::Goto, top, &[]);
3976            self.place_label(done);
3977            self.emit(Opcode::Drop, &[]);
3978            self.emit(Opcode::Drop, &[]);
3979            self.destructure_rest(rest, decl)?;
3980        }
3981        self.emit(Opcode::IteratorClose, &[]);
3982        Ok(())
3983    }
3984
3985    /// `{…}` on the left: read properties off one boxed source object.
3986    fn destructure_object(
3987        &mut self,
3988        properties: &[Option<PatternElement>],
3989        rest: &Option<Box<RestElement>>,
3990        decl: Option<VarDeclKind>,
3991        pattern: &Pattern,
3992    ) -> Result<(), SyntaxError> {
3993        // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
3994        // aside for the rest element below.
3995        self.emit(Opcode::ToObject, &[]);
3996        let mut taken: Vec<Wtf8> = Vec::new();
3997        // Whether any key was computed, which a rest element cannot exclude.
3998        let mut computed = false;
3999        for property in properties {
4000            let Some(PatternElement::Property {
4001                key, value, span, ..
4002            }) = property
4003            else {
4004                return Err(SyntaxError::new(
4005                    "a bare pattern is not a valid object property",
4006                    properties
4007                        .iter()
4008                        .flatten()
4009                        .map(|element| match element {
4010                            PatternElement::Pattern(pattern) => pattern.span,
4011                            PatternElement::Property { span, .. } => *span,
4012                        })
4013                        .next()
4014                        .unwrap_or(pattern.span),
4015                ));
4016            };
4017            // Every read needs the source twice: to read from, and to keep for the next
4018            // property. `get_field2` is that duplicate-and-read in one instruction, but it
4019            // leaves the copy *under* the value, so it is only usable when whatever
4020            // consumes the value tolerates that. See [`reads_with_get_field2`].
4021            let nested = reads_with_get_field2(decl, value);
4022            if !nested {
4023                self.emit(Opcode::Dup, &[]);
4024            }
4025            match key {
4026                PropName::Literal(literal) => {
4027                    let name = self.property_key_text(literal, *span)?;
4028                    taken.push(name.clone());
4029                    self.emit(
4030                        if nested {
4031                            Opcode::GetField2
4032                        } else {
4033                            Opcode::GetField
4034                        },
4035                        &[Op::Atom(Atom::from_wtf8(&name))],
4036                    );
4037                }
4038                PropName::Computed(index) => {
4039                    // A computed key has no name to exclude ahead of time, so a rest
4040                    // element that has to skip it is refused below rather than silently
4041                    // copying the property into the rest object.
4042                    computed = true;
4043                    self.expr(index)?;
4044                    self.emit(Opcode::GetArrayEl, &[]);
4045                }
4046                PropName::Private(_) => {
4047                    return Err(SyntaxError::new(
4048                        "private fields are not supported by the compiler yet",
4049                        value.span,
4050                    ));
4051                }
4052            }
4053            self.destructure(value, decl)?;
4054        }
4055        match rest {
4056            Some(rest) => {
4057                if computed {
4058                    return Err(SyntaxError::new(
4059                        "a computed key with a rest element is not supported by the compiler yet",
4060                        Self::rest_span(rest),
4061                    ));
4062                }
4063                // `target src exclude`: the exclusion list is an array of the keys the
4064                // literal part already took, so the rest object gets only the others.
4065                self.emit(Opcode::Object, &[]);
4066                self.emit(Opcode::Swap, &[]);
4067                for name in &taken {
4068                    self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
4069                }
4070                self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
4071                self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4072                self.emit(Opcode::Drop, &[]);
4073                self.emit(Opcode::Drop, &[]);
4074                self.destructure_rest(rest, decl)?;
4075            }
4076            // The source was only kept for a rest element.
4077            None => self.emit(Opcode::Drop, &[]),
4078        }
4079        Ok(())
4080    }
4081
4082    /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
4083    fn destructure_rest(
4084        &mut self,
4085        rest: &RestElement,
4086        decl: Option<VarDeclKind>,
4087    ) -> Result<(), SyntaxError> {
4088        match rest {
4089            RestElement::Pattern(pattern) => self.destructure(pattern, decl),
4090            // `[...a.b] = c` stores into a property.
4091            RestElement::Member(member) => {
4092                let pattern = Pattern {
4093                    kind: PatternKind::Member(member.clone()),
4094                    span: member.span,
4095                };
4096                self.destructure(&pattern, decl)
4097            }
4098        }
4099    }
4100
4101    /// The source range of a rest element, for error messages.
4102    fn rest_span(rest: &RestElement) -> Span {
4103        match rest {
4104            RestElement::Pattern(pattern) => pattern.span,
4105            RestElement::Member(member) => member.span,
4106        }
4107    }
4108
4109    /// Compile a function declaration and queue it for instantiation at scope
4110    /// entry.
4111    ///
4112    /// A declaration is visible before the statement that declares it, so the
4113    /// code that creates the function object belongs at the top of the enclosing
4114    /// scope, not at the declaration.
4115    fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
4116        let name = func.name.as_ref().expect("a declaration has a name");
4117        let function = self.compile_function(func)?;
4118        let pool_index = self.push_constant(Constant::Function(Box::new(function)));
4119        let target = self.hoist_target(&name.name);
4120        let block = self.cur().current_block;
4121        self.state().hoisted.push((block, target, pool_index));
4122        Ok(())
4123    }
4124
4125    /// Where a name lives, for a hoisted declaration.
4126    fn hoist_target(&self, name: &str) -> HoistTarget {
4127        let state = self.cur();
4128        if let Some(index) = state.args.iter().position(|a| a.name == name) {
4129            return HoistTarget::Arg(index as u32);
4130        }
4131        if let Some(index) = state.vars.iter().position(|v| v.name == name) {
4132            return HoistTarget::Loc(index as u32);
4133        }
4134        // A global function declaration is not a slot at all.
4135        HoistTarget::Global(name.to_string())
4136    }
4137
4138    // -- expressions -------------------------------------------------------
4139
4140    /// Compile one expression, recording where its instructions sit.
4141    ///
4142    /// The position is the node's operator when it has one and its first token
4143    /// otherwise, and it is restored on the way out so a parent's own instructions —
4144    /// which are emitted *after* its children — are blamed on the parent. Without the
4145    /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4146    fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4147        let saved = self.cur().cur_pos;
4148        // Only the node kinds the reference calls `emit_source_pos` for record a position:
4149        // the operator a node exists for, and a variable *read*, which the reference
4150        // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4151        // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4152        // start, a parenthesised group, an anonymous function expression — leaves the
4153        // previous position in place, because a table entry the reference never writes is
4154        // one we must not write either: the instruction that inherits a position (the
4155        // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4156        // report a more recent token than the reference does.
4157        let pos = expr.op_pos.or(match &expr.kind {
4158            ExprKind::Ident(ident) => Some(ident.span.start),
4159            _ => None,
4160        });
4161        match pos {
4162            Some(pos) => self.state().cur_pos = Some(pos),
4163            // A node the reference records nothing for: its own instructions stay
4164            // unpositioned, so they inherit whatever was written last — which is what an
4165            // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4166            // enclosing position instead would blame them on a token the reference has not
4167            // reached yet: a spread's `iterator_open` reports the expression it follows, and
4168            // a template's `to_propkey` the interpolation.
4169            None => self.state().cur_pos = None,
4170        }
4171        // Note a direct `eval` call before compiling it, because the *whole* function
4172        // is affected: an eval can name any binding the function declares, so every one
4173        // of them has to live in a cell for a closure it creates to capture it.
4174        if Self::is_direct_eval(expr) {
4175            // Every enclosing function is affected too: the eval sees the whole scope
4176            // chain, and a closure it creates can capture a binding of any of them.
4177            // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a
4178            // cell, because the closure the eval builds outlives the loop iteration.
4179            for state in &mut self.stack {
4180                state.has_direct_eval = true;
4181            }
4182            let block = self.cur().current_block;
4183            let in_params = self.cur().in_params;
4184            self.state()
4185                .pending_eval_sites
4186                .push((expr.span, block, in_params));
4187        }
4188        let result = self.expr_inner(expr);
4189        self.state().cur_pos = saved;
4190        result
4191    }
4192
4193    /// Record which bindings are in scope at a direct `eval` call.
4194    ///
4195    /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
4196    /// resolves names from a string at run time, so the only chance to pin down *which*
4197    /// slot a name means is here. Visibility is the lexical rule: a binding counts when
4198    /// its block is the current block, an enclosing one, or the function scope.
4199    fn materialize_eval_sites(&mut self) {
4200        let pending = std::mem::take(&mut self.state().pending_eval_sites);
4201        for (span, site_block, in_params) in pending {
4202            self.resolve_eval_site(span, site_block, in_params);
4203        }
4204    }
4205
4206    /// Resolve the bindings visible at one `eval` call.
4207    fn resolve_eval_site(&mut self, span: Span, site_block: u64, site_in_params: bool) {
4208        /// How near a binding is: function distance first, then block depth, then the
4209        /// later declaration (which shadows the earlier one in the same block).
4210        type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
4211
4212        // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
4213        // walked, innermost function first: a direct `eval` sees every enclosing
4214        // function's bindings, and none of them can be resolved at run time because the
4215        // runtime only has names to go on.
4216        let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
4217        let deepest = self.stack.len() - 1;
4218        for (level, state) in self.stack.iter().enumerate().rev() {
4219            let owner = (deepest - level) as u32;
4220            // The innermost function's block is the one the call sat in, which is not
4221            // the block the compiler is in now; the enclosing functions are still at
4222            // the point where this one was created.
4223            let here = if level == deepest {
4224                site_block
4225            } else {
4226                state.current_block
4227            };
4228            // The chain of live blocks, innermost first, with a depth for each. The walk
4229            // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
4230            // block can start at source offset zero.
4231            let mut live: Vec<(u64, usize)> = vec![(here, 0)];
4232            let mut block = here;
4233            while let Some(parent) = state
4234                .blocks
4235                .iter()
4236                .find(|candidate| candidate.key == block)
4237                .map(|candidate| candidate.parent)
4238                .filter(|parent| *parent != NO_PARENT)
4239                .filter(|parent| parent != &block)
4240            {
4241                live.push((parent, live.len()));
4242                block = parent;
4243            }
4244            let depth_of = |key: u64| {
4245                live.iter()
4246                    .find(|(candidate, _)| *candidate == key)
4247                    .map(|(_, depth)| *depth)
4248                    // The function scope is the outermost depth there is. A binding of a
4249                    // block this site is not inside lands here too, which pushes it
4250                    // behind every live one — the right answer: it is out of scope.
4251                    .unwrap_or(live.len())
4252            };
4253            for (index, arg) in state.args.iter().enumerate() {
4254                bindings.push((
4255                    (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
4256                    EvalVisible {
4257                        name: arg.name.clone(),
4258                        is_arg: true,
4259                        index: index as u32,
4260                        owner,
4261                    },
4262                ));
4263            }
4264            // A parameter list cannot see the body, so a body `var` is not a binding the
4265            // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
4266            // not let that eval write the body's `c`.
4267            let hides_body = if level == deepest {
4268                site_in_params
4269            } else {
4270                state.created_in_params
4271            };
4272            for (index, var) in state.vars.iter().enumerate() {
4273                let block = state
4274                    .var_block
4275                    .get(index)
4276                    .copied()
4277                    .unwrap_or(FUNCTION_SCOPE);
4278                if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
4279                    continue;
4280                }
4281                bindings.push((
4282                    (
4283                        owner as usize,
4284                        depth_of(block),
4285                        std::cmp::Reverse(index as u32),
4286                    ),
4287                    EvalVisible {
4288                        name: var.name.clone(),
4289                        is_arg: false,
4290                        index: index as u32,
4291                        owner,
4292                    },
4293                ));
4294            }
4295        }
4296        // Innermost function first, then innermost block, then the later declaration
4297        // (which shadows the earlier one within a block).
4298        bindings.sort_by_key(|(priority, _)| *priority);
4299        let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
4300        self.state().eval_sites.push(EvalSite {
4301            line: span.start.line,
4302            column: span.start.column,
4303            bindings,
4304        });
4305    }
4306
4307    /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
4308    ///
4309    /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
4310    /// a bare identifier callee counts.
4311    fn is_direct_eval(expr: &Expr) -> bool {
4312        matches!(
4313            &expr.kind,
4314            ExprKind::Call { callee, .. }
4315                if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
4316        )
4317    }
4318
4319    fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4320        match &expr.kind {
4321            ExprKind::Number(value) => self.push_number(*value),
4322            ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
4323            ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
4324            ExprKind::Null => self.emit(Opcode::Null, &[]),
4325            ExprKind::String(text) => self.push_string(text),
4326            ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
4327            ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
4328            ExprKind::This => self.this_expression(),
4329            ExprKind::NewTarget => self.new_target_expression(),
4330            ExprKind::Paren(inner) => self.expr(inner)?,
4331            ExprKind::Binary { op, left, right } => {
4332                self.expr(left)?;
4333                self.expr(right)?;
4334                self.emit(binary_opcode(*op), &[]);
4335            }
4336            ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
4337            ExprKind::Unary {
4338                op: UnaryOp::Minus,
4339                argument,
4340            } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
4341                let ExprKind::Number(value) = argument.unparen().kind else {
4342                    unreachable!("matched above")
4343                };
4344                // The reference folds a negative literal only when the negation is
4345                // exact in the integer range: `-1` becomes `push_minus1` and
4346                // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
4347                // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
4348                // `-Infinity`, not `Infinity` — and folding a fraction would change
4349                // which instruction the reference emits.
4350                let negated = -value;
4351                // `-2147483648` is deliberately excluded: its magnitude is one past
4352                // `i32::MAX`, so the reference sends it through the constant pool and
4353                // negates at run time instead.
4354                if value > 0.0
4355                    && negated == negated.trunc()
4356                    && negated >= -(i32::MAX as f64)
4357                    && negated < 0.0
4358                {
4359                    self.push_number(negated);
4360                } else {
4361                    self.push_number(value);
4362                    self.emit(Opcode::Neg, &[]);
4363                }
4364            }
4365            ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
4366            ExprKind::Conditional { test, cons, alt } => {
4367                let else_label = self.new_label();
4368                let end_label = self.new_label();
4369                self.expr(test)?;
4370                self.emit_jump(Opcode::IfFalse, else_label, &[]);
4371                self.expr(cons)?;
4372                self.emit_jump(Opcode::Goto, end_label, &[]);
4373                self.place_label(else_label);
4374                self.expr(alt)?;
4375                self.place_label(end_label);
4376            }
4377            ExprKind::Assign { op, target, value } => self.assign(*op, target, value)?,
4378            ExprKind::Update {
4379                op,
4380                argument,
4381                prefix,
4382            } => self.update(*op, argument, *prefix)?,
4383            ExprKind::Sequence(items) => {
4384                for (index, item) in items.iter().enumerate() {
4385                    self.expr(item)?;
4386                    if index + 1 != items.len() {
4387                        self.emit(Opcode::Drop, &[]);
4388                    }
4389                }
4390            }
4391            ExprKind::Call { .. } => self.chain_link_top(expr)?,
4392            ExprKind::Member { .. } => self.chain_link_top(expr)?,
4393            ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
4394            ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
4395            ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
4396            ExprKind::Template(template) => self.template_literal(template)?,
4397            ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
4398            ExprKind::New { callee, arguments } => {
4399                // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
4400                // The `dup` is not redundant: `call_constructor` takes the
4401                // constructor twice, once as the target and once as `new.target`,
4402                // which is what makes `new.target === C` inside the body.
4403                self.expr(callee)?;
4404                self.emit(Opcode::Dup, &[]);
4405                let args = arguments.as_deref().unwrap_or(&[]);
4406                if Self::has_spread(args) {
4407                    // `C C array`: the duplicated callee is already both the target
4408                    // and `new.target`, so no reordering is needed before `apply 1`.
4409                    self.argument_array(args)?;
4410                    self.emit(Opcode::Apply, &[Op::Int(1)]);
4411                    return Ok(());
4412                }
4413                for argument in args {
4414                    self.expr(argument)?;
4415                }
4416                self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
4417            }
4418            ExprKind::Class(class) => self.class_definition(class, true)?,
4419            ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
4420            ExprKind::Yield { argument, delegate } => {
4421                self.yield_expression(argument.as_deref(), *delegate)?
4422            }
4423            ExprKind::Await(argument) => self.await_expression(argument)?,
4424            ExprKind::RegExp { pattern, flags } => {
4425                // A literal is compiled *here*, at parse time, not when the line runs. The
4426                // spec is explicit that an invalid pattern is an early error (§12.9.4:
4427                // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
4428                // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
4429                // also validates `\p{…}` names: 163 conformance cases are patterns that have
4430                // to be rejected before any code runs.
4431                //
4432                // This is the whole reason the engine lives in its own crate rather than
4433                // inside `quickjs-pure`: the compiler could not depend on the interpreter
4434                // (`pure` depends on `compile`), but both need this.
4435                // The lexer already rejected an unknown or repeated flag, so an unparsable
4436                // flag string here would be a bug in the lexer rather than in the script;
4437                // fall back to the default flags instead of inventing a second message.
4438                let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
4439                let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
4440                    SyntaxError::new(
4441                        format!("invalid regular expression: {}", error.message),
4442                        expr.span,
4443                    )
4444                })?;
4445                // The tree is thrown away and rebuilt when the literal first runs: keeping it
4446                // would mean serialising the syntax tree into the function's constant pool,
4447                // and a literal is created once per evaluation of its expression anyway.
4448                let _ = parsed;
4449                // The pattern and its flags travel as two string constants; `regexp` builds
4450                // the object. A dedicated opcode (rather than a call to the constructor) is
4451                // what the reference does too, so that a literal never goes through the
4452                // public `RegExp` function and its string-coercion rules.
4453                self.push_string(&Wtf8::new(pattern));
4454                self.push_string(&Wtf8::new(flags));
4455                self.emit(Opcode::Regexp, &[]);
4456            }
4457            ExprKind::Arrow(func) => {
4458                let function = self.compile_function(func)?;
4459                let index = self.push_constant(Constant::Function(Box::new(function)));
4460                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4461            }
4462            ExprKind::Function(func) => {
4463                let function = self.compile_function_with_name(func, true)?;
4464                let index = self.push_constant(Constant::Function(Box::new(function)));
4465                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4466            }
4467            // `import.meta`: the host fills a per-module object at link time.
4468            ExprKind::ImportMeta => {
4469                self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
4470            }
4471            // `import("x")` compiles to a two-slot push followed by one opcode: the
4472            // specifier, then the options object (`undefined` here, since this compiler
4473            // does not accept the second argument yet).
4474            ExprKind::ImportCall(specifier) => {
4475                self.expr(specifier)?;
4476                self.emit(Opcode::Undefined, &[]);
4477                self.emit(Opcode::Import, &[]);
4478            }
4479            ExprKind::PrivateIn { name, object } => {
4480                // `#x in o`: the object, then the binding, then one opcode which decides what
4481                // to do with the second operand. A field's binding holds a symbol and the
4482                // answer is an own-property test; a method's holds a function and the answer
4483                // is a brand check — both live in `private_in`, so the compiler emits the
4484                // same instruction for either.
4485                self.expr(object)?;
4486                self.emit_var(VarAction::Get, &format!("#{}", name.name));
4487                self.emit(Opcode::PrivateIn, &[]);
4488            }
4489            _ => {
4490                return Err(SyntaxError::new(
4491                    "this expression form is not supported by the compiler yet",
4492                    expr.span,
4493                ));
4494            }
4495        }
4496        Ok(())
4497    }
4498
4499    /// Build one array holding the evaluated call arguments, which is how a call
4500    /// containing a spread is compiled: the reference does the same, building the
4501    /// list on the stack and handing it to `apply`.
4502    fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
4503        let elements: Vec<Option<ArrayElement>> = arguments
4504            .iter()
4505            .map(|argument| match &argument.unparen().kind {
4506                ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
4507                _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
4508            })
4509            .collect();
4510        self.array_literal(&elements, Span::default())
4511    }
4512
4513    /// Whether any argument is a spread, which is what selects the `apply` form.
4514    fn has_spread(arguments: &[Expr]) -> bool {
4515        arguments
4516            .iter()
4517            .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
4518    }
4519
4520    /// Compile `a${x}b`.
4521    ///
4522    /// A template is a `+` chain built left to right: the leading chunk (or an empty
4523    /// string when the template starts with a substitution), then for each
4524    /// substitution its value, `to_propkey` and `add`, then the following chunk when
4525    /// it is not empty. `to_propkey` is what makes a number or object substitute the
4526    /// way `ToString` would while leaving the result a string for `add` to
4527    /// concatenate.
4528    ///
4529    /// The chunk is an atom rather than a constant-pool string, because a non-empty
4530    /// chunk always lands where a value is pushed and `push_atom_value` is the
4531    /// instruction the reference uses for it; the empty first chunk has its own
4532    /// zero-byte form.
4533    fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
4534        let first = template.quasis.first();
4535        match first.and_then(|quasi| quasi.cooked.clone()) {
4536            Some(text) if !text.is_empty() => {
4537                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4538            }
4539            // Either the template begins with a substitution, or the chunk is
4540            // empty — in both cases the chain needs a string to start from.
4541            _ => self.emit(Opcode::PushEmptyString, &[]),
4542        }
4543        for (index, expression) in template.expressions.iter().enumerate() {
4544            self.expr(expression)?;
4545            self.emit(Opcode::ToPropkey, &[]);
4546            self.emit(Opcode::Add, &[]);
4547            if let Some(text) = template
4548                .quasis
4549                .get(index + 1)
4550                .and_then(|quasi| quasi.cooked.clone())
4551                && !text.is_empty()
4552            {
4553                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4554                self.emit(Opcode::Add, &[]);
4555            }
4556        }
4557        Ok(())
4558    }
4559
4560    /// Compile an object literal.
4561    ///
4562    /// The object is built in place: `object` pushes it, and each property leaves it
4563    /// on the stack with one field more, so no temporary is needed and later
4564    /// properties can overwrite earlier ones.
4565    ///
4566    /// The instruction depends on *how* the property was written, not on what kind
4567    /// of value it holds:
4568    ///
4569    /// | source | instruction |
4570    /// |---|---|
4571    /// | `{ a: v }` | `define_field a` |
4572    /// | `{ __proto__: v }` | `set_proto` |
4573    /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
4574    /// | `{ m() {} }` | `define_method m,4` |
4575    /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
4576    /// | `{ [k]() {} }` | `define_method_computed 4` |
4577    /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
4578    ///
4579    /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
4580    /// key itself, which is why the trailing `drop` is absent there too.
4581    /// `tag`…``: a call whose first argument is the call site's template object.
4582    ///
4583    /// The template object is a frozen array of the cooked chunks with a frozen `raw`
4584    /// array beside it, so `String.raw` can read the source text back. It is a constant
4585    /// because its contents never change; the reference builds one per call site and
4586    /// reuses it, while this builds one per evaluation, which only `tag` code that
4587    /// compares template objects across calls could tell apart.
4588    fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
4589        let cooked = quasi
4590            .quasis
4591            .iter()
4592            .map(|chunk| chunk.cooked.clone())
4593            .collect();
4594        let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
4595        let index = self.push_constant(Constant::Template { cooked, raw });
4596        let count = quasi.expressions.len() + 1;
4597        // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
4598        if let ExprKind::Member {
4599            object, property, ..
4600        } = &tag.unparen().kind
4601        {
4602            self.expr(object)?;
4603            match property {
4604                MemberProp::Ident(name) => {
4605                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
4606                }
4607                MemberProp::Computed(key) => {
4608                    self.expr(key)?;
4609                    self.emit(Opcode::GetArrayEl2, &[]);
4610                }
4611                MemberProp::Private(name) => {
4612                    let binding = format!("#{}", name.name);
4613                    let (kind, _) = self.private_use(&binding, tag.span)?;
4614                    self.private_callee(&binding, kind)?;
4615                }
4616            }
4617            self.emit(Opcode::PushConst, &[Op::Const(index)]);
4618            for expression in &quasi.expressions {
4619                self.expr(expression)?;
4620            }
4621            self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
4622            return Ok(());
4623        }
4624        self.expr(tag)?;
4625        self.emit(Opcode::PushConst, &[Op::Const(index)]);
4626        for expression in &quasi.expressions {
4627            self.expr(expression)?;
4628        }
4629        self.emit(Opcode::Call, &[Op::Int(count as i32)]);
4630        Ok(())
4631    }
4632
4633    fn object_literal(
4634        &mut self,
4635        properties: &[ObjectProperty],
4636        span: Span,
4637    ) -> Result<(), SyntaxError> {
4638        self.emit(Opcode::Object, &[]);
4639        for property in properties {
4640            match property {
4641                ObjectProperty::Spread(value) => {
4642                    // `copy_data_properties` takes the target, the source and an
4643                    // exclusion list; a literal `null` means "exclude nothing".
4644                    // Flag bit 1 copies symbols, bits 2/5 pick the source and the
4645                    // exclusion list by stack offset.
4646                    self.expr(spread_argument(value))?;
4647                    self.emit(Opcode::Null, &[]);
4648                    self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4649                    self.emit(Opcode::Drop, &[]);
4650                    self.emit(Opcode::Drop, &[]);
4651                }
4652                ObjectProperty::Property {
4653                    key,
4654                    value,
4655                    kind,
4656                    shorthand,
4657                    span: property_span,
4658                } => match key {
4659                    PropName::Computed(key_expr) => {
4660                        self.expr(key_expr)?;
4661                        match kind {
4662                            PropertyKind::Value => {
4663                                self.emit(Opcode::ToPropkey, &[]);
4664                                self.expr(value)?;
4665                                self.set_name_if_anonymous_computed(value);
4666                                self.emit(Opcode::DefineArrayEl, &[]);
4667                                // `define_array_el` leaves the object and the key;
4668                                // the key is no longer needed.
4669                                self.emit(Opcode::Drop, &[]);
4670                            }
4671                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4672                                self.emit_method_function(value)?;
4673                                self.emit(
4674                                    Opcode::DefineMethodComputed,
4675                                    &[Op::Int(define_method_flags(*kind))],
4676                                );
4677                            }
4678                        }
4679                    }
4680                    PropName::Literal(key) => {
4681                        let name = self.property_key_text(key, *property_span)?;
4682                        match kind {
4683                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4684                                self.emit_method_function(value)?;
4685                                self.emit(
4686                                    Opcode::DefineMethod,
4687                                    &[
4688                                        Op::Atom(Atom::from_wtf8(&name)),
4689                                        Op::Int(define_method_flags(*kind)),
4690                                    ],
4691                                );
4692                            }
4693                            PropertyKind::Value => {
4694                                self.expr(value)?;
4695                                // `{__proto__: x}` sets the prototype instead of
4696                                // creating a property; the shorthand `{__proto__}`
4697                                // is an ordinary property and does not.
4698                                if name == "__proto__" && !shorthand {
4699                                    self.emit(Opcode::SetProto, &[]);
4700                                } else {
4701                                    self.set_name_if_anonymous(value, &name);
4702                                    self.emit(
4703                                        Opcode::DefineField,
4704                                        &[Op::Atom(Atom::from_wtf8(&name))],
4705                                    );
4706                                }
4707                            }
4708                        }
4709                    }
4710                    PropName::Private(_) => {
4711                        return Err(SyntaxError::new(
4712                            "private names are not valid in object literals",
4713                            *property_span,
4714                        ));
4715                    }
4716                },
4717            }
4718        }
4719        let _ = span;
4720        Ok(())
4721    }
4722
4723    /// Emit the function a method/accessor property defines.
4724    fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
4725        self.expr(value)
4726    }
4727
4728    /// The name a literal property key contributes.
4729    ///
4730    /// String keys are used as written. A numeric key is converted the way
4731    /// `ToString` would convert it, because the atom is made from that spelling:
4732    /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
4733    fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
4734        match key {
4735            PropKey::Str(text) => Ok(text.clone()),
4736            PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
4737        }
4738    }
4739
4740    /// Compile an optional chain.
4741    ///
4742    /// `?.` short-circuits the *whole remaining spine*, not just its own link:
4743    /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
4744    /// `undefined`. So the chain is compiled with one end label and every guard
4745    /// jumps to it. The parser hands us the extent of that spine as an
4746    /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
4747    /// exactly the scope the label has to cover.
4748    fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
4749        let end = self.new_label();
4750        self.chain_link(inner, end)?;
4751        self.place_label(end);
4752        Ok(())
4753    }
4754
4755    /// A member access or call reached from outside any optional chain.
4756    ///
4757    /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
4758    /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
4759    /// still created because [`Self::chain_link`] takes it, and placing it at the
4760    /// end is a no-op that keeps a single code path.
4761    fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4762        let end = self.new_label();
4763        self.chain_link(expr, end)?;
4764        self.place_label(end);
4765        Ok(())
4766    }
4767
4768    /// One link of a chain, where `end` is the label a `?.` guard jumps to.
4769    fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
4770        match &expr.kind {
4771            ExprKind::Member {
4772                object,
4773                property,
4774                optional,
4775            } => {
4776                // `super.x` is not a lookup on a value: it starts at the home object's
4777                // prototype and keeps `this` as the receiver, so it cannot go through
4778                // `chain_link` and the ordinary field read.
4779                if matches!(object.unparen().kind, ExprKind::SuperProp) {
4780                    self.super_base();
4781                    match property {
4782                        MemberProp::Ident(name) => self.emit(
4783                            Opcode::PushAtomValue,
4784                            &[Op::Atom(Atom::from_text(&name.name))],
4785                        ),
4786                        MemberProp::Computed(index) => self.expr(index)?,
4787                        MemberProp::Private(_) => {
4788                            return Err(SyntaxError::new(
4789                                "private fields are not supported by the compiler yet",
4790                                expr.span,
4791                            ));
4792                        }
4793                    }
4794                    self.emit(Opcode::GetSuperValue, &[]);
4795                    return Ok(());
4796                }
4797                self.chain_link(object, end)?;
4798                if *optional {
4799                    self.optional_guard(end);
4800                }
4801                match property {
4802                    // `.length` has its own opcode. The reference emits it for every
4803                    // object, not just arrays, so a name-based rule is right and
4804                    // cheaper than the generic field read.
4805                    MemberProp::Ident(name) if name.name == "length" => {
4806                        self.emit(Opcode::GetLength, &[]);
4807                    }
4808                    MemberProp::Ident(name) => {
4809                        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
4810                    }
4811                    MemberProp::Computed(index) => {
4812                        self.expr(index)?;
4813                        self.emit(Opcode::GetArrayEl, &[]);
4814                    }
4815                    MemberProp::Private(name) => {
4816                        // The binding comes from the class scope, so a read from outside the
4817                        // class cannot name it at all. `?.` checks the object, not the field:
4818                        // `o?.#x` guards on `o` being nullish.
4819                        let binding = format!("#{}", name.name);
4820                        let (kind, _) = self.private_use(&binding, expr.span)?;
4821                        self.private_load(&binding, kind, expr.span)?;
4822                    }
4823                }
4824                Ok(())
4825            }
4826            ExprKind::Call {
4827                callee,
4828                arguments,
4829                optional,
4830            } => {
4831                // `o.m(args)` has to pass `o` as `this`, which a plain `call`
4832                // cannot: it reads the function and then calls it with no
4833                // receiver at all. The reference's answer is to keep the object
4834                // under the function value — `get_field2` reads a field and leaves
4835                // its base in place — and to use `call_method`, which takes the
4836                // receiver from the stack. Missing this does not just cost an
4837                // instruction, it loses the `this` binding.
4838                if let ExprKind::Member {
4839                    object,
4840                    property,
4841                    optional: member_optional,
4842                } = &callee.unparen().kind
4843                {
4844                    // `super.m()` reads the method off the home object's prototype but
4845                    // calls it with `this`, so the receiver goes under the read instead of
4846                    // being replaced by it.
4847                    if matches!(object.unparen().kind, ExprKind::SuperProp) {
4848                        self.super_base();
4849                        match property {
4850                            MemberProp::Ident(name) => self.emit(
4851                                Opcode::PushAtomValue,
4852                                &[Op::Atom(Atom::from_text(&name.name))],
4853                            ),
4854                            MemberProp::Computed(index) => self.expr(index)?,
4855                            MemberProp::Private(_) => {
4856                                return Err(SyntaxError::new(
4857                                    "private fields are not supported by the compiler yet",
4858                                    expr.span,
4859                                ));
4860                            }
4861                        }
4862                        // The two-output form would drop the receiver; this one replaces
4863                        // the prototype and the key, leaving `this` underneath.
4864                        self.emit(Opcode::GetArrayEl, &[]);
4865                        if Self::has_spread(arguments) {
4866                            self.argument_array(arguments)?;
4867                            self.emit(Opcode::Perm3, &[]);
4868                            self.emit(Opcode::Apply, &[Op::Int(0)]);
4869                            return Ok(());
4870                        }
4871                        for argument in arguments {
4872                            self.expr(argument)?;
4873                        }
4874                        self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4875                        return Ok(());
4876                    }
4877                    self.chain_link(object, end)?;
4878                    if *member_optional {
4879                        self.optional_guard(end);
4880                    }
4881                    match property {
4882                        MemberProp::Ident(name) => {
4883                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4884                        }
4885                        MemberProp::Computed(index) => {
4886                            self.expr(index)?;
4887                            // The key is not needed after the read, so this is the
4888                            // two-output form: object, value.
4889                            self.emit(Opcode::GetArrayEl2, &[]);
4890                        }
4891                        MemberProp::Private(name) => {
4892                            // The receiver is already under the callee, which is exactly the
4893                            // shape `call_method` and `apply` want — so nothing is dropped.
4894                            let binding = format!("#{}", name.name);
4895                            let (kind, _) = self.private_use(&binding, expr.span)?;
4896                            self.private_callee(&binding, kind)?;
4897                        }
4898                    }
4899                    if Self::has_spread(arguments) {
4900                        // Stack is `obj func`; the array goes on top, then `perm3`
4901                        // reorders to the `func this array` that `apply` wants.
4902                        self.argument_array(arguments)?;
4903                        self.emit(Opcode::Perm3, &[]);
4904                        self.emit(Opcode::Apply, &[Op::Int(0)]);
4905                        return Ok(());
4906                    }
4907                    for argument in arguments {
4908                        self.expr(argument)?;
4909                    }
4910                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4911                    return Ok(());
4912                }
4913                // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
4914                // with `get_field2` so the base stays under it, and on the short-circuit
4915                // path pushes an extra `undefined` as a placeholder receiver — the call
4916                // then throws, which is what calling a missing optional chain should do.
4917                if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
4918                    && let ExprKind::Member {
4919                        object,
4920                        property,
4921                        optional: member_optional,
4922                    } = &inner.unparen().kind
4923                {
4924                    let call = self.new_label();
4925                    // A guard target of its own: the outer `end` skips the whole
4926                    // expression, and a short-circuited receiver still has to reach the
4927                    // call so that calling it throws.
4928                    let short = self.new_label();
4929                    self.chain_link(object, end)?;
4930                    if *member_optional {
4931                        self.optional_guard(short);
4932                    }
4933                    match property {
4934                        MemberProp::Ident(name) => {
4935                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4936                        }
4937                        MemberProp::Computed(index) => {
4938                            self.expr(index)?;
4939                            self.emit(Opcode::GetArrayEl2, &[]);
4940                        }
4941                        MemberProp::Private(name) => {
4942                            let binding = format!("#{}", name.name);
4943                            let (kind, _) = self.private_use(&binding, expr.span)?;
4944                            self.private_callee(&binding, kind)?;
4945                        }
4946                    }
4947                    self.emit_jump(Opcode::Goto, call, &[]);
4948                    self.place_label(short);
4949                    self.emit(Opcode::Undefined, &[]);
4950                    self.place_label(call);
4951                    if Self::has_spread(arguments) {
4952                        self.argument_array(arguments)?;
4953                        self.emit(Opcode::Perm3, &[]);
4954                        self.emit(Opcode::Apply, &[Op::Int(0)]);
4955                        return Ok(());
4956                    }
4957                    for argument in arguments {
4958                        self.expr(argument)?;
4959                    }
4960                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4961                    return Ok(());
4962                }
4963                self.chain_link(callee, end)?;
4964                if *optional {
4965                    self.optional_guard(end);
4966                }
4967                if Self::has_spread(arguments) {
4968                    // `func array -> func undefined array`, which is the plain-call
4969                    // form of `apply`: the receiver is `undefined`.
4970                    self.argument_array(arguments)?;
4971                    self.emit(Opcode::Undefined, &[]);
4972                    self.emit(Opcode::Swap, &[]);
4973                    self.emit(Opcode::Apply, &[Op::Int(0)]);
4974                    return Ok(());
4975                }
4976                for argument in arguments {
4977                    self.expr(argument)?;
4978                }
4979                self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
4980                Ok(())
4981            }
4982            _ => self.expr(expr),
4983        }
4984    }
4985
4986    /// Compile `expr` as a tail call when it is one, reporting whether it was.
4987    ///
4988    /// `tail_call` reuses the current frame instead of pushing a new one, so a
4989    /// tail-recursive function runs in constant stack space. It also has to be the
4990    /// *last* thing the function does, which is why only a `return` reaches here.
4991    fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
4992        let ExprKind::Call {
4993            callee,
4994            arguments,
4995            optional: false,
4996        } = &expr.unparen().kind
4997        else {
4998            return Ok(false);
4999        };
5000        // A spread call has no tail form: `tail_call` takes its arguments one at a time off
5001        // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
5002        // as an ordinary call costs the one frame the optimisation was saving and keeps the
5003        // semantics — the alternative was reaching the spread expression below and failing
5004        // with "this expression form is not supported", which is how `return super.m(...a)`
5005        // stopped compiling. Checked before anything is emitted, because the decision cannot
5006        // be taken back once `super_base` or a `get_field2` is on the stack.
5007        if Self::has_spread(arguments) {
5008            return Ok(false);
5009        }
5010        let end = self.new_label();
5011        if let ExprKind::Member {
5012            object,
5013            property,
5014            optional: false,
5015        } = &callee.unparen().kind
5016        {
5017            // `super.m()` in tail position is still an ordinary method call with `this`
5018            // as the receiver; only the read of the method differs.
5019            if matches!(object.unparen().kind, ExprKind::SuperProp) {
5020                self.super_base();
5021                match property {
5022                    MemberProp::Ident(name) => self.emit(
5023                        Opcode::PushAtomValue,
5024                        &[Op::Atom(Atom::from_text(&name.name))],
5025                    ),
5026                    MemberProp::Computed(index) => self.expr(index)?,
5027                    MemberProp::Private(_) => return Ok(false),
5028                }
5029                self.emit(Opcode::GetArrayEl, &[]);
5030                for argument in arguments {
5031                    self.expr(argument)?;
5032                }
5033                self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5034                self.place_label(end);
5035                return Ok(true);
5036            }
5037            self.chain_link(object, end)?;
5038            match property {
5039                MemberProp::Ident(name) => {
5040                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5041                }
5042                MemberProp::Computed(index) => {
5043                    self.expr(index)?;
5044                    self.emit(Opcode::GetArrayEl2, &[]);
5045                }
5046                MemberProp::Private(_) => return Ok(false),
5047            }
5048            for argument in arguments {
5049                self.expr(argument)?;
5050            }
5051            self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5052            self.place_label(end);
5053            return Ok(true);
5054        }
5055        self.chain_link(callee, end)?;
5056        for argument in arguments {
5057            self.expr(argument)?;
5058        }
5059        self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
5060        self.place_label(end);
5061        Ok(true)
5062    }
5063
5064    /// The `?.` guard: keep the value if it is neither null nor undefined,
5065    /// otherwise replace it with `undefined` and leave the whole chain.
5066    fn optional_guard(&mut self, end: Label) {
5067        let cont = self.new_label();
5068        self.emit(Opcode::Dup, &[]);
5069        self.emit(Opcode::IsUndefinedOrNull, &[]);
5070        self.emit_jump(Opcode::IfFalse, cont, &[]);
5071        self.emit(Opcode::Drop, &[]);
5072        self.emit(Opcode::Undefined, &[]);
5073        self.emit_jump(Opcode::Goto, end, &[]);
5074        self.place_label(cont);
5075    }
5076
5077    fn push_number(&mut self, value: f64) {
5078        // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
5079        // goes into the constant pool.
5080        if value == value.trunc() && value.abs() <= i32::MAX as f64 {
5081            let int = value as i32;
5082            if (-1..=7).contains(&int) {
5083                self.emit(Opcode::PushI32, &[Op::Int(int)]);
5084                return;
5085            }
5086            if (-128..=127).contains(&int) {
5087                self.emit(Opcode::PushI8, &[Op::Int(int)]);
5088                return;
5089            }
5090            if (-32768..=32767).contains(&int) {
5091                self.emit(Opcode::PushI16, &[Op::Int(int)]);
5092                return;
5093            }
5094            self.emit(Opcode::PushI32, &[Op::Int(int)]);
5095            return;
5096        }
5097        let index = self.push_constant(Constant::Number(value));
5098        self.emit(Opcode::PushConst, &[Op::Const(index)]);
5099    }
5100
5101    /// Push a `BigInt` literal.
5102    ///
5103    /// A value that fits an `i32` uses the immediate form, which is what the reference
5104    /// emits too; anything larger goes into the constant pool, because the operand of
5105    /// `push_bigint` is only four bytes wide.
5106    fn push_bigint(&mut self, digits: &str, radix: u32) {
5107        if radix == 10
5108            && let Ok(value) = digits.parse::<i64>()
5109            && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
5110        {
5111            self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
5112            return;
5113        }
5114        let index = self.push_constant(Constant::BigInt {
5115            digits: digits.to_string(),
5116            radix,
5117        });
5118        self.emit(Opcode::PushConst, &[Op::Const(index)]);
5119    }
5120
5121    fn push_string(&mut self, text: &Wtf8) {
5122        if text.is_empty() {
5123            self.emit(Opcode::PushEmptyString, &[]);
5124            return;
5125        }
5126        self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
5127    }
5128
5129    /// Name an anonymous function from the binding it is assigned to.
5130    ///
5131    /// `var f = function(){}` produces a function whose `name` is `f`, which the
5132    /// runtime cannot know without being told: the function object is created
5133    /// before the store. `set_name` carries the name across.
5134    fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
5135        if value.is_anonymous_function_definition() {
5136            self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
5137        }
5138    }
5139
5140    /// The same, for a computed key: the name comes from the value on the stack
5141    /// rather than from an atom, so a different instruction carries it.
5142    fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
5143        if value.is_anonymous_function_definition() {
5144            self.emit(Opcode::SetNameComputed, &[]);
5145        }
5146    }
5147
5148    /// Compile a function body that exists only in the compiler's head — a class's
5149    /// implicit constructor or its field initialiser.
5150    ///
5151    /// Everything structural is the same as a written function: a fresh `FnState`, its
5152    /// own body block, and resolution while the frame is still on the stack. Only the
5153    /// statements differ.
5154    fn compile_synthetic_function(
5155        &mut self,
5156        name: &str,
5157        strict: bool,
5158        span: Span,
5159        body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
5160    ) -> Result<CompiledFunction, SyntaxError> {
5161        let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
5162        state.span = Some((span.start.offset as usize, span.end.offset as usize));
5163        state.strict = strict;
5164        state.created_in_block = self.cur().current_block;
5165        state.with_names = self.cur().with_names.clone();
5166        state.line = span.start.line;
5167        state.column = span.start.column;
5168        let depth = self.stack.len();
5169        self.stack.push(state);
5170        let body_key = span.start.offset as u64;
5171        self.push_block(body_key, NO_PARENT);
5172        self.state().body_block = body_key;
5173        let result = (|| {
5174            self.emit_scope_enter(body_key);
5175            body(self)?;
5176            if self.end_is_reachable() {
5177                self.emit(Opcode::ReturnUndef, &[]);
5178            }
5179            Ok(())
5180        })();
5181        if result.is_err() {
5182            self.stack.truncate(depth);
5183            return result.map(|()| unreachable!());
5184        }
5185        Ok(self.finish_current())
5186    }
5187
5188    /// The implicit return of a class constructor.
5189    ///
5190    /// A constructor that falls off the end initialises its instance fields first, and a
5191    /// derived one returns `this` — which is what makes `new D()` the object `super()`
5192    /// built rather than `undefined`.
5193    fn emit_class_constructor_tail(&mut self) {
5194        match self.cur().ctor_kind {
5195            CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
5196            // Nothing to install: a base constructor did it in its prologue and a derived
5197            // one at each `super()` site, which is where `this` first exists.
5198            CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
5199            CtorKind::Derived => {
5200                // `get_loc_check` rather than `get_loc`: reaching the end without ever
5201                // running `super()` is a ReferenceError, not `undefined`.
5202                self.emit_var(VarAction::Get, "this");
5203                self.emit(Opcode::Return, &[]);
5204            }
5205        }
5206    }
5207
5208    /// `yield expr` / `yield* expr`.
5209    ///
5210    /// The suspension itself is one instruction: the value is on the stack, `yield` hands
5211    /// it to the caller and parks the frame. On resume the stack holds the value the
5212    /// caller passed *and* a "magic" number saying which method resumed it — `next`
5213    /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
5214    /// `if_false <continue>` asks whether this was an ordinary `next`:
5215    ///
5216    /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
5217    /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
5218    ///   and uses the value sitting under the magic number.
5219    ///
5220    /// A `throw` never reaches here: the interpreter unwinds instead (see
5221    /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
5222    fn yield_expression(
5223        &mut self,
5224        argument: Option<&Expr>,
5225        delegate: bool,
5226    ) -> Result<(), SyntaxError> {
5227        if delegate {
5228            return self.yield_star(argument);
5229        }
5230        // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
5231        // does the same for the `return(v)` that can resume it — which is why an async
5232        // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
5233        // generator's is just `yield`.
5234        let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
5235        match argument {
5236            Some(value) => self.expr(value)?,
5237            None => self.emit(Opcode::Undefined, &[]),
5238        }
5239        if is_async {
5240            self.emit(Opcode::Await, &[]);
5241            self.state().has_await = true;
5242        }
5243        self.emit(Opcode::Yield, &[]);
5244        let resume = self.new_label();
5245        self.emit_jump(Opcode::IfFalse, resume, &[]);
5246        // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
5247        // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
5248        // finished the generator and never ran the `finally`.
5249        if is_async {
5250            self.emit(Opcode::Await, &[]);
5251        }
5252        self.emit_unwind_for_return(true);
5253        self.emit(Opcode::ReturnAsync, &[]);
5254        self.place_label(resume);
5255        // Nothing is emitted here: the value the caller passed to `next` *is* the value
5256        // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
5257        // it through the ordinary expression-statement discard.
5258        Ok(())
5259    }
5260
5261    /// `yield* iterable`.
5262    ///
5263    /// The shape is the reference's, and it is a fall-through chain rather than a
5264    /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
5265    /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
5266    /// the inner iterator and finishes, `throw` forwards the exception into it and
5267    /// continues only if it has a `throw` method.
5268    ///
5269    /// The stack is `iter next catch value` throughout, `catch` being the offset
5270    /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
5271    fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
5272        match argument {
5273            Some(value) => self.expr(value)?,
5274            // The parser rejects a bare `yield*`, so this is unreachable in practice.
5275            None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
5276        }
5277        // `for await of` is the same protocol as `for of` with two differences that matter
5278        // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
5279        // every `next()` result is a promise the delegate has to await.
5280        let is_async = self.cur().kind.is_async();
5281        self.emit(
5282            if is_async {
5283                Opcode::ForAwaitOfStart
5284            } else {
5285                Opcode::ForOfStart
5286            },
5287            &[],
5288        );
5289        self.emit(Opcode::Drop, &[]);
5290        self.emit(Opcode::Undefined, &[]);
5291        self.emit(Opcode::Undefined, &[]);
5292        let next = self.new_label();
5293        let resume = self.new_label();
5294        let finished = self.new_label();
5295        let rethrow = self.new_label();
5296        let throw_no_method = self.new_label();
5297        let done = self.new_label();
5298        self.place_label(next);
5299        self.emit(Opcode::IteratorNext, &[]);
5300        if is_async {
5301            self.emit(Opcode::Await, &[]);
5302            self.state().has_await = true;
5303        }
5304        self.emit(Opcode::IteratorCheckObject, &[]);
5305        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5306        self.emit_jump(Opcode::IfTrue, done, &[]);
5307        // The suspension. `resume` is both the label the return path jumps back to in order
5308        // to yield one more value and where the caller's answer arrives, as the value
5309        // followed by the magic number.
5310        //
5311        // The two forms differ in what they hand the suspension: `yield_star` takes the
5312        // result object itself, `async_yield_star` takes `.value`, because an async
5313        // generator awaits and re-wraps whatever it yields.
5314        self.place_label(resume);
5315        if is_async {
5316            self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5317            self.emit(Opcode::AsyncYieldStar, &[]);
5318        } else {
5319            self.emit(Opcode::YieldStar, &[]);
5320        }
5321        self.emit(Opcode::Dup, &[]);
5322        self.emit_jump(Opcode::IfTrue, rethrow, &[]);
5323        self.emit(Opcode::Drop, &[]);
5324        self.emit_jump(Opcode::Goto, next, &[]);
5325
5326        // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
5327        self.place_label(rethrow);
5328        self.emit(Opcode::PushI32, &[Op::Int(2)]);
5329        self.emit(Opcode::StrictEq, &[]);
5330        self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
5331        // A `return` closes the inner iterator; if it had none, the delegate simply
5332        // finishes with the requested value. In an async generator both the call and its
5333        // result are awaited, because the inner `return` may itself be async.
5334        if is_async {
5335            self.emit(Opcode::Await, &[]);
5336        }
5337        self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
5338        self.emit_jump(Opcode::IfTrue, finished, &[]);
5339        if is_async {
5340            self.emit(Opcode::Await, &[]);
5341        }
5342        self.emit(Opcode::IteratorCheckObject, &[]);
5343        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5344        self.emit_jump(Opcode::IfFalse, resume, &[]);
5345        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5346        self.place_label(finished);
5347        self.emit(Opcode::Nip, &[]);
5348        self.emit(Opcode::Nip, &[]);
5349        self.emit(Opcode::Nip, &[]);
5350        // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
5351        // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
5352        // awaits the value in an async generator and then runs the same `finally`/iterator
5353        // unwinding a written `return` would. Skipping the unwinding made
5354        // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
5355        if is_async {
5356            self.emit(Opcode::Await, &[]);
5357        }
5358        self.emit_unwind_for_return(true);
5359        self.emit(Opcode::ReturnAsync, &[]);
5360
5361        // `throw(e)`: forward it into the inner iterator.
5362        self.place_label(throw_no_method);
5363        self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
5364        let no_throw = self.new_label();
5365        self.emit_jump(Opcode::IfTrue, no_throw, &[]);
5366        if is_async {
5367            self.emit(Opcode::Await, &[]);
5368        }
5369        self.emit(Opcode::IteratorCheckObject, &[]);
5370        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5371        self.emit_jump(Opcode::IfFalse, resume, &[]);
5372        self.emit_jump(Opcode::Goto, done, &[]);
5373        // No `throw` method: close the iterator, then report the spec's TypeError. The
5374        // `if_true` before the `await` is the reference's shape — the flag it consumes is
5375        // what `iterator_call` leaves behind, and a close that *did* find no `return`
5376        // method has nothing to await.
5377        self.place_label(no_throw);
5378        self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
5379        let no_close = self.new_label();
5380        self.emit_jump(Opcode::IfTrue, no_close, &[]);
5381        if is_async {
5382            self.emit(Opcode::Await, &[]);
5383        }
5384        self.place_label(no_close);
5385        self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
5386
5387        // The inner iterator finished: the delegate's value is the `yield*` expression's
5388        // value, so it is left on the stack for whatever consumes it.
5389        self.place_label(done);
5390        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5391        self.emit(Opcode::Nip, &[]);
5392        self.emit(Opcode::Nip, &[]);
5393        self.emit(Opcode::Nip, &[]);
5394        Ok(())
5395    }
5396
5397    /// `await expr`: exactly one instruction.
5398    ///
5399    /// No resume-magic branch follows it. The reference's `await` leaves a single value
5400    /// on the stack and completion is signalled by the `return_async` at the end of the
5401    /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
5402    /// reference never emits, and a `for await` loop — which reaches `await` through the
5403    /// same opcode — would then spill a value the loop's unpacking does not expect.
5404    fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
5405        self.expr(argument)?;
5406        self.emit(Opcode::Await, &[]);
5407        self.state().has_await = true;
5408        Ok(())
5409    }
5410
5411    /// The `super` base: the receiver followed by the home object's prototype.
5412    ///
5413    /// Everything `super` does needs both. A *read* starts at the prototype but reports
5414    /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
5415    /// prototype but calls it with the receiver.
5416    fn super_base(&mut self) {
5417        self.this_expression();
5418        self.home_object();
5419        self.emit(Opcode::GetSuper, &[]);
5420    }
5421
5422    /// `[[HomeObject]]` as `super` sees it.
5423    ///
5424    /// A method, a constructor and a field initialiser each carry one — `set_home_object`
5425    /// put it there — so for them the special object *is* the answer. An arrow and a
5426    /// static block have none: they read the enclosing function's, which has to be
5427    /// materialised into a local, exactly as `this` is for an arrow.
5428    ///
5429    /// The name matches what the reference stores, so the disassembly agrees; it is not a
5430    /// name any program can write.
5431    fn home_object(&mut self) {
5432        if !self.cur().is_arrow {
5433            self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
5434            return;
5435        }
5436        if let Some(target) = self.enclosing_function() {
5437            self.state_at(target).needs_home_object_local = true;
5438            self.declare_at(target, HOME_OBJECT);
5439        }
5440        self.emit_var(VarAction::Get, HOME_OBJECT);
5441    }
5442
5443    /// `super(args)`: construct the parent class and adopt the result as `this`.
5444    ///
5445    /// The parent is the prototype of the constructor that is running, which is exactly
5446    /// what `extends` set up. `new.target` is passed through unchanged so that
5447    /// `new.target` inside the parent is the class actually being constructed.
5448    fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5449        self.active_func_expression();
5450        self.emit(Opcode::GetSuper, &[]);
5451        self.new_target_expression();
5452        if Self::has_spread(arguments) {
5453            self.argument_array(arguments)?;
5454            self.emit(Opcode::Apply, &[Op::Int(1)]);
5455        } else {
5456            for argument in arguments {
5457                self.expr(argument)?;
5458            }
5459            self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
5460        }
5461        // The value stays on the stack: `super()` is an expression, and a derived
5462        // constructor's `this` may only be initialised once.
5463        self.emit(Opcode::Dup, &[]);
5464        self.emit_var(VarAction::PutInitChecked, "this");
5465        // Instance fields are installed here, not at the top of the body: a derived
5466        // constructor has no `this` to install them on until `super()` returns. The
5467        // reference emits the same call at every `super()` site.
5468        self.call_field_initialiser();
5469        Ok(())
5470    }
5471
5472    /// `this` as a local, which every class constructor and field initialiser needs.
5473    ///
5474    /// The reference materialises the receiver into a local rather than reading
5475    /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
5476    /// and a field initialiser has to see the final value.
5477    fn begin_this_local(&mut self) {
5478        self.declare_hidden_local("this", VarKind::Normal);
5479        self.emit(Opcode::PushThis, &[]);
5480        self.emit_var(VarAction::Put, "this");
5481        // The store is already at the top of the body, so `provide_this_local` has
5482        // nothing left to prepend. Without this the initialiser ended up with
5483        // `push_this; put_loc0 this` twice whenever the class also held a field
5484        // initialiser whose body read `this` through an arrow.
5485        self.state().has_this_prologue = true;
5486    }
5487
5488    /// Compile a constructor the class wrote.
5489    ///
5490    /// The flags have to be in place before the body is compiled, but
5491    /// `compile_function_with_name` creates its own state — so the caller's state is
5492    /// marked instead and the new one inherits it. That is the same trick the parameter
5493    /// prologue uses, and it keeps one code path for both.
5494    fn compile_class_constructor(
5495        &mut self,
5496        func: &ast::Function,
5497        has_heritage: bool,
5498    ) -> Result<CompiledFunction, SyntaxError> {
5499        let saved = self.cur().ctor_kind;
5500        self.state().class_ctor_pending = Some(if has_heritage {
5501            CtorKind::Derived
5502        } else {
5503            CtorKind::Base
5504        });
5505        let result = self.compile_function_with_name(func, false);
5506        self.state().ctor_kind = saved;
5507        self.state().class_ctor_pending = None;
5508        result
5509    }
5510
5511    /// The constructor a class gets when it does not declare one.
5512    ///
5513    /// A base class's is empty; a derived class's forwards every argument to the parent
5514    /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
5515    /// instance field initialiser afterwards when the class has fields, which is why the
5516    /// initialiser is captured rather than inlined.
5517    fn compile_implicit_constructor(
5518        &mut self,
5519        class: &Class,
5520        has_heritage: bool,
5521    ) -> Result<CompiledFunction, SyntaxError> {
5522        self.compile_synthetic_function(
5523            "",
5524            true,
5525            Span::new(class.body_end, class.body_end),
5526            |compiler| {
5527                if has_heritage {
5528                    // A derived constructor's `this` does not exist until `super()` returns,
5529                    // so it starts in the dead zone and `init_ctor` fills it.
5530                    compiler.declare("this", VarDef::lexical("this"));
5531                    compiler.emit(
5532                        Opcode::SetLocUninitialized,
5533                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5534                    );
5535                    compiler.emit(Opcode::InitCtor, &[]);
5536                    compiler.emit(
5537                        Opcode::PutLocCheckInit,
5538                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5539                    );
5540                } else {
5541                    compiler.begin_this_local();
5542                    compiler.emit(Opcode::CheckCtor, &[]);
5543                }
5544                compiler.call_field_initialiser();
5545                // A derived constructor returns `this`, the object `super()` built. Without
5546                // this the implicit constructor fell through to `return_undef`, and `new B()`
5547                // handed back the empty object `construct` had made instead of the one the
5548                // parent constructor initialised.
5549                if has_heritage {
5550                    compiler.emit_var(VarAction::Get, "this");
5551                    compiler.emit(Opcode::Return, &[]);
5552                }
5553                Ok(())
5554            },
5555        )
5556    }
5557
5558    /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
5559    ///
5560    /// A class with no instance fields leaves the binding `undefined`, and calling it
5561    /// would throw; the reference emits the same guard rather than branching at compile
5562    /// time because a class can be extended by a subclass whose fields still have to run.
5563    fn call_field_initialiser(&mut self) {
5564        let skip = self.new_label();
5565        self.emit_var(VarAction::Get, "<class_fields_init>");
5566        self.emit(Opcode::Dup, &[]);
5567        self.emit_jump(Opcode::IfFalse, skip, &[]);
5568        self.emit_var(VarAction::Get, "this");
5569        self.emit(Opcode::Swap, &[]);
5570        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
5571        self.place_label(skip);
5572        self.emit(Opcode::Drop, &[]);
5573    }
5574
5575    /// The function that defines one class's fields on `this`, and runs its static blocks.
5576    ///
5577    /// `define_field` rather than `put_field`: a field is an own property created
5578    /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
5579    /// `x = 1` field must not call the setter.
5580    ///
5581    /// One function serves the whole class: it is called once per instance (or once, for
5582    /// the static half) and walks the members in source order. Static blocks are compiled
5583    /// into the same function because they *are* part of the same sequence — `static a =
5584    /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
5585    /// different values, so the two kinds cannot be split apart.
5586    fn compile_field_initialiser(
5587        &mut self,
5588        items: &[StaticInitItem<'_>],
5589        span: Span,
5590        instance: bool,
5591        add_brand: bool,
5592    ) -> Result<CompiledFunction, SyntaxError> {
5593        self.compile_synthetic_function("", true, span, |compiler| {
5594            if instance {
5595                // An instance initialiser always carries a `<home_object>` local, because the
5596                // brand block below reads it — even when that block turns out to be dead. The
5597                // reference has the same artefact, and the store is visible in its dump.
5598                let current = compiler.stack.len() - 1;
5599                compiler.stack[current].needs_home_object_local = true;
5600            }
5601            compiler.begin_this_local();
5602            if instance {
5603                // `this` gets the brand the prototype created, before any field is defined —
5604                // which is what makes `#m()` usable from inside a field initialiser.
5605                //
5606                // The reference always emits `push_false; if_false L; this; home; add_brand;
5607                // L:` and patches the `push_false` to `push_true` from the class parse when
5608                // the class has private methods; either way the branch folds, but the *mark*
5609                // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
5610                // `this` local from being fused into a `set_loc`.
5611                let skip = compiler.new_label();
5612                if add_brand {
5613                    compiler.emit(Opcode::PushTrue, &[]);
5614                } else {
5615                    compiler.emit(Opcode::PushFalse, &[]);
5616                }
5617                compiler.emit_jump(Opcode::IfFalse, skip, &[]);
5618                compiler.emit_var(VarAction::Get, "this");
5619                compiler.emit_var(VarAction::Get, HOME_OBJECT);
5620                compiler.emit(Opcode::AddBrand, &[]);
5621                compiler.place_label(skip);
5622            }
5623            for item in items {
5624                match item {
5625                    StaticInitItem::Field(key, value) => {
5626                        // A private field is *defined*, not assigned: `define_private_field`
5627                        // reads `obj symbol value`, and its point is that it fails on a
5628                        // receiver that is not this class's — which `put_field` would not.
5629                        //
5630                        // The three shapes are the reference's: `define_field <atom>` for a
5631                        // static name, `define_array_el` for a key that is only known at run
5632                        // time (`obj key value`), `define_private_field` for `#x`, and a
5633                        // computed key is read from its binding rather than recomputed.
5634                        compiler.emit_var(VarAction::Get, "this");
5635                        match key {
5636                            FieldKey::Private(binding) | FieldKey::Computed(binding) => {
5637                                compiler.emit_var(VarAction::Get, binding);
5638                            }
5639                            FieldKey::Literal(_) => {}
5640                        }
5641                        match value {
5642                            Some(value) => compiler.expr(value)?,
5643                            None => compiler.emit(Opcode::Undefined, &[]),
5644                        }
5645                        match key {
5646                            FieldKey::Literal(literal) => {
5647                                let text = compiler.property_key_text(literal, span)?;
5648                                compiler
5649                                    .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
5650                            }
5651                            FieldKey::Computed(_) => {
5652                                compiler.emit(Opcode::DefineArrayEl, &[]);
5653                                // `define_array_el` leaves `obj key`; the key is consumed by
5654                                // the copy the pattern machinery wants, so both go.
5655                                compiler.emit(Opcode::Drop, &[]);
5656                            }
5657                            FieldKey::Private(_) => {
5658                                compiler.emit(Opcode::DefinePrivateField, &[]);
5659                            }
5660                        }
5661                        compiler.emit(Opcode::Drop, &[]);
5662                    }
5663                    StaticInitItem::Block { body, body_start } => {
5664                        let block = compiler.compile_static_block(body, *body_start)?;
5665                        let index = compiler.push_constant(Constant::Function(Box::new(block)));
5666                        // `this fclosure`, so `call_method` finds the receiver below the
5667                        // callee: the block runs with `this` bound to the class.
5668                        compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
5669                        compiler.emit_var(VarAction::Get, "this");
5670                        compiler.emit(Opcode::Swap, &[]);
5671                        compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
5672                        // Nothing the block evaluates is wanted; its effects are the point.
5673                        compiler.emit(Opcode::Drop, &[]);
5674                    }
5675                }
5676            }
5677            Ok(())
5678        })
5679    }
5680
5681    /// Compile a `static { … }` body into the function the class calls for it.
5682    ///
5683    /// Shaped like an arrow, because that is the one function form with no `this`,
5684    /// `new.target` or `arguments` of its own: all three reach the enclosing static
5685    /// initialiser, and through it the class. `arguments` never gets that far — the parser
5686    /// rejects the reference — but `this` and `super` both depend on it.
5687    ///
5688    /// The body is hoisted like a function body's, because the reference parses it as one:
5689    /// `var` inside a block is a local of the block's function, not of whatever encloses
5690    /// the class.
5691    fn compile_static_block(
5692        &mut self,
5693        body: &[Stmt],
5694        body_start: Position,
5695    ) -> Result<CompiledFunction, SyntaxError> {
5696        let mut state = FnState::new(String::new(), FunctionKind::Normal);
5697        // Class bodies are strict, so a static block is too.
5698        state.strict = true;
5699        // The one property that makes this an arrow: nothing of its own to bind `this` to,
5700        // so `this` and `super` come from the initialiser that calls it.
5701        state.is_arrow = true;
5702        state.created_in_block = self.cur().current_block;
5703        state.with_names = self.cur().with_names.clone();
5704        state.line = body_start.line;
5705        state.column = body_start.column;
5706        let depth = self.stack.len();
5707        self.stack.push(state);
5708        let body_key = body_start.offset as u64;
5709        self.push_block(body_key, NO_PARENT);
5710        self.state().body_block = body_key;
5711        let result = (|| {
5712            self.hoist(body, body_key)?;
5713            self.emit_scope_enter(body_key);
5714            for statement in body {
5715                self.stmt(statement)?;
5716            }
5717            if self.end_is_reachable() {
5718                self.emit(Opcode::ReturnUndef, &[]);
5719            }
5720            Ok(())
5721        })();
5722        if result.is_err() {
5723            self.stack.truncate(depth);
5724            return result.map(|()| unreachable!());
5725        }
5726        Ok(self.finish_current())
5727    }
5728
5729    /// Compile a class, leaving the constructor on the stack when `keep`.
5730    ///
5731    /// The shape follows the reference: the class body is its own scope holding the
5732    /// class's *inner* name as a `const` — which is what lets a method refer to the
5733    /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
5734    /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
5735    /// on the top of the stack: the prototype for instance members, the constructor
5736    /// itself for `static` ones, which is why a static member costs an extra `swap`.
5737    fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
5738        let parent_block = self.cur().current_block;
5739        let key = class.span.start.offset as u64;
5740        self.push_block(key, parent_block);
5741        let name = class.name.as_ref().map(|ident| ident.name.clone());
5742        // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
5743        // resolves `E` without a global lookup. An *unnamed* class expression has no such
5744        // binding, and `define_class` is handed the empty name.
5745        if let Some(name) = &name {
5746            self.declare(name, VarDef::constant(name.clone()));
5747        }
5748        self.emit_scope_enter(key);
5749
5750        // The heritage clause is evaluated outside the class's own scope: it cannot see
5751        // the class binding it is about to initialise.
5752        let saved_block = self.cur().current_block;
5753        self.state().current_block = parent_block;
5754        match &class.super_class {
5755            Some(parent) => self.expr(parent)?,
5756            None => self.emit(Opcode::Undefined, &[]),
5757        }
5758        self.state().current_block = saved_block;
5759        let has_heritage = class.super_class.is_some();
5760
5761        // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
5762        // lands after the heritage's code — which is where the reference puts it, because it
5763        // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
5764        // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
5765        // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
5766        // came out in the opposite order from the reference's.
5767        //
5768        // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
5769        // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
5770        // a const accepts — so the old comment's worry ("a const would refuse the second
5771        // store") did not apply: there is no second store.
5772        // Every `#name` the class declares gets a `const` binding in the class scope, and so
5773        // does every computed field key. That is how the reference does it
5774        // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
5775        // what makes a private name resolve like any other class-scope variable — including
5776        // through a nested function's closure — while remaining invisible outside.
5777        //
5778        // All of them are declared *before* `<class_fields_init>`, in member order, because
5779        // that is when the reference's parser creates them.
5780        let plan = ClassPlan::build(class);
5781        // The body's private names are visible from here to the end of the class, and shadow
5782        // any outer class's of the same spelling. Pushed *before* the constructor is compiled
5783        // — it is compiled first because `define_class` consumes it, but its body can name
5784        // `#x` like any other member's.
5785        self.private_scopes.push(plan.uses.clone());
5786        let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
5787        for binding in &plan.bindings {
5788            class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
5789        }
5790        let fci = self.declare(
5791            "<class_fields_init>",
5792            VarDef::constant("<class_fields_init>"),
5793        );
5794        // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
5795        // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
5796        // members' bindings follow in reverse.
5797        self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
5798        for slot in class_slots.iter().rev() {
5799            self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
5800        }
5801
5802        // The constructor is compiled before `define_class` because that instruction
5803        // consumes it; a class without one gets the implicit version.
5804        let constructor = class.elements.iter().find_map(|element| match element {
5805            ClassElement::Method {
5806                kind: MethodKind::Constructor,
5807                func,
5808                ..
5809            } => Some(&**func),
5810            _ => None,
5811        });
5812        // A constructor is compiled differently from a method: it owns `this`. The flags
5813        // go on the *enclosing* state because a constructor is a nested function and
5814        // `compile_function_with_name` starts a fresh one.
5815        let ctor = match constructor {
5816            Some(func) => self.compile_class_constructor(func, has_heritage)?,
5817            None => self.compile_implicit_constructor(class, has_heritage)?,
5818        };
5819        // A closure, not the bare constant: the constructor captures
5820        // `<class_fields_init>`, which is only filled after `define_class` has run, so it
5821        // has to hold the cell rather than a copy of its value.
5822        //
5823        // The pool slot is left unassigned for now, because the reference gives the
5824        // constructor the *last* index of the members' range: `js_parse_class` emits a
5825        // `push_const` whose operand is patched at the end of the class parse, after every
5826        // method has taken a slot. Emitting the members first and the constant second is how
5827        // the numbering comes out the same; the instruction itself stays where it is.
5828        let ctor_insn = self.cur().insns.len();
5829        self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
5830        let flags = if has_heritage { 1 } else { 0 };
5831        self.emit(
5832            Opcode::DefineClass,
5833            &[
5834                Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
5835                Op::Int(flags),
5836            ],
5837        );
5838
5839        // Instance fields and static fields are two different functions: the first runs
5840        // per instance from the constructor, the second runs once, here.
5841        let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
5842        let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
5843        for (index, element) in class.elements.iter().enumerate() {
5844            match element {
5845                ClassElement::Method {
5846                    key: member_key,
5847                    is_static,
5848                    kind,
5849                    func,
5850                    span,
5851                } => {
5852                    if *kind == MethodKind::Constructor {
5853                        continue;
5854                    }
5855                    // `static(x)` is a *method* named `static`, not a static method; the
5856                    // parser already decided which by putting it in `kind`.
5857                    if *is_static {
5858                        self.emit(Opcode::Swap, &[]);
5859                    }
5860                    // A computed key is evaluated *here*, before the method's closure
5861                    // exists, and stays under it: `define_method_computed` pops
5862                    // `function, key, object`, so the stack has to read
5863                    // `[class, prototype, key, function]`. Evaluating the key after the
5864                    // `fclosure` and swapping the two put the prototype *below* the
5865                    // closure, which defined the method on the function and lost the
5866                    // prototype: `class C { [k]() {} }` left `C` undefined. The order is
5867                    // also the spec's — a class body evaluates every element's name before
5868                    // that element's function.
5869                    if let PropName::Computed(key) = member_key {
5870                        self.expr(key)?;
5871                    }
5872                    let function = self.compile_function_with_name(func, true)?;
5873                    let index = self.push_constant(Constant::Function(Box::new(function)));
5874                    self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5875                    match member_key {
5876                        // A private method is not a property of the prototype: it is a
5877                        // closure in the class scope, which is why nothing outside can reach
5878                        // it and why a use site has to brand-check. `set_name` gives the
5879                        // function its `name` (`#m`), which an accessor does not get — the
5880                        // reference leaves that commented out.
5881                        PropName::Private(ident) => {
5882                            let name = format!("#{}", ident.name);
5883                            // `set_home_object` first: the brand check reads the function's
5884                            // home object, and for a method that is the prototype.
5885                            self.emit(Opcode::SetHomeObject, &[]);
5886                            let binding = if *kind == MethodKind::Set {
5887                                format!("{name}<set>")
5888                            } else {
5889                                name.clone()
5890                            };
5891                            if *kind == MethodKind::Method {
5892                                self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
5893                            }
5894                            self.emit_var(VarAction::PutInit, &binding);
5895                        }
5896                        PropName::Computed(_) => {
5897                            self.emit(
5898                                Opcode::DefineMethodComputed,
5899                                &[Op::Int(class_method_flags(*kind))],
5900                            );
5901                        }
5902                        PropName::Literal(literal) => {
5903                            let text = self.property_key_text(literal, *span)?;
5904                            self.emit(
5905                                Opcode::DefineMethod,
5906                                &[
5907                                    Op::Atom(Atom::from_wtf8(&text)),
5908                                    Op::Int(class_method_flags(*kind)),
5909                                ],
5910                            );
5911                        }
5912                    }
5913                    if *is_static {
5914                        self.emit(Opcode::Swap, &[]);
5915                    }
5916                }
5917                ClassElement::Field {
5918                    key: field_key,
5919                    is_static,
5920                    value,
5921                    ..
5922                } => {
5923                    // A private field's *symbol* is created here, at the member, and stored
5924                    // in its binding: the field's property is keyed by it, so it has to exist
5925                    // before any initialiser runs, and a fresh one per class body is what
5926                    // makes two classes that both write `#x` independent.
5927                    //
5928                    // A computed key is evaluated once, here, and `to_propkey`'d once — a key
5929                    // whose `toString` has a side effect must not run again per instance.
5930                    let key = match field_key {
5931                        PropName::Private(ident) => {
5932                            let binding = format!("#{}", ident.name);
5933                            if *is_static {
5934                                self.emit(Opcode::Swap, &[]);
5935                            }
5936                            self.emit(
5937                                Opcode::PrivateSymbol,
5938                                &[Op::Atom(Atom::from_text(&binding))],
5939                            );
5940                            self.emit_var(VarAction::PutInit, &binding);
5941                            if *is_static {
5942                                self.emit(Opcode::Swap, &[]);
5943                            }
5944                            FieldKey::Private(binding)
5945                        }
5946                        PropName::Computed(expression) => {
5947                            let binding = plan
5948                                .computed
5949                                .get(&index)
5950                                .cloned()
5951                                .expect("every computed key got a binding");
5952                            if *is_static {
5953                                self.emit(Opcode::Swap, &[]);
5954                            }
5955                            self.expr(expression)?;
5956                            self.emit(Opcode::ToPropkey, &[]);
5957                            self.emit_var(VarAction::PutInit, &binding);
5958                            if *is_static {
5959                                self.emit(Opcode::Swap, &[]);
5960                            }
5961                            FieldKey::Computed(binding)
5962                        }
5963                        PropName::Literal(literal) => FieldKey::Literal(literal),
5964                    };
5965                    if *is_static {
5966                        static_items.push(StaticInitItem::Field(key, value.as_deref()));
5967                    } else {
5968                        instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
5969                    }
5970                }
5971                ClassElement::StaticBlock {
5972                    body, body_start, ..
5973                } => static_items.push(StaticInitItem::Block {
5974                    body,
5975                    body_start: *body_start,
5976                }),
5977            }
5978        }
5979
5980        // Now that every member has its slot, the constructor can have the next one and the
5981        // `fclosure` above can name it.
5982        let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
5983        match self.state().insns.get_mut(ctor_insn) {
5984            Some(Insn::Fixed { operands, .. }) => {
5985                operands[0] = Op::Const(ctor_index);
5986            }
5987            // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
5988            // loudly beats emitting a `fclosure` of slot 4294967295.
5989            _ => {
5990                return Err(SyntaxError::new(
5991                    "the class constructor's fclosure went missing",
5992                    class.span,
5993                ));
5994            }
5995        }
5996
5997        // The instance brand: a symbol created once on the prototype, which every instance
5998        // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
5999        // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
6000        // copy is created. The prototype is on top of the stack at this point.
6001        if plan.instance_brand {
6002            self.emit(Opcode::Dup, &[]);
6003            self.emit(Opcode::Null, &[]);
6004            self.emit(Opcode::Swap, &[]);
6005            self.emit(Opcode::AddBrand, &[]);
6006        }
6007
6008        // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
6009        // class has no instance fields. The constructor calls it only when it is defined.
6010        //
6011        // A class with private *methods* but no fields still needs one, because adding the
6012        // brand to each new instance is the initialiser's job.
6013        if instance_fields.is_empty() && !plan.instance_brand {
6014            self.emit(Opcode::Undefined, &[]);
6015        } else {
6016            let initialiser = self.compile_field_initialiser(
6017                &instance_fields,
6018                class.span,
6019                true,
6020                plan.instance_brand,
6021            )?;
6022            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6023            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6024            // `set_home_object` reads `obj func`, so the prototype stays where it is.
6025            self.emit(Opcode::SetHomeObject, &[]);
6026        }
6027        self.emit_var(VarAction::PutInit, "<class_fields_init>");
6028        // The prototype has done its job: every instance member is defined on it. What
6029        // is left under it is the constructor.
6030        self.emit(Opcode::Drop, &[]);
6031
6032        // The static brand, for `static #m() {}`: same opcode, but the home object is the
6033        // constructor itself, so the symbol lands on the class and the class carries it.
6034        if plan.static_brand {
6035            self.emit(Opcode::Dup, &[]);
6036            self.emit(Opcode::Dup, &[]);
6037            self.emit(Opcode::AddBrand, &[]);
6038        }
6039
6040        // The class binding is initialised *before* static fields run, so a static field
6041        // can refer to the class by name (`static y = S.x`).
6042        // `set_loc` leaves the constructor on the stack, which is what the static field
6043        // call and the outer store both consume.
6044        //
6045        // Only when there *is* such a binding: an anonymous class expression declares no
6046        // class-scope name, and asking for one by the empty string resolved to nothing —
6047        // which made `var x = class {}` assign `undefined` and put a bogus global store in
6048        // the instruction stream.
6049        if let Some(name) = &name {
6050            self.emit_var(VarAction::SetInit, name);
6051        }
6052        if !static_items.is_empty() {
6053            // The static half has no brand prologue of its own: the constructor got its
6054            // brand above, before this runs.
6055            let initialiser =
6056                self.compile_field_initialiser(&static_items, class.span, false, false)?;
6057            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6058            self.emit(Opcode::Dup, &[]);
6059            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6060            self.emit(Opcode::SetHomeObject, &[]);
6061            self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6062            self.emit(Opcode::Drop, &[]);
6063        }
6064        // The body is over, and with it this class's private names.
6065        let _ = self.private_scopes.pop();
6066        self.emit_scope_leave(key);
6067        self.state().current_block = parent_block;
6068        if keep {
6069            // A class *expression* is its own value; the class-scope binding was only
6070            // ever an alias for it.
6071            return Ok(());
6072        }
6073        // A declaration stores into the binding the enclosing statement declared.
6074        self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
6075        Ok(())
6076    }
6077
6078    fn push_this(&mut self) {
6079        self.emit(Opcode::PushThis, &[]);
6080    }
6081
6082    /// `this`, which an arrow does not have of its own.
6083    ///
6084    /// The reference gives the enclosing function a local named `this`, initialised from
6085    /// `push_this` at the top of its body, and the arrow then reads it as a captured
6086    /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
6087    /// the arrow is called with none.
6088    fn this_expression(&mut self) {
6089        // In a class constructor `this` is a local: a derived constructor only gets one
6090        // when `super()` returns, and reading the raw receiver would give the *outer*
6091        // one instead.
6092        if self.cur().ctor_kind != CtorKind::None {
6093            self.emit_var(VarAction::Get, "this");
6094            return;
6095        }
6096        if !self.cur().is_arrow {
6097            self.push_this();
6098            return;
6099        }
6100        // An arrow at the **top level** of a script or module has no enclosing function,
6101        // but it still inherits `this` — the script's or module's own. Falling through to
6102        // `emit_var(Get, "this")` without a target made that a *global* lookup, so
6103        // `var f = () => typeof this` at top level reported
6104        // `ReferenceError: 'this' is not defined` instead of `"object"`
6105        // (`Set/prototype/forEach/this-arg-explicit-cannot-override-lexical-this-arrow`
6106        // is the test262 case that reaches it, through a native `forEach`).
6107        //
6108        // The script state is the bottom of the stack, so it is the fallback target. Its
6109        // own `provide_this_local` then prepends the `push_this` the arrow reads.
6110        let target = self.enclosing_function().unwrap_or(0);
6111        self.state_at(target).needs_this_local = true;
6112        self.declare_at(target, "this");
6113        self.emit_var(VarAction::Get, "this");
6114    }
6115
6116    /// `new.target`, which an arrow likewise does not own.
6117    fn new_target_expression(&mut self) {
6118        if !self.cur().is_arrow {
6119            self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
6120            return;
6121        }
6122        if let Some(target) = self.enclosing_function() {
6123            self.state_at(target).needs_new_target_local = true;
6124            self.declare_at(target, NEW_TARGET);
6125        }
6126        self.emit_var(VarAction::Get, NEW_TARGET);
6127    }
6128
6129    /// `this.active_func`: the function `super()` resolves against.
6130    ///
6131    /// In a constructor or a method that is the function being run, so the special object
6132    /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
6133    /// a closure variable — see [`FnState::needs_active_func_local`].
6134    fn active_func_expression(&mut self) {
6135        if !self.cur().is_arrow {
6136            self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
6137            return;
6138        }
6139        if let Some(target) = self.enclosing_function() {
6140            self.state_at(target).needs_active_func_local = true;
6141            self.declare_at(target, ACTIVE_FUNC);
6142        }
6143        self.emit_var(VarAction::Get, ACTIVE_FUNC);
6144    }
6145
6146    /// Give the function a local `<active_func>`, for an arrow inside it to capture.
6147    fn provide_active_func_local(&mut self) {
6148        let current = self.stack.len() - 1;
6149        if !self.stack[current].needs_active_func_local {
6150            return;
6151        }
6152        if !self.stack[current]
6153            .vars
6154            .iter()
6155            .any(|var| var.name == ACTIVE_FUNC)
6156        {
6157            self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
6158        }
6159        self.prepend_initialiser(
6160            ACTIVE_FUNC,
6161            Insn::Fixed {
6162                op: Opcode::SpecialObject,
6163                operands: vec![Op::Int(2)],
6164            },
6165        );
6166    }
6167
6168    /// Give the function a local `new.target`, for an arrow inside it to capture.
6169    fn provide_new_target_local(&mut self) {
6170        let current = self.stack.len() - 1;
6171        if !self.stack[current].needs_new_target_local {
6172            return;
6173        }
6174        if !self.stack[current]
6175            .vars
6176            .iter()
6177            .any(|var| var.name == NEW_TARGET)
6178        {
6179            self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
6180        }
6181        self.prepend_initialiser(
6182            NEW_TARGET,
6183            Insn::Fixed {
6184                op: Opcode::SpecialObject,
6185                operands: vec![Op::Int(3)],
6186            },
6187        );
6188    }
6189
6190    /// `arguments` reached from an arrow, which likewise belongs to the enclosing
6191    /// function.
6192    fn ensure_enclosing_arguments(&mut self) {
6193        // An arrow created in a parameter list needs the *parameter* scope's
6194        // `arguments`, not the body's: the two are separate bindings and the arrow was
6195        // born before the body existed.
6196        let from_params = self.cur().created_in_params;
6197        if let Some(target) = self.enclosing_function() {
6198            self.state_at(target).needs_arguments_local = true;
6199            if from_params {
6200                self.state_at(target).needs_param_arguments = true;
6201                // Declare it now, not at the enclosing function's `finish_current`: the
6202                // arrow resolves its own `arguments` before that runs, and a binding that
6203                // does not exist yet resolves as a global.
6204                declare_param_var_at(&mut self.stack[target], "arguments");
6205            }
6206            self.declare_at(target, "arguments");
6207        }
6208    }
6209
6210    /// The innermost enclosing frame that is a real function — an arrow inherits from it
6211    /// rather than starting a scope of its own.
6212    fn enclosing_function(&self) -> Option<usize> {
6213        (0..self.stack.len())
6214            .rev()
6215            .find(|index| !self.stack[*index].is_arrow && !self.stack[*index].is_script)
6216    }
6217
6218    fn state_at(&mut self, index: usize) -> &mut FnState {
6219        &mut self.stack[index]
6220    }
6221
6222    /// Declare a `var` binding directly in a specific frame.
6223    fn declare_at(&mut self, index: usize, name: &str) {
6224        let state = &mut self.stack[index];
6225        if state.vars.iter().any(|var| var.name == name) {
6226            return;
6227        }
6228        state.var_block.push(FUNCTION_SCOPE);
6229        state.vars.push(VarDef::var(name));
6230    }
6231
6232    /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
6233    /// the reference calls a `special_object` gets initialised on entry.
6234    fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
6235        let current = self.stack.len() - 1;
6236        let init = [
6237            producer,
6238            Insn::Var {
6239                action: VarAction::Put,
6240                name: name.to_string(),
6241                block: 0,
6242                // A prologue initialiser runs before the body proper, but it is body
6243                // code: `this` and `arguments` are provided for it, not by it.
6244                in_params: false,
6245            },
6246        ];
6247        let inserted = init.len();
6248        for (index, instruction) in init.into_iter().enumerate() {
6249            self.stack[current].insns.insert(index, instruction);
6250        }
6251        for placed in self.stack[current].labels.iter_mut().flatten() {
6252            *placed += inserted;
6253        }
6254        self.stack[current].label_since_insn = true;
6255    }
6256
6257    fn push_constant(&mut self, constant: Constant) -> u32 {
6258        let state = self.state();
6259        let index = state.cpool.len() as u32;
6260        state.cpool.push(constant);
6261        index
6262    }
6263
6264    /// Compile `a && b`, `a || b`, `a ?? b`.
6265    ///
6266    /// A run of the *same* operator shares one end label, so `a || b || c` tests
6267    /// `a` once and jumps past everything when it is truthy, instead of falling
6268    /// into `b`'s test. The parser builds such a run left-associated —
6269    /// `((a || b) || c)` — so the operands are collected off the left spine.
6270    ///
6271    /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
6272    /// `||`'s label, because the inner chain really does end before `&&` begins.
6273    fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
6274        let mut operands = Vec::new();
6275        collect_same_operator(op, left, &mut operands);
6276        operands.push(right);
6277
6278        let end = self.new_label();
6279        // Every operand but the last decides whether the chain stops here.
6280        let last = operands.pop().expect("the right operand is always present");
6281        for operand in operands {
6282            self.expr(operand)?;
6283            self.emit(Opcode::Dup, &[]);
6284            match op {
6285                LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
6286                LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
6287                // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
6288                // `0 || b` is `b`. The dedicated test keeps the value unless it is
6289                // null-ish, so the jump is taken on `false`.
6290                LogicalOp::Coalesce => {
6291                    self.emit(Opcode::IsUndefinedOrNull, &[]);
6292                    self.emit_jump(Opcode::IfFalse, end, &[]);
6293                }
6294            }
6295            self.emit(Opcode::Drop, &[]);
6296        }
6297        self.expr(last)?;
6298        self.place_label(end);
6299        Ok(())
6300    }
6301
6302    fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
6303        match op {
6304            UnaryOp::Typeof => {
6305                // `typeof x` must not throw on an undeclared name.
6306                if let ExprKind::Ident(name) = &argument.kind {
6307                    self.emit_var(VarAction::GetUndef, &name.name);
6308                } else {
6309                    self.expr(argument)?;
6310                }
6311                self.emit(Opcode::Typeof, &[]);
6312            }
6313            UnaryOp::Delete => {
6314                // `delete obj.prop` really deletes, and answers whether it could.
6315                // Deleting a *binding* is always `false`: a local, an argument and a
6316                // declared global are all non-configurable, which the reference encodes
6317                // as a constant `push_false` rather than a runtime check. Only a
6318                // property access has anything to do at run time.
6319                // `delete super.x` is not a delete at all: the spec refuses it, and the
6320                // reference encodes the refusal as a `throw_error`. The receiver and the
6321                // key are still evaluated first, which is what keeps the evaluation order
6322                // of the operand intact.
6323                // `delete z?.b.c` answers `true` when the chain short-circuits: there is
6324                // nothing to delete, and a failed delete is not the same as a skipped
6325                // one. The reference emits the guards so they land on a `drop; push_true`
6326                // tail, which is what this reproduces.
6327                if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
6328                    && let ExprKind::Member {
6329                        object, property, ..
6330                    } = &inner.unparen().kind
6331                {
6332                    let end = self.new_label();
6333                    let done = self.new_label();
6334                    self.chain_link(object, end)?;
6335                    match property {
6336                        MemberProp::Ident(name) => self.emit(
6337                            Opcode::PushAtomValue,
6338                            &[Op::Atom(Atom::from_text(&name.name))],
6339                        ),
6340                        MemberProp::Computed(index) => self.expr(index)?,
6341                        MemberProp::Private(_) => {
6342                            return Err(SyntaxError::new(
6343                                "deleting a private field is not allowed",
6344                                argument.span,
6345                            ));
6346                        }
6347                    }
6348                    self.emit(Opcode::Delete, &[]);
6349                    self.emit_jump(Opcode::Goto, done, &[]);
6350                    self.place_label(end);
6351                    self.emit(Opcode::Drop, &[]);
6352                    self.emit(Opcode::PushTrue, &[]);
6353                    self.place_label(done);
6354                    return Ok(());
6355                }
6356                if let ExprKind::Member { object, .. } = &argument.unparen().kind
6357                    && matches!(object.unparen().kind, ExprKind::SuperProp)
6358                {
6359                    self.super_base();
6360                    self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
6361                    return Ok(());
6362                }
6363                match &argument.kind {
6364                    ExprKind::Member {
6365                        object, property, ..
6366                    } => {
6367                        self.expr(object)?;
6368                        match property {
6369                            MemberProp::Ident(name) => {
6370                                self.emit(
6371                                    Opcode::PushAtomValue,
6372                                    &[Op::Atom(Atom::from_text(&name.name))],
6373                                );
6374                            }
6375                            MemberProp::Computed(index) => self.expr(index)?,
6376                            MemberProp::Private(_) => {
6377                                return Err(SyntaxError::new(
6378                                    "deleting a private field is not allowed",
6379                                    argument.span,
6380                                ));
6381                            }
6382                        }
6383                        self.emit(Opcode::Delete, &[]);
6384                    }
6385                    ExprKind::Ident(name) => {
6386                        // `delete name`: a declared global, a local and an argument all
6387                        // answer `false`, but an *implicit* global (`x = 1` with no
6388                        // declaration) is a configurable property of the global object
6389                        // and really goes away. Which of those a name is only the
6390                        // resolver knows, so the decision waits for it.
6391                        let pos = self.cur().cur_pos;
6392                        self.state().insns.push(Insn::DeleteVar {
6393                            name: name.name.clone(),
6394                        });
6395                        self.state().insn_pos.push(pos);
6396                    }
6397                    _ => self.emit(Opcode::PushFalse, &[]),
6398                }
6399            }
6400            UnaryOp::Void => {
6401                self.expr(argument)?;
6402                self.emit(Opcode::Drop, &[]);
6403                self.emit(Opcode::Undefined, &[]);
6404            }
6405            UnaryOp::Minus => {
6406                self.expr(argument)?;
6407                self.emit(Opcode::Neg, &[]);
6408            }
6409            UnaryOp::Plus => {
6410                self.expr(argument)?;
6411                self.emit(Opcode::Plus, &[]);
6412            }
6413            UnaryOp::Not => {
6414                self.expr(argument)?;
6415                self.emit(Opcode::Lnot, &[]);
6416            }
6417            UnaryOp::BitNot => {
6418                self.expr(argument)?;
6419                self.emit(Opcode::Not, &[]);
6420            }
6421        }
6422        Ok(())
6423    }
6424
6425    /// Compile an assignment.
6426    ///
6427    /// Three operator families, three shapes:
6428    ///
6429    /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
6430    ///   the value is kept, because `put_field`/`put_array_el` consume both the
6431    ///   object and the value: `insert2` is `obj a -> a obj a`, so the store sees
6432    ///   the pair it wants and leaves a copy on top.
6433    /// * **compound** `+=` … — read the place, apply the operator, store. A member
6434    ///   reads through `get_field2`/`get_array_el3`, which leave the object (and
6435    ///   index) underneath the value precisely so the store can follow.
6436    /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
6437    ///   right-hand side. The test *keeps* the current value and skips the store
6438    ///   entirely, which is the whole point: `a ||= b` must not evaluate `b` when
6439    ///   `a` is already truthy.
6440    fn assign(&mut self, op: AssignOp, target: &Pattern, value: &Expr) -> Result<(), SyntaxError> {
6441        // Reading the flag clears it: only the outermost assignment of an
6442        // expression statement may drop its value.
6443        let keep = !std::mem::take(&mut self.state().discard_value);
6444        match &target.kind {
6445            PatternKind::Ident(name) => {
6446                // A *simple* store is blamed on the identifier, not on the `=`: a
6447                // strict-mode `not_def = 1` raises when the name is written, which the
6448                // reference reports at the name's column. A compound store is blamed on
6449                // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
6450                // which the reference reports at the `+=`), so only the simple case
6451                // moves the position.
6452                let saved = self.cur().cur_pos;
6453                let name_pos = Some(name.span.start);
6454                if matches!(op, AssignOp::Assign) {
6455                    self.state().cur_pos = name_pos;
6456                }
6457                // A *compound* store reads the binding before it combines, and that read
6458                // is blamed on the identifier: `not_def += 2` fails while reading
6459                // `not_def`, so the position is the name's, not the `+=`'s. The
6460                // combination that follows is blamed on the operator, which is why
6461                // `cur_pos` is put back to the operator position before it is emitted.
6462                self.state().cur_pos = name_pos;
6463                match op {
6464                    AssignOp::Assign => {
6465                        self.expr(value)?;
6466                        self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
6467                        // A discarded store to a *slot* consumes its value, so no copy
6468                        // is needed. A global store goes through `put_var`, which the
6469                        // reference always pairs with a `dup` — matching it keeps the
6470                        // bytecode identical. Getting this wrong is not only an extra
6471                        // instruction: a stray copy gives the peephole a chance to fold
6472                        // the store into an unrelated later read.
6473                        let slot = self.is_slot(&name.name);
6474                        if keep || !slot {
6475                            self.emit(Opcode::Dup, &[]);
6476                        }
6477                        self.state().no_value = !keep && slot;
6478                        self.emit_var(VarAction::Put, &name.name);
6479                    }
6480                    AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6481                        let end = self.new_label();
6482                        self.emit_var(VarAction::Get, &name.name);
6483                        self.state().cur_pos = saved;
6484                        self.emit(Opcode::Dup, &[]);
6485                        self.emit_logical_test(op);
6486                        self.emit_jump(logical_jump(op), end, &[]);
6487                        self.emit(Opcode::Drop, &[]);
6488                        self.expr(value)?;
6489                        self.emit(Opcode::Dup, &[]);
6490                        self.emit_var(VarAction::Put, &name.name);
6491                        self.place_label(end);
6492                    }
6493                    _ => {
6494                        self.emit_var(VarAction::Get, &name.name);
6495                        self.expr(value)?;
6496                        self.state().cur_pos = saved;
6497                        self.emit(compound_opcode(op), &[]);
6498                        self.emit(Opcode::Dup, &[]);
6499                        self.emit_var(VarAction::Put, &name.name);
6500                    }
6501                }
6502                self.state().cur_pos = saved;
6503                Ok(())
6504            }
6505            PatternKind::Member(member) => {
6506                // `super.x = v` is not a store through a value: it starts at the home
6507                // object's prototype but writes to `this`, so it goes through
6508                // `put_super_value` rather than `put_field`. The receiver, prototype, key
6509                // and value are handed over together.
6510                if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
6511                    return self.assign_super(member, op, value);
6512                }
6513                // A store is blamed on the selector punctuator (`.` or `[`), the same
6514                // token a load is blamed on — the reference records `put_field obj.a`
6515                // at the `.`, so a setter that throws reports that column and not the
6516                // `=` of the assignment it sits in. The inner expressions restore their
6517                // own positions, so the selector's sticks for the store instructions.
6518                let saved = self.cur().cur_pos;
6519                self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6520                self.expr(&member.object)?;
6521                match &member.property {
6522                    MemberProp::Ident(property) => {
6523                        let atom = Atom::from_text(&property.name);
6524                        match op {
6525                            AssignOp::Assign => {
6526                                self.expr(value)?;
6527                                // `put_field` consumes the object and the value, so
6528                                // without `insert2` nothing is left over for the
6529                                // statement to drop.
6530                                self.state().no_value = !keep;
6531                                if keep {
6532                                    self.emit(Opcode::Insert2, &[]);
6533                                }
6534                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6535                            }
6536                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6537                                // `get_field2` leaves the object under the value, so
6538                                // the keep path has an object to dispose of. The store
6539                                // path must jump *over* that cleanup: falling into it
6540                                // would `nip` a stack that only holds the value.
6541                                let (keep_label, end) = (self.new_label(), self.new_label());
6542                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6543                                self.emit(Opcode::Dup, &[]);
6544                                self.emit_logical_test(op);
6545                                self.emit_jump(logical_jump(op), keep_label, &[]);
6546                                self.emit(Opcode::Drop, &[]);
6547                                self.expr(value)?;
6548                                self.emit(Opcode::Insert2, &[]);
6549                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6550                                self.emit_jump(Opcode::Goto, end, &[]);
6551                                self.place_label(keep_label);
6552                                self.emit(Opcode::Nip, &[]);
6553                                self.place_label(end);
6554                            }
6555                            _ => {
6556                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6557                                self.expr(value)?;
6558                                self.emit(compound_opcode(op), &[]);
6559                                self.state().no_value = !keep;
6560                                if keep {
6561                                    self.emit(Opcode::Insert2, &[]);
6562                                }
6563                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6564                            }
6565                        }
6566                    }
6567                    MemberProp::Computed(index) => {
6568                        self.expr(index)?;
6569                        match op {
6570                            AssignOp::Assign => {
6571                                self.expr(value)?;
6572                                self.state().no_value = !keep;
6573                                if keep {
6574                                    self.emit(Opcode::Insert3, &[]);
6575                                }
6576                                self.emit(Opcode::PutArrayEl, &[]);
6577                            }
6578                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6579                                let (keep_label, end) = (self.new_label(), self.new_label());
6580                                self.emit(Opcode::GetArrayEl3, &[]);
6581                                self.emit(Opcode::Dup, &[]);
6582                                self.emit_logical_test(op);
6583                                self.emit_jump(logical_jump(op), keep_label, &[]);
6584                                self.emit(Opcode::Drop, &[]);
6585                                self.expr(value)?;
6586                                self.emit(Opcode::Insert3, &[]);
6587                                self.emit(Opcode::PutArrayEl, &[]);
6588                                self.emit_jump(Opcode::Goto, end, &[]);
6589                                self.place_label(keep_label);
6590                                // Both the object and the index are left over.
6591                                self.emit(Opcode::Nip, &[]);
6592                                self.emit(Opcode::Nip, &[]);
6593                                self.place_label(end);
6594                            }
6595                            _ => {
6596                                self.emit(Opcode::GetArrayEl3, &[]);
6597                                self.expr(value)?;
6598                                self.emit(compound_opcode(op), &[]);
6599                                self.state().no_value = !keep;
6600                                if keep {
6601                                    self.emit(Opcode::Insert3, &[]);
6602                                }
6603                                self.emit(Opcode::PutArrayEl, &[]);
6604                            }
6605                        }
6606                    }
6607                    MemberProp::Private(name) => {
6608                        // `obj value` is on the stack, and every private store wants exactly
6609                        // that. A top-level private name cannot be assigned (the parser rejects
6610                        // `#x = 1`), so the only way here is `this.#x = …` inside the class.
6611                        //
6612                        // The reference emits `insert2` whether or not the value is wanted,
6613                        // so this does too: the copy left behind is the assignment expression's
6614                        // value, and a discarded one is simply never read.
6615                        let binding = format!("#{}", name.name);
6616                        let (kind, setter) = self.private_use(&binding, member.span)?;
6617                        match op {
6618                            AssignOp::Assign => {
6619                                self.expr(value)?;
6620                                if keep {
6621                                    self.emit(Opcode::Insert2, &[]);
6622                                }
6623                                self.private_store(&binding, kind, setter.as_deref())?;
6624                                self.state().no_value = !keep;
6625                            }
6626                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6627                                let (keep_label, end) = (self.new_label(), self.new_label());
6628                                self.emit(Opcode::Dup, &[]);
6629                                self.private_load(&binding, kind, member.span)?;
6630                                self.emit(Opcode::Dup, &[]);
6631                                self.emit_logical_test(op);
6632                                self.emit_jump(logical_jump(op), keep_label, &[]);
6633                                self.emit(Opcode::Drop, &[]);
6634                                self.expr(value)?;
6635                                self.emit(Opcode::Insert2, &[]);
6636                                self.private_store(&binding, kind, setter.as_deref())?;
6637                                self.emit_jump(Opcode::Goto, end, &[]);
6638                                self.place_label(keep_label);
6639                                self.emit(Opcode::Nip, &[]);
6640                                self.place_label(end);
6641                            }
6642                            _ => {
6643                                self.emit(Opcode::Dup, &[]);
6644                                self.private_load(&binding, kind, member.span)?;
6645                                self.expr(value)?;
6646                                self.emit(compound_opcode(op), &[]);
6647                                self.emit(Opcode::Insert2, &[]);
6648                                self.private_store(&binding, kind, setter.as_deref())?;
6649                            }
6650                        }
6651                    }
6652                }
6653                self.state().cur_pos = saved;
6654                Ok(())
6655            }
6656            // A destructuring assignment: the right-hand side is the expression's own
6657            // value, so it is evaluated once and kept under the pattern's stores.
6658            PatternKind::Array { .. } | PatternKind::Object { .. } => {
6659                self.expr(value)?;
6660                if keep {
6661                    self.emit(Opcode::Dup, &[]);
6662                }
6663                self.destructure(target, None)?;
6664                self.state().no_value = !keep;
6665                Ok(())
6666            }
6667            _ => Err(SyntaxError::new(
6668                "this assignment target is not supported by the compiler yet",
6669                target.span,
6670            )),
6671        }
6672    }
6673
6674    /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
6675    ///
6676    /// The stack has to carry four values — receiver, prototype, key, value — because
6677    /// `put_super_value` takes them together; the receiver is what makes a setter found on
6678    /// the prototype run with `this`, and the key has to survive until the store, which is
6679    /// why a compound form converts it to a property key once and `dup3`s rather than
6680    /// evaluating it twice.
6681    fn assign_super(
6682        &mut self,
6683        member: &MemberPattern,
6684        op: AssignOp,
6685        value: &Expr,
6686    ) -> Result<(), SyntaxError> {
6687        let saved = self.cur().cur_pos;
6688        self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6689        self.super_base();
6690        match &member.property {
6691            MemberProp::Ident(property) => self.emit(
6692                Opcode::PushAtomValue,
6693                &[Op::Atom(Atom::from_text(&property.name))],
6694            ),
6695            MemberProp::Computed(index) => self.expr(index)?,
6696            MemberProp::Private(_) => {
6697                return Err(SyntaxError::new(
6698                    "private fields are not supported by the compiler yet",
6699                    member.span,
6700                ));
6701            }
6702        }
6703        match op {
6704            AssignOp::Assign => {
6705                // The key is only converted once, by `put_super_value` itself, so a
6706                // computed key's `toString` runs exactly once.
6707                self.expr(value)?;
6708                self.emit(Opcode::Insert4, &[]);
6709                self.emit(Opcode::PutSuperValue, &[]);
6710            }
6711            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6712                let (keep_label, end) = (self.new_label(), self.new_label());
6713                self.emit(Opcode::ToPropkey, &[]);
6714                self.emit(Opcode::Dup3, &[]);
6715                self.emit(Opcode::GetSuperValue, &[]);
6716                self.emit(Opcode::Dup, &[]);
6717                self.emit_logical_test(op);
6718                self.emit_jump(logical_jump(op), keep_label, &[]);
6719                self.emit(Opcode::Drop, &[]);
6720                self.expr(value)?;
6721                self.emit(Opcode::Insert4, &[]);
6722                self.emit(Opcode::PutSuperValue, &[]);
6723                self.emit_jump(Opcode::Goto, end, &[]);
6724                self.place_label(keep_label);
6725                // The prototype and the key are still under the value that was read.
6726                self.emit(Opcode::Nip, &[]);
6727                self.emit(Opcode::Nip, &[]);
6728                self.emit(Opcode::Nip, &[]);
6729                self.place_label(end);
6730            }
6731            _ => {
6732                self.emit(Opcode::ToPropkey, &[]);
6733                self.emit(Opcode::Dup3, &[]);
6734                self.emit(Opcode::GetSuperValue, &[]);
6735                self.expr(value)?;
6736                self.emit(compound_opcode(op), &[]);
6737                self.emit(Opcode::Insert4, &[]);
6738                self.emit(Opcode::PutSuperValue, &[]);
6739            }
6740        }
6741        // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
6742        // is still on the stack when the store finishes, and the expression statement is
6743        // what disposes of it — the same arrangement as `put_field`, reached from the other
6744        // side: there the store consumes the value (`no_value`), here it leaves it
6745        // (`keep` already false, so nothing tells the statement otherwise).
6746        self.state().cur_pos = saved;
6747        Ok(())
6748    }
6749
6750    /// The test a logical assignment applies to the current value.
6751    ///
6752    /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
6753    /// assign, while `0 ||= b` must not.
6754    fn emit_logical_test(&mut self, op: AssignOp) {
6755        if op == AssignOp::Coalesce {
6756            self.emit(Opcode::IsUndefinedOrNull, &[]);
6757        }
6758    }
6759
6760    /// The private name `#name` this use site resolves against.
6761    ///
6762    /// The parser has already rejected a name no enclosing class declares, so a miss here
6763    /// means the compiler lost track of a class scope — which is worth a real error rather
6764    /// than an `unwrap`.
6765    fn private_use(
6766        &self,
6767        binding: &str,
6768        span: Span,
6769    ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
6770        ClassPlan::find(self, binding)
6771            .map(|use_| (use_.kind, use_.setter.clone()))
6772            .ok_or_else(|| {
6773                SyntaxError::new(
6774                    format!("the private name '{binding}' is out of scope here"),
6775                    span,
6776                )
6777            })
6778    }
6779
6780    /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
6781    ///
6782    /// The three readable kinds take three different instructions, because a private name
6783    /// holds three different things — a symbol, a method function, a getter function — and
6784    /// only the first one is a property read at all.
6785    fn private_load(
6786        &mut self,
6787        binding: &str,
6788        kind: PrivateKind,
6789        span: Span,
6790    ) -> Result<(), SyntaxError> {
6791        match kind {
6792            PrivateKind::Field => {
6793                self.emit_var(VarAction::Get, binding);
6794                self.emit(Opcode::GetPrivateField, &[]);
6795            }
6796            PrivateKind::Method => {
6797                self.emit_var(VarAction::Get, binding);
6798                self.emit(Opcode::CheckBrand, &[]);
6799                // `check_brand` reads `obj func` and leaves both; the method itself is what
6800                // `this.#m` evaluates to.
6801                self.emit(Opcode::Nip, &[]);
6802            }
6803            PrivateKind::Getter => {
6804                self.emit_var(VarAction::Get, binding);
6805                self.emit(Opcode::CheckBrand, &[]);
6806                self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6807            }
6808            // `#a` is declared but never filled when only a setter exists, so reading it is
6809            // the same refusal as assigning to a `const`. The reference reports it with the
6810            // generic read-only wording and leaves the better message as a `XXX`.
6811            PrivateKind::Setter => self.emit(
6812                Opcode::ThrowError,
6813                &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
6814            ),
6815        }
6816        let _ = span;
6817        Ok(())
6818    }
6819
6820    /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
6821    fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
6822        match kind {
6823            // A method *is* the callee, so only the check goes in between.
6824            PrivateKind::Method => {
6825                self.emit_var(VarAction::Get, binding);
6826                self.emit(Opcode::CheckBrand, &[]);
6827            }
6828            _ => self.private_load(binding, kind, Span::default())?,
6829        }
6830        Ok(())
6831    }
6832
6833    /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
6834    /// wanted back.
6835    ///
6836    /// A getter/setter pair is a *method call*, not a property store: the reference reads
6837    /// the setter out of its own binding and calls it with the receiver, which is why the
6838    /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
6839    /// keeps the assignment's value for an expression context.
6840    fn private_store(
6841        &mut self,
6842        binding: &str,
6843        kind: PrivateKind,
6844        setter: Option<&str>,
6845    ) -> Result<(), SyntaxError> {
6846        match kind {
6847            PrivateKind::Field => {
6848                self.emit_var(VarAction::Get, binding);
6849                self.emit(Opcode::PutPrivateField, &[]);
6850            }
6851            PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
6852                Some(setter) => {
6853                    self.emit_var(VarAction::Get, setter);
6854                    // `obj func value` -> `value obj func` for the check, and back again for
6855                    // the call, which wants `obj func arg`.
6856                    self.emit(Opcode::Swap, &[]);
6857                    self.emit(Opcode::Rot3r, &[]);
6858                    self.emit(Opcode::CheckBrand, &[]);
6859                    self.emit(Opcode::Rot3l, &[]);
6860                    self.emit(Opcode::CallMethod, &[Op::Int(1)]);
6861                    // The setter's return value is discarded; the assignment's own value is
6862                    // whatever the caller left underneath.
6863                    self.emit(Opcode::Drop, &[]);
6864                }
6865                None => self.emit(
6866                    Opcode::ThrowError,
6867                    &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
6868                ),
6869            },
6870        }
6871        Ok(())
6872    }
6873
6874    fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
6875        let instruction = match (op, prefix) {
6876            (UpdateOp::Increment, true) => Opcode::Inc,
6877            (UpdateOp::Increment, false) => Opcode::PostInc,
6878            (UpdateOp::Decrement, true) => Opcode::Dec,
6879            (UpdateOp::Decrement, false) => Opcode::PostDec,
6880        };
6881        if let ExprKind::Member {
6882            object,
6883            property,
6884            optional: _,
6885        } = &argument.kind
6886        {
6887            // `o.x++` needs the receiver twice, so the last link is read with the
6888            // `get_*2`/`get_*3` form that keeps it, and the update is written back
6889            // with `put_field`/`put_array_el`. The reordering in between is what puts
6890            // the old value below the receiver for a postfix update and the new one
6891            // above it for a prefix one:
6892            //
6893            //   `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
6894            //   `obj val` → `inc`      → `obj new new` → `insert2` → `new obj new`
6895            //
6896            // This mirrors the reference instruction for instruction.
6897            self.expr(object)?;
6898            match property {
6899                MemberProp::Ident(name) => {
6900                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
6901                    self.emit(instruction, &[]);
6902                    self.emit(
6903                        if prefix {
6904                            Opcode::Insert2
6905                        } else {
6906                            Opcode::Perm3
6907                        },
6908                        &[],
6909                    );
6910                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
6911                }
6912                MemberProp::Computed(index) => {
6913                    self.expr(index)?;
6914                    self.emit(Opcode::GetArrayEl3, &[]);
6915                    self.emit(instruction, &[]);
6916                    self.emit(
6917                        if prefix {
6918                            Opcode::Insert3
6919                        } else {
6920                            Opcode::Perm4
6921                        },
6922                        &[],
6923                    );
6924                    self.emit(Opcode::PutArrayEl, &[]);
6925                }
6926                MemberProp::Private(name) => {
6927                    // The receiver is duplicated and the read keeps it, exactly as `get_field2`
6928                    // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
6929                    // `perm3` -> `old obj new` -> store.
6930                    let binding = format!("#{}", name.name);
6931                    let (kind, setter) = self.private_use(&binding, argument.span)?;
6932                    self.emit(Opcode::Dup, &[]);
6933                    self.private_load(&binding, kind, argument.span)?;
6934                    self.emit(instruction, &[]);
6935                    self.emit(
6936                        if prefix {
6937                            Opcode::Insert2
6938                        } else {
6939                            Opcode::Perm3
6940                        },
6941                        &[],
6942                    );
6943                    self.private_store(&binding, kind, setter.as_deref())?;
6944                }
6945            }
6946            return Ok(());
6947        }
6948        let ExprKind::Ident(name) = &argument.kind else {
6949            return Err(SyntaxError::new(
6950                "increment of a non-variable is not supported by the compiler yet",
6951                argument.span,
6952            ));
6953        };
6954        // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
6955        // reference's `inc_loc` folds those three into one, but it does so only in some
6956        // positions (a `for` update and not a bare statement, and never for a lexical
6957        // binding), so emitting it unconditionally would move *away* from its output.
6958        // The instruction is equivalent either way; matching the reference matters more
6959        // than saving two instructions.
6960        let _ = !std::mem::take(&mut self.state().discard_value);
6961        self.emit_var(VarAction::Get, &name.name);
6962        self.emit(instruction, &[]);
6963        if prefix {
6964            self.emit(Opcode::Dup, &[]);
6965        }
6966        self.emit_var(VarAction::Put, &name.name);
6967        Ok(())
6968    }
6969
6970    /// Compile an array literal.
6971    ///
6972    /// The reference splits this into three phases, and the split is load-bearing
6973    /// rather than an optimisation detail:
6974    ///
6975    /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
6976    ///    the array in one instruction.
6977    /// 2. **Everything up to the first spread** is appended with explicit indices
6978    ///    (`define_field <index>`), because a hole has no element to pass to
6979    ///    `array_from`. A hole here is what makes `length` need fixing up: an
6980    ///    explicit index does not extend the array the way a pushed element does.
6981    /// 3. **From the first spread on** the index lives on the stack, so `append` and
6982    ///    `define_array_el` can consume it and `inc` advances it.
6983    ///
6984    /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
6985    /// forces phase 2, and `[...a]` forces phase 3.
6986    fn array_literal(
6987        &mut self,
6988        elements: &[Option<ArrayElement>],
6989        span: Span,
6990    ) -> Result<(), SyntaxError> {
6991        let _ = span;
6992        let mut index: u32 = 0;
6993        let mut cursor = 0usize;
6994
6995        // Phase 1: a leading run of plain elements, at most 32 of them.
6996        while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
6997            if index >= 32 {
6998                break;
6999            }
7000            self.expr(element)?;
7001            index += 1;
7002            cursor += 1;
7003        }
7004        self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
7005
7006        // Phase 2: explicit indices, up to the first spread.
7007        let mut need_length = false;
7008        while let Some(element) = elements.get(cursor) {
7009            if matches!(element, Some(ArrayElement::Spread(_))) {
7010                break;
7011            }
7012            need_length = true;
7013            if let Some(ArrayElement::Expr(expression)) = element {
7014                self.expr(expression)?;
7015                self.emit_define_index(index);
7016                need_length = false;
7017            }
7018            index += 1;
7019            cursor += 1;
7020        }
7021
7022        if cursor >= elements.len() {
7023            if need_length {
7024                // `define_field` cannot set `length`, which is not configurable.
7025                self.emit(Opcode::Dup, &[]);
7026                self.push_number(index as f64);
7027                self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7028            }
7029            return Ok(());
7030        }
7031
7032        // Phase 3: the index moves onto the stack for the spreading tail.
7033        //
7034        // `need_length` deliberately carries over from phase 2: a hole before the
7035        // first spread still has to be reflected in `length`, and only the final
7036        // check can do it because the array is not finished until the tail is
7037        // appended.
7038        self.push_number(index as f64);
7039        while let Some(element) = elements.get(cursor) {
7040            match element {
7041                Some(ArrayElement::Spread(expression)) => {
7042                    // `append` copies an iterable and leaves the next index behind,
7043                    // so no `inc` is needed here.
7044                    self.expr(spread_argument(expression))?;
7045                    self.emit(Opcode::Append, &[]);
7046                }
7047                None | Some(ArrayElement::Expr(_)) => {
7048                    need_length = true;
7049                    if let Some(ArrayElement::Expr(expression)) = element {
7050                        self.expr(expression)?;
7051                        self.emit(Opcode::DefineArrayEl, &[]);
7052                        need_length = false;
7053                    }
7054                    self.emit(Opcode::Inc, &[]);
7055                }
7056            }
7057            cursor += 1;
7058        }
7059        if need_length {
7060            self.emit(Opcode::Dup1, &[]);
7061            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7062        } else {
7063            self.emit(Opcode::Drop, &[]);
7064        }
7065        Ok(())
7066    }
7067
7068    /// `define_field` with an array-index atom, which is how phase 2 stores elements.
7069    fn emit_define_index(&mut self, index: u32) {
7070        self.emit(
7071            Opcode::DefineField,
7072            &[Op::Atom(Atom::from_text(&index.to_string()))],
7073        );
7074    }
7075
7076    // -- functions ---------------------------------------------------------
7077
7078    fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
7079        self.compile_function_with_name(func, false)
7080    }
7081
7082    /// Compile a function, recording whether it is a *named function expression*.
7083    ///
7084    /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
7085    /// must not leak outside. The reference does that by declaring `g` as a local of
7086    /// the function itself and initialising it with `special_object 2` (the current
7087    /// function), which is why this has to be known at compile time.
7088    fn compile_function_with_name(
7089        &mut self,
7090        func: &ast::Function,
7091        is_expression: bool,
7092    ) -> Result<CompiledFunction, SyntaxError> {
7093        let kind = match (func.is_generator, func.is_async) {
7094            (false, false) => FunctionKind::Normal,
7095            (true, false) => FunctionKind::Generator,
7096            (false, true) => FunctionKind::Async,
7097            (true, true) => FunctionKind::AsyncGenerator,
7098        };
7099        let mut state = FnState::new(
7100            func.name
7101                .as_ref()
7102                .map(|n| n.name.clone())
7103                .unwrap_or_default(),
7104            kind,
7105        );
7106        // The function's own mode, recorded by the parser. Inheriting the enclosing
7107        // function's instead let a nested `"use strict"` directive be ignored, so the
7108        // body ran with sloppy `this`, sloppy `arguments` and no const checks.
7109        state.strict = func.strict;
7110        // A function defined inside a `with` block keeps seeing that object: the guard
7111        // chain names the enclosing `<with>` locals, which resolve outward into closure
7112        // variables exactly like any other captured binding.
7113        state.with_names = self.cur().with_names.clone();
7114        state.is_arrow = func.is_arrow;
7115        state.created_in_block = self.cur().current_block;
7116        // A default anywhere in the parameter list is what gives the function two
7117        // variable environments. The reference decides this the same way: it scans the
7118        // parenthesis for a top-level `=`, so a destructured name without a default
7119        // stays a plain function-scope binding.
7120        state.in_params = false;
7121        // The reference scans the parenthesis for *any* `=`, including one nested inside
7122        // a pattern, so `function f({a = 1})` has parameter expressions even though the
7123        // parameter itself carries no initialiser.
7124        state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
7125        // `IsSimpleParameterList`: no default, no rest, no destructuring. Unlike the
7126        // flag above this looks at the *shape* of each parameter, not just for `=`.
7127        state.simple_parameter_list = func
7128            .params
7129            .iter()
7130            .all(|pattern| matches!(pattern.kind, PatternKind::Ident(_)));
7131        // A function born inside a parameter list inherits the prohibition: it must not
7132        // see the body bindings of the function it was created in.
7133        state.created_in_params = self.cur().in_params || self.cur().created_in_params;
7134        // A class constructor knows what it is only because the class told it.
7135        if let Some(kind) = self.cur().class_ctor_pending {
7136            state.ctor_kind = kind;
7137        }
7138        // A named *expression* binds its own name; a declaration's name is already
7139        // bound in the enclosing scope.
7140        state.self_name = if is_expression && !func.is_arrow {
7141            func.name.as_ref().map(|n| n.name.clone())
7142        } else {
7143            None
7144        };
7145        // Keep the written range so `Function.prototype.toString` can answer with the
7146        // original text rather than `[native code]`.
7147        //
7148        // It starts at the *parameter list*, not at the function: §20.2.3.5 removes the
7149        // accessor and generator prefixes, and for a method it must not include the name
7150        // or a leading `static`. `params_span` is exactly that boundary.
7151        // A *method* keeps the old `[native code]` answer: its reported text is defined
7152        // by the method-definition grammar (no name, no `static`, no `get`/`set`, but
7153        // the comments in between kept verbatim), and reconstructing that from a byte
7154        // span got it wrong in more cases than it got right. A plain function and an
7155        // arrow are the shapes libraries actually introspect, and those are exact.
7156        let method = is_method_syntax(self.source.as_deref(), func);
7157        state.span = if method {
7158            None
7159        } else {
7160            Some((
7161                func.span.start.offset as usize,
7162                func.span.end.offset as usize,
7163            ))
7164        };
7165        state.line = func.span.start.line;
7166        state.column = func.span.start.column;
7167        // A function body has no hidden `<ret>` local; the value comes back on
7168        // the stack. Only a script keeps one.
7169        // Parameters are positional, so even a pattern occupies one argument slot. A
7170        // simple name is that slot itself; anything else (a pattern, a default, a rest
7171        // parameter) takes an anonymous slot and is unpicked into locals at the top of
7172        // the body, which is the only way one argument can bind several names.
7173        let mut prologue: Vec<(usize, Pattern)> = Vec::new();
7174        // `.length` stops at the first parameter that can be substituted: a default
7175        // fills a missing argument in, and a rest parameter absorbs the rest.
7176        let mut defined_args = func.params.len() as u32;
7177        for (index, param) in func.params.iter().enumerate() {
7178            match simple_parameter(param) {
7179                Some(name) => state.args.push(VarDef::var(name.name.clone())),
7180                None => {
7181                    state.args.push(VarDef::var(ANONYMOUS_BINDING));
7182                    prologue.push((index, param.clone()));
7183                }
7184            }
7185        }
7186        // A default anywhere before the end also ends the count, which the loop above
7187        // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
7188        for (position, param) in func.params.iter().enumerate() {
7189            if matches!(
7190                param.kind,
7191                PatternKind::Assign { .. } | PatternKind::Rest(_)
7192            ) {
7193                defined_args = position as u32;
7194                break;
7195            }
7196        }
7197        state.defined_args = defined_args;
7198        state.param_prologue = prologue;
7199        let depth = self.stack.len();
7200        self.stack.push(state);
7201        let result = self.compile_function_body(func);
7202        if result.is_err() {
7203            // A failed compile must not leave its `FnState` behind. Every caller
7204            // reads `self.state()` as "the function being compiled", so a leftover
7205            // frame silently retargets all later bookkeeping at a dead function.
7206            self.stack.truncate(depth);
7207        }
7208        result
7209    }
7210
7211    /// The body of a function, with its frame already pushed.
7212    fn compile_function_body(
7213        &mut self,
7214        func: &ast::Function,
7215    ) -> Result<CompiledFunction, SyntaxError> {
7216        let body_key = func.params_span.end.offset as u64;
7217        // Where the body begins, in source order. The runtime needs this to tell a
7218        // closure created by a default expression from one the body creates — the two see
7219        // different variable environments — and a bytecode offset would not survive the
7220        // instruction shuffling that building the frame does. Positions are in source
7221        // order, so a comparison answers it.
7222        self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
7223        self.push_block(body_key, NO_PARENT);
7224        self.state().body_block = body_key;
7225        // An arrow with an expression body has no statements; the expression is
7226        // its `return`. Building the statement here keeps one code path below, and
7227        // matters for correctness beyond convenience: returning early with the new
7228        // `FnState` still on the stack would leave the compiler looking at the
7229        // wrong function, which surfaces as an unrelated underflow later.
7230        let concise = match &func.body {
7231            js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
7232                StmtKind::Return(Some(Box::new((**value).clone()))),
7233                value.span,
7234            )),
7235            js_parse::ast::FunctionBody::Block(_) => None,
7236        };
7237        let body: &[Stmt] = match &concise {
7238            Some(stmt) => std::slice::from_ref(stmt),
7239            None => func
7240                .body
7241                .statements()
7242                .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
7243        };
7244        let prologue = std::mem::take(&mut self.state().param_prologue);
7245        let has_param_scope = self.cur().has_parameter_expressions;
7246        // The parameter scope's own bindings, declared in source order.
7247        //
7248        // With parameter expressions the list gets a variable environment of its own, and
7249        // every name it binds is a `let` there. That is what puts the *list* in the
7250        // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
7251        // and `function f(x = y, y){}` does the same, where a single shared environment
7252        // would answer `undefined` to both.
7253        if has_param_scope {
7254            let mut declared: Vec<String> = Vec::new();
7255            for param in &func.params {
7256                let mut names = Vec::new();
7257                param.bound_names(&mut names);
7258                for name in names {
7259                    if declared.contains(&name.name) {
7260                        continue;
7261                    }
7262                    declared.push(name.name.clone());
7263                    self.declare_param_binding(&name.name);
7264                }
7265            }
7266        }
7267        // A pattern parameter binds its names as function-scope locals, so they have to
7268        // exist — and be unpicked from the argument — before the body runs. With a
7269        // parameter scope these are the *second* environment: the pattern fills the
7270        // parameter's copy, and the body's binding is filled from it afterwards.
7271        for (_, pattern) in &prologue {
7272            let mut names = Vec::new();
7273            pattern.bound_names(&mut names);
7274            for name in names {
7275                self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
7276            }
7277        }
7278        self.hoist(body, body_key)?;
7279        // A constructor's prologue is not a parameter unpacking but the `this` binding:
7280        // a base constructor takes the receiver, a derived one starts in the dead zone
7281        // because only `super()` may produce it.
7282        match self.cur().ctor_kind {
7283            CtorKind::None => {}
7284            CtorKind::Base => {
7285                self.begin_this_local();
7286                self.emit(Opcode::CheckCtor, &[]);
7287                // Instance fields are installed at the top of a base constructor's body,
7288                // before any statement — `class C { x = 1; constructor() { this.x } }` sees
7289                // `1`. This used to be emitted at the *tail*, which made every field read
7290                // `undefined` inside the constructor that declared it.
7291                self.call_field_initialiser();
7292            }
7293            CtorKind::Derived => {
7294                self.declare("this", VarDef::lexical("this"));
7295                let slot = self.cur().vars.len() as u32 - 1;
7296                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7297                self.emit(Opcode::CheckCtor, &[]);
7298            }
7299        }
7300        // Entering the parameter list: everything it binds starts in the dead zone.
7301        // The order is the reference's — it walks the scope chain, which is prepended, so
7302        // the bindings come out newest first.
7303        for name in self.param_binding_names().into_iter().rev() {
7304            if let Some(slot) = self.param_binding_slot(&name) {
7305                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7306            }
7307        }
7308        // The whole parameter list is one scope, and nothing in the body exists yet, so
7309        // every name it mentions resolves against the parameter bindings and outward.
7310        self.state().in_params = has_param_scope;
7311        for (index, param) in func.params.iter().enumerate() {
7312            if let Some(pattern) = prologue_pattern(&prologue, index) {
7313                // A destructuring parameter *initialises* its bindings: with a parameter
7314                // scope they are the list's own `let`s, which is why the stores skip the
7315                // dead-zone check, and why the reference reads their properties with
7316                // `get_field2` — a `let` needs no reference.
7317                let kind = if has_param_scope {
7318                    VarDeclKind::Let
7319                } else {
7320                    VarDeclKind::Var
7321                };
7322                match &pattern.kind {
7323                    // `...rest` collects what is left rather than reading one slot.
7324                    PatternKind::Rest(inner) => {
7325                        self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7326                        self.destructure(inner, Some(kind))?;
7327                    }
7328                    _ => {
7329                        self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7330                        self.destructure(pattern, Some(kind))?;
7331                    }
7332                }
7333                continue;
7334            }
7335            // A plain name binds straight from its argument slot. With a parameter scope
7336            // the slot is also copied into the parameter binding, which is what a later
7337            // default (or a closure made among the defaults) reads.
7338            let Some(name) = simple_parameter(param) else {
7339                continue;
7340            };
7341            let target = self.param_binding_slot(&name.name);
7342            if matches!(param.kind, PatternKind::Rest(_)) {
7343                self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7344                if let Some(slot) = target {
7345                    self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
7346                }
7347                // `put_arg` rather than `set_arg`: the array is the last thing on the
7348                // stack and nothing keeps it. Named by hand because a name in the
7349                // parameter list resolves to the parameter binding, and this store has to
7350                // reach the *argument* — that is what the body reads.
7351                self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
7352                continue;
7353            }
7354            if let PatternKind::Assign { default, .. } = &param.kind {
7355                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7356                let has_value = self.new_label();
7357                self.emit(Opcode::Dup, &[]);
7358                self.emit(Opcode::IsUndefined, &[]);
7359                self.emit_jump(Opcode::IfFalse, has_value, &[]);
7360                self.emit(Opcode::Drop, &[]);
7361                self.expr(default)?;
7362                self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
7363                // The argument slot keeps the substituted value, because the *body* reads
7364                // the slot rather than the parameter binding — so this store is named
7365                // explicitly, like the rest parameter's.
7366                self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7367                self.place_label(has_value);
7368                if let Some(slot) = target {
7369                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7370                }
7371                continue;
7372            }
7373            if let Some(slot) = target {
7374                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7375                self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7376            }
7377        }
7378        // Copy the parameter scope into the body. A plain parameter needs nothing: the
7379        // body reads its argument slot, and the list kept the two in step. A name a
7380        // pattern bound has no argument slot of its own, so the body gets a `var` filled
7381        // from the parameter's copy — and *that* is why an assignment inside a default
7382        // does not reach the body.
7383        if has_param_scope {
7384            for (_, pattern) in &prologue {
7385                let mut names = Vec::new();
7386                pattern.bound_names(&mut names);
7387                for name in names {
7388                    let Some(slot) = self.param_binding_slot(&name.name) else {
7389                        continue;
7390                    };
7391                    let Some(body) = self.body_var_slot(&name.name) else {
7392                        continue;
7393                    };
7394                    self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
7395                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
7396                }
7397            }
7398        }
7399        // The parameter list is over; from here on a direct `eval` belongs to the body.
7400        self.state().in_params = false;
7401        // Entering the body's own scope comes *after* the parameter list: the body's
7402        // `let`s are not in existence while the defaults run, and the reference emits
7403        // their `set_loc_uninitialized` only once the parameters are bound.
7404        self.emit_scope_enter(body_key);
7405        // A generator starts suspended: `initial_yield` parks the body so that creating one
7406        // runs no body code until the first `next()`.
7407        //
7408        // It comes *after* the parameter unpacking, not before, because a parameter
7409        // initialiser is not body code — `function* g(a = sideEffect())` must run
7410        // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
7411        // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
7412        // until the first `next()` and 29 test262 cases that check for a synchronous throw
7413        // saw none at all.
7414        //
7415        // An async function does **not** get one. Its body runs synchronously up to the
7416        // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
7417        // before its caller's next statement — so an `initial_yield` here would park the
7418        // body before it started, which is not fixable at run time: the suspension looks
7419        // exactly like a real `await`.
7420        if self.cur().kind.is_generator() {
7421            self.emit(Opcode::InitialYield, &[]);
7422        }
7423        // Through `stmts`: the body is a block, and a `using` declaration in it is a
7424        // disposal region.
7425        self.stmts(body)?;
7426        // The implicit return only exists if control can actually get here: an
7427        // infinite loop never falls off the end.
7428        if self.end_is_reachable() {
7429            if self.cur().is_suspending() {
7430                // Falling off the end finishes the generator with `undefined`, and the
7431                // value is what tells the resume machinery "completed" rather than
7432                // "suspended".
7433                self.emit(Opcode::Undefined, &[]);
7434                self.emit(Opcode::ReturnAsync, &[]);
7435            } else {
7436                self.emit_class_constructor_tail();
7437            }
7438        }
7439        // Resolution runs while this function is still on the stack: capturing a
7440        // variable from an enclosing function means reaching into that
7441        // function's state, which requires the whole chain to be present.
7442        Ok(self.finish_current())
7443    }
7444
7445    /// Put every binding of a function that contains a direct `eval` into a cell.
7446    ///
7447    /// A direct eval can name any binding in scope, and any closure it creates has to
7448    /// keep sharing that binding after the function returns — `for (let i …)
7449    /// eval("push(() => i)")` collects one closure per iteration and each must read its
7450    /// own `i`. A copy in a side table would freeze the value, so the binding has to be
7451    /// a cell. Doing this unconditionally for such functions is the cheap, honest
7452    /// answer: the alternative is knowing at compile time which names a string will
7453    /// mention.
7454    fn capture_everything_for_eval(&mut self) {
7455        let current = self.stack.len() - 1;
7456        if !self.stack[current].has_direct_eval {
7457            return;
7458        }
7459        for arg in &mut self.stack[current].args {
7460            arg.is_captured = true;
7461        }
7462        for var in &mut self.stack[current].vars {
7463            var.is_captured = true;
7464        }
7465    }
7466
7467    /// Whether the current position in the instruction stream can be reached.
7468    ///
7469    /// A walk over the control-flow graph, using labels as instruction indices.
7470    /// The reference does the same thing to decide whether an implicit
7471    /// `return_undef` is needed.
7472    fn end_is_reachable(&self) -> bool {
7473        let state = self.cur();
7474        reachable_instructions(state, state.insns.len())[state.insns.len()]
7475    }
7476
7477    /// Resolve and assemble the function on top of the compiler stack, then pop
7478    /// it.
7479    fn finish_current(&mut self) -> CompiledFunction {
7480        self.provide_param_arguments();
7481        self.provide_arguments();
7482        self.provide_this_local();
7483        self.provide_new_target_local();
7484        self.provide_home_object_local();
7485        self.provide_active_func_local();
7486        self.provide_self_name();
7487        self.materialize_eval_sites();
7488        self.capture_everything_for_eval();
7489        let (mut resolved, resolved_pos) = resolve(&mut self.stack);
7490        // Captured bindings need a reference cell; the count goes in the header so
7491        // the runtime knows how many cells to allocate on entry.
7492        let current = self.stack.len() - 1;
7493        let captured = self.stack[current]
7494            .args
7495            .iter()
7496            .filter(|a| a.is_captured)
7497            .count()
7498            + self.stack[current]
7499                .vars
7500                .iter()
7501                .filter(|v| v.is_captured)
7502                .count();
7503        self.stack[current].var_ref_count = captured as u32;
7504        // The scope chain is only final now that every binding is known.
7505        rebuild_scope_chain(&mut self.stack[current]);
7506        let (code, stack_size, positions) =
7507            assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
7508        let _ = &mut resolved;
7509        let mut state = self.stack.pop().expect("a function is being compiled");
7510        CompiledFunction {
7511            name: state.name,
7512            kind: state.kind,
7513            strict: state.strict,
7514            is_arrow: state.is_arrow,
7515            has_parameter_expressions: state.has_parameter_expressions,
7516            simple_parameter_list: state.simple_parameter_list,
7517            body_start: state.body_start,
7518            args: state.args,
7519            defined_args: state.defined_args,
7520            vars: state.vars,
7521            closure_vars: state.closure_vars,
7522            cpool: state.cpool,
7523            atoms: state.atoms,
7524            code,
7525            stack_size,
7526            var_ref_count: state.var_ref_count,
7527            positions,
7528            source: self.function_source(state.span, state.line, state.column),
7529            line: state.line,
7530            column: state.column,
7531            filename: None,
7532            eval_sites: state.eval_sites,
7533            module: state.module.take().map(Box::new),
7534        }
7535    }
7536}
7537
7538/// Assign each binding a scope level and rebuild the scope chains.
7539///
7540/// Levels are numbered in the order the blocks appear, with 0 reserved for the
7541/// function scope where `var` and hoisted functions live. Every binding outside
7542/// level 0 gets a `scope_next` link to the next binding visible from the same
7543/// point, so walking a block's chain enumerates exactly the bindings live there.
7544///
7545/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
7546/// point at `b`, which is declared later in the source but earlier in the chain.
7547fn rebuild_scope_chain(state: &mut FnState) {
7548    // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
7549    // real block that happens to start at offset zero keeps its own level instead of
7550    // being merged into the function scope.
7551    let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
7552    for block in &state.blocks {
7553        if !levels.contains(&block.key) {
7554            levels.push(block.key);
7555        }
7556    }
7557    let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
7558    let parent_level = |level: usize| -> usize {
7559        if level == 0 {
7560            return 0;
7561        }
7562        let key = levels[level];
7563        let parent = state
7564            .blocks
7565            .iter()
7566            .find(|b| b.key == key)
7567            .map(|b| b.parent)
7568            .unwrap_or(FUNCTION_SCOPE);
7569        level_of(parent)
7570    };
7571
7572    // Own bindings per level, in declaration order.
7573    let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
7574    let keys: Vec<u64> = (0..state.vars.len())
7575        .map(|index| {
7576            state
7577                .var_block
7578                .get(index)
7579                .copied()
7580                .unwrap_or(FUNCTION_SCOPE)
7581        })
7582        .collect();
7583    for (index, key) in keys.into_iter().enumerate() {
7584        // The parameter scope is not a block: it is a level of its own with no parent,
7585        // assigned below. Letting it land in level 0 would chain the body's bindings onto
7586        // it, which the reference does not do — the two environments are siblings.
7587        if key == PARAM_SCOPE {
7588            continue;
7589        }
7590        let level = level_of(key);
7591        state.vars[index].scope_level = level as u32;
7592        // A `catch` parameter is part of the runtime scope chain even though it is
7593        // not lexical: the handler's own bindings chain on to it, which is why the
7594        // reference prints `let y [next:1]` with `e` at 1.
7595        if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
7596        {
7597            own[level].push(index);
7598        }
7599    }
7600
7601    // A scope's chain is its own bindings in reverse declaration order followed
7602    // by the enclosing scope's chain.
7603    let mut head = vec![-1i32; levels.len()];
7604    for level in 0..levels.len() {
7605        let inherited = if level == 0 {
7606            -1
7607        } else {
7608            head[parent_level(level)]
7609        };
7610        let chain: Vec<usize> = own[level].iter().rev().copied().collect();
7611        head[level] = chain.first().map_or(inherited, |first| *first as i32);
7612        for (position, &index) in chain.iter().enumerate() {
7613            let next = chain
7614                .get(position + 1)
7615                .map_or(inherited, |next| *next as i32);
7616            state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
7617        }
7618    }
7619    state.block_heads = head;
7620
7621    // The parameter list is a scope of its own, and it has no parent: the reference pops
7622    // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
7623    // the `-1` a block uses. A level past every real block keeps it out of the walk above
7624    // — nothing but the dump reads it — and the links run newest-to-oldest through the
7625    // bindings themselves, which is the order `set_loc_uninitialized` walks.
7626    let param_level = levels.len() as u32;
7627    let mut previous: Option<usize> = None;
7628    for index in 0..state.vars.len() {
7629        if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
7630        {
7631            continue;
7632        }
7633        state.vars[index].scope_level = param_level;
7634        state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
7635        previous = Some(index);
7636    }
7637}
7638
7639/// This is where names become slots and where the temporal dead zone shows up in
7640/// the instruction stream: a read of a `let`/`const` binding compiles to
7641/// `get_loc_check`, which throws if the binding is still uninitialised.
7642///
7643/// The peephole pass from the reference implementation is applied at the end,
7644/// for the same reason it is applied to resolved bytecode there: the patterns are
7645/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
7646/// resolution. Deleted instructions stay in the list as `None` so that label
7647/// indices remain valid; [`Assembler`] maps them to byte offsets.
7648/// A resolved instruction and the source position it came from.
7649type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
7650
7651/// A resolved instruction paired with its position, which is what `assemble` consumes.
7652type PositionedInsn = (Opcode, Vec<Op>);
7653
7654fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
7655    let current = stack.len() - 1;
7656    // Dead-code elimination, on the symbolic form where labels are still
7657    // instruction indices. A `break` inside a loop leaves the trailing `goto`
7658    // unreachable, and a `return` leaves everything after it unreachable; the
7659    // reference drops both. Doing it here means the emitter never has to think
7660    // about reachability.
7661    strip_empty_gosubs(stack, current);
7662    eliminate_dead_code(stack, current);
7663    let insns = std::mem::take(&mut stack[current].insns);
7664    // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
7665    // `insns`, and every arm below pushes exactly one instruction, so the positions
7666    // stay aligned with `out`.
7667    let positions = std::mem::take(&mut stack[current].insn_pos);
7668    let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
7669    let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
7670    for (index, insn) in insns.iter().enumerate() {
7671        let pos = positions.get(index).copied().flatten();
7672        out_pos.push(pos);
7673        match insn {
7674            Insn::Fixed { op, operands } => {
7675                let operands = operands
7676                    .iter()
7677                    .map(|operand| match operand {
7678                        Op::Atom(atom) => {
7679                            Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
7680                        }
7681                        other => other.clone(),
7682                    })
7683                    .collect();
7684                out.push(Some((*op, operands)));
7685            }
7686            Insn::Var {
7687                action,
7688                name,
7689                block,
7690                in_params,
7691            } => {
7692                // Both reads and writes in the parameter list address the parameter
7693                // scope. That is what puts the list in the temporal dead zone — a read of
7694                // a later parameter is `get_loc_check` on an uninitialised slot — and it
7695                // is also what keeps an assignment made inside a default away from the
7696                // body, which sees a separate environment.
7697                let slot = resolve_slot(stack, current, name, *block, *in_params);
7698                // A store to the name of a named function expression is special: the
7699                // reference drops it in sloppy mode and throws in strict mode, because
7700                // the binding is immutable but only *checked* when the body is strict.
7701                // The same rule applies when the name is reached through a closure:
7702                // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
7703                // the store in the arrow too, not just in the function that owns the
7704                // binding. Reaching the owner means walking the chain of closure
7705                // entries, which is what `self_name_binding` does.
7706                let self_name = matches!(action, VarAction::Put | VarAction::Set)
7707                    .then(|| {
7708                        // A local of this function is the common case and needs no
7709                        // chain walk; only an access that resolves elsewhere can be
7710                        // pointing at an enclosing function's name binding.
7711                        if let Slot::Loc(index) = slot {
7712                            stack[current]
7713                                .vars
7714                                .get(index as usize)
7715                                .filter(|var| var.kind == VarKind::FunctionName)
7716                                .map(|var| var.is_const)
7717                        } else {
7718                            self_name_binding(stack, current, name, *block)
7719                        }
7720                    })
7721                    .flatten();
7722                if let Some(is_const) = self_name {
7723                    out.push(Some(if is_const {
7724                        (
7725                            Opcode::ThrowError,
7726                            vec![
7727                                Op::AtomId(intern_atom(&mut stack[current], name)),
7728                                Op::Int(0),
7729                            ],
7730                        )
7731                    } else {
7732                        (Opcode::Drop, Vec::new())
7733                    }));
7734                    continue;
7735                }
7736                out.push(Some(variable_instruction(stack, current, *action, slot)));
7737            }
7738            Insn::CloseCaptured { name, block } => {
7739                // The block matters: a loop variable is scoped to the `for` head's own
7740                // block, so resolving it against block 0 would miss it entirely and
7741                // silently emit nothing.
7742                let slot = resolve_slot(stack, current, name, *block, false);
7743                // Only a local with a reference cell has anything to close. A global
7744                // or a never-captured local resolves to no instruction at all, which
7745                // keeps the bytecode identical to the reference's.
7746                if let Slot::Loc(index) = slot
7747                    && stack[current]
7748                        .vars
7749                        .get(index as usize)
7750                        .is_some_and(|v| v.is_captured)
7751                {
7752                    out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
7753                } else {
7754                    out.push(None);
7755                }
7756            }
7757            Insn::DeleteVar { name } => {
7758                // A binding — a local, an argument, or a declared global — cannot be
7759                // deleted, and the reference encodes that as a constant `push_false`.
7760                // Only an implicit global needs the runtime lookup.
7761                if matches!(
7762                    resolve_slot(stack, current, name, 0, false),
7763                    Slot::Global(_)
7764                ) {
7765                    let atom = intern_atom(&mut stack[current], name);
7766                    out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
7767                } else {
7768                    out.push(Some((Opcode::PushFalse, Vec::new())));
7769                }
7770            }
7771            Insn::Dead => out.push(None),
7772        }
7773    }
7774    // Which label (if any) sits on each instruction, so the jump patterns can
7775    // tell whether they would cross a jump target.
7776    let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
7777    for (id, placed) in stack[current].labels.iter().enumerate() {
7778        if let Some(index) = *placed
7779            && index < label_at.len()
7780            && label_at[index].is_none()
7781        {
7782            label_at[index] = Some(id as u32);
7783        }
7784    }
7785    if std::env::var_os("QJS_DEBUG").is_some() {
7786        eprintln!("--- peephole entry ---");
7787        for (i, e) in out.iter().enumerate() {
7788            eprintln!("{i}: {e:?}");
7789        }
7790        eprintln!("label_at: {label_at:?}");
7791    }
7792    peephole(&mut out, &label_at, &stack[current].labels);
7793    (out, out_pos)
7794}
7795
7796/// Find where `name` lives, capturing it in an enclosing function when needed.
7797///
7798/// The search runs outward through the enclosing functions' states, which are
7799/// still on the compiler stack while a nested function is resolved. Finding the
7800/// name in an enclosing function is what creates a closure reference, and every
7801/// function in between has to forward it — a function can only reach its own
7802/// parent's frame.
7803///
7804/// A name declared nowhere is a global. The reference does *not* look it up by
7805/// name from the inner function: the top-level function gets one `[global]`
7806/// entry and every nested function gets a `[global_ref<n>]` pointing at its
7807/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
7808/// rather than `[global]`.
7809/// The lexical blocks enclosing `block`, innermost first.
7810fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
7811    let mut chain = Vec::new();
7812    let mut current = Some(block);
7813    while let Some(key) = current {
7814        // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
7815        // explicitly (rather than on "no block with this key") is what keeps a block
7816        // that happens to sit at offset zero from being mistaken for the terminator.
7817        if key == NO_PARENT || chain.contains(&key) {
7818            break;
7819        }
7820        chain.push(key);
7821        current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
7822    }
7823    chain
7824}
7825
7826/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
7827///
7828/// The binding may be several functions away: an arrow nested in `function myfunc`
7829/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
7830/// means following `Ref` entries down and then reading the owning function's var table.
7831fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
7832    let state = stack.get(current)?;
7833    // A parameter shadows everything and is never a function-expression name.
7834    if state.args.iter().any(|arg| arg.name == name) {
7835        return None;
7836    }
7837    // A local of this very function: the answer is in its var table.
7838    if let Some(index) = local_slot_index(state, name, block) {
7839        let var = state.vars.get(index)?;
7840        return (var.kind == VarKind::FunctionName).then_some(var.is_const);
7841    }
7842    // Otherwise the name lives further out, and the closure entry says how to get
7843    // there. `Local` names the owner's slot directly; `Ref` names the next level's
7844    // closure entry, so the walk continues downwards.
7845    let mut level = current;
7846    let mut index = state
7847        .closure_vars
7848        .iter()
7849        .position(|closure| closure.name == name)?;
7850    loop {
7851        let state = stack.get(level)?;
7852        let closure = state.closure_vars.get(index)?;
7853        match closure.closure_type {
7854            ClosureType::Local => {
7855                let owner = stack.get(level.checked_sub(1)?)?;
7856                let var = owner.vars.get(closure.var_idx as usize)?;
7857                return (var.kind == VarKind::FunctionName).then_some(var.is_const);
7858            }
7859            ClosureType::Arg => return None,
7860            ClosureType::Ref => {
7861                level -= 1;
7862                index = closure.var_idx as usize;
7863            }
7864            // A global is never a function-expression name.
7865            ClosureType::Global
7866            | ClosureType::GlobalDecl
7867            | ClosureType::GlobalRef
7868            | ClosureType::ModuleDecl
7869            | ClosureType::ModuleImport => return None,
7870        }
7871    }
7872}
7873
7874/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
7875fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
7876    block_chain(state, block).into_iter().find_map(|scope| {
7877        state.vars.iter().enumerate().find_map(|(index, var)| {
7878            (var.name == name && state.var_block.get(index).copied() == Some(scope))
7879                .then_some(index)
7880        })
7881    })
7882}
7883
7884/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
7885fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
7886    if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
7887        var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
7888    }) {
7889        return index as u32;
7890    }
7891    state.var_block.push(PARAM_SCOPE);
7892    state.vars.push(VarDef::var(name));
7893    state.vars.len() as u32 - 1
7894}
7895
7896/// The name a parameter binds straight from its argument slot, if it has one.
7897///
7898/// A plain name does — with or without a default, and with or without `...`. Everything
7899/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
7900/// reference names the argument in the first case and leaves it `<null>` in the second,
7901/// so both the dump and the closures that capture the argument depend on this.
7902fn simple_parameter(param: &Pattern) -> Option<&Ident> {
7903    match &param.kind {
7904        PatternKind::Ident(name) => Some(name),
7905        PatternKind::Assign { target, .. } => match &target.kind {
7906            PatternKind::Ident(name) => Some(name),
7907            _ => None,
7908        },
7909        PatternKind::Rest(inner) => match &inner.kind {
7910            PatternKind::Ident(name) => Some(name),
7911            _ => None,
7912        },
7913        _ => None,
7914    }
7915}
7916
7917/// The pattern a parameter list has to unpick, if `index` is one of them.
7918fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
7919    prologue
7920        .iter()
7921        .find(|(at, _)| *at == index)
7922        .map(|(_, pattern)| pattern)
7923}
7924
7925/// Whether a parameter pattern contains a default anywhere, at any depth.
7926///
7927/// The reference decides "this function has parameter expressions" by scanning the
7928/// parenthesis for a top-level `=`, which a default buried in a pattern still counts as —
7929/// `function f({a = 1})` has a parameter scope just like `function f(a = 1)`.
7930/// Whether a function was written in *method* position, which `Function.prototype.toString`
7931/// reports without the leading name or modifiers.
7932///
7933/// The AST does not record this — a method is compiled as an ordinary `Function` — so it
7934/// is read back off the source: everything between the start of the definition and its
7935/// parameter list. A `function` keyword there means a function expression or declaration;
7936/// the absence of one means `m(){}`, `static m(){}`, `get x(){}` and friends.
7937fn is_method_syntax(source: Option<&str>, func: &ast::Function) -> bool {
7938    let Some(source) = source else {
7939        return false;
7940    };
7941    let start = func.span.start.offset as usize;
7942    let params = func.params_span.start.offset as usize;
7943    if start >= params {
7944        return false;
7945    }
7946    let Some(head) = source.get(start..params) else {
7947        return false;
7948    };
7949    !head.contains("function")
7950}
7951
7952fn pattern_has_default(pattern: &Pattern) -> bool {
7953    match &pattern.kind {
7954        PatternKind::Assign { .. } => true,
7955        PatternKind::Rest(inner) => pattern_has_default(inner),
7956        PatternKind::Array { elements, rest } => {
7957            elements.iter().flatten().any(element_has_default)
7958                || rest.as_deref().is_some_and(rest_has_default)
7959        }
7960        PatternKind::Object { properties, rest } => {
7961            properties.iter().flatten().any(element_has_default)
7962                || rest.as_deref().is_some_and(rest_has_default)
7963        }
7964        _ => false,
7965    }
7966}
7967
7968fn element_has_default(element: &PatternElement) -> bool {
7969    match element {
7970        PatternElement::Pattern(pattern) => pattern_has_default(pattern),
7971        PatternElement::Property { value, .. } => pattern_has_default(value),
7972    }
7973}
7974
7975fn rest_has_default(rest: &RestElement) -> bool {
7976    match rest {
7977        RestElement::Pattern(pattern) => pattern_has_default(pattern),
7978        RestElement::Member(_) => false,
7979    }
7980}
7981
7982/// Whether a function-scope binding is visible to the parameter list.
7983///
7984/// The parameter list runs before the body, so the body's `var`s and function
7985/// declarations do not exist yet — a name that only the body declares has to resolve
7986/// outward instead. What *does* exist by then is the compiler's own prologue: the
7987/// self-name of a named function expression (bound by `special_object 2` before anything
7988/// else), `this` and `new.target`. Those stay visible, which is what makes
7989/// `function f(a = this)` and `var f = function f(a = f)` work.
7990///
7991/// `arguments` is handled separately, as a binding of the parameter scope itself: with
7992/// parameter expressions the reference creates two of them, and the one the parameter
7993/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
7994fn visible_in_params(var: &VarDef) -> bool {
7995    var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
7996}
7997
7998fn resolve_slot(
7999    stack: &mut [FnState],
8000    current: usize,
8001    name: &str,
8002    block: u64,
8003    in_params: bool,
8004) -> Slot {
8005    // The parameter list's own bindings. They are consulted first because they shadow
8006    // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
8007    // `a` in the parameter scope, so a closure made there reads the parameter even after
8008    // the body assigns to its own `a`.
8009    if in_params
8010        && let Some(index) = stack[current]
8011            .vars
8012            .iter()
8013            .enumerate()
8014            .position(|(index, var)| {
8015                var.name == name
8016                    && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
8017            })
8018    {
8019        return Slot::Loc(index as u32);
8020    }
8021    // A name can be bound more than once: two `catch` parameters in nested
8022    // handlers are two slots. The binding that wins is the one whose scope encloses
8023    // the access, and among those the innermost — so the blocks are walked outward
8024    // and the first binding found on the way is the one that counts. A binding in
8025    // no block (`var`) is reachable from anywhere, which is why the function scope
8026    // is the end of the walk.
8027    //
8028    // The block walk comes *before* the argument slots, because a block may shadow a
8029    // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
8030    // slot is only the answer once nothing nearer claims the name.
8031    let chain = block_chain(&stack[current], block);
8032    for scope in &chain {
8033        let found = stack[current]
8034            .vars
8035            .iter()
8036            .enumerate()
8037            .find(|(index, var)| {
8038                var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
8039            })
8040            .map(|(index, _)| index);
8041        if let Some(index) = found {
8042            return Slot::Loc(index as u32);
8043        }
8044    }
8045    // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
8046    // its own slot, and `var` of the same name in the body is the same binding.
8047    if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
8048        return Slot::Arg(index as u32);
8049    }
8050    // Function-scope bindings — `var` and function declarations — are recorded with
8051    // the sentinel block `0`, which no real scope uses, so the walk above cannot see
8052    // them. They are reachable from anywhere in the function, which is exactly what
8053    // the sentinel means.
8054    //
8055    // This pass is *only* for those. A lexical binding has to be found through the
8056    // chain or not at all, and looking a name up without its block is precisely how
8057    // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
8058    // block leaked out of it.
8059    let function_scoped = stack[current]
8060        .vars
8061        .iter()
8062        .enumerate()
8063        .find(|(index, var)| {
8064            var.name == name
8065                && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
8066                && (!in_params || visible_in_params(var))
8067        })
8068        .map(|(index, _)| index);
8069    if let Some(index) = function_scoped {
8070        return Slot::Loc(index as u32);
8071    }
8072    if let Some(index) = stack[current]
8073        .closure_vars
8074        .iter()
8075        .position(|c| c.name == name)
8076    {
8077        return slot_for_closure(&stack[current].closure_vars[index], index as u32);
8078    }
8079
8080    for owner in (0..current).rev() {
8081        // The nested function was created inside one of this frame's blocks, and the
8082        // outermost visible binding is the innermost block on that chain — not whatever
8083        // comes first in the variable table. `function f(){ class S{} }` has two `S`
8084        // bindings: the `let S` inside `f` and the `const S` inside the class body, and
8085        // the class body is the one a method may see.
8086        let entry = stack
8087            .get(owner + 1)
8088            .map(|s| s.created_in_block)
8089            .unwrap_or(0);
8090        let lexical = block_chain(&stack[owner], entry)
8091            .into_iter()
8092            .find_map(|scope| {
8093                stack[owner]
8094                    .vars
8095                    .iter()
8096                    .enumerate()
8097                    .find(|(index, var)| {
8098                        var.name == name
8099                            && stack[owner].var_block.get(*index).copied() == Some(scope)
8100                    })
8101                    .map(|(index, _)| index)
8102            });
8103        // A function born in a parameter list sees that list's bindings, not the body's:
8104        // the parameter scope is the environment it was created in.
8105        let in_param_scope = stack
8106            .get(owner + 1)
8107            .is_some_and(|child| child.created_in_params)
8108            .then(|| {
8109                stack[owner]
8110                    .vars
8111                    .iter()
8112                    .enumerate()
8113                    .position(|(index, var)| {
8114                        var.name == name
8115                            && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
8116                    })
8117            })
8118            .flatten();
8119        let found = if let Some(index) = in_param_scope {
8120            let var = &stack[owner].vars[index];
8121            Some(Found::Local(
8122                ClosureType::Local,
8123                index as u32,
8124                var.is_const,
8125                var.needs_check(),
8126            ))
8127        } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
8128            Some(Found::Local(ClosureType::Arg, index as u32, false, false))
8129        } else if let Some(index) = lexical {
8130            let var = &stack[owner].vars[index];
8131            Some(Found::Local(
8132                ClosureType::Local,
8133                index as u32,
8134                var.is_const,
8135                var.needs_check(),
8136            ))
8137        } else if let Some(index) = stack[owner]
8138            .vars
8139            .iter()
8140            .enumerate()
8141            .find_map(|(index, var)| {
8142                // A function created inside a parameter list must not see the body of the
8143                // function it was born in; see [`FnState::created_in_params`].
8144                let hidden = stack
8145                    .get(owner + 1)
8146                    .is_some_and(|child| child.created_in_params);
8147                (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
8148            })
8149        {
8150            let var = &stack[owner].vars[index];
8151            Some(Found::Local(
8152                ClosureType::Local,
8153                index as u32,
8154                var.is_const,
8155                var.needs_check(),
8156            ))
8157        } else if stack[owner].self_name.as_deref() == Some(name) {
8158            // A named function expression's own name. The reference declares it here,
8159            // on the first lookup that fails, rather than up front — and that is what
8160            // makes it reachable from a *nested* function: the nested lookup is what
8161            // walks out and creates the binding. A direct reference in the body is
8162            // caught the same way, which is why `provide_self_name` only has to add
8163            // the prologue.
8164            let strict = stack[owner].strict;
8165            stack[owner].var_block.push(FUNCTION_SCOPE);
8166            stack[owner].vars.push(VarDef {
8167                kind: VarKind::FunctionName,
8168                // In strict mode the name is immutable, so a store raises; sloppy
8169                // mode drops the store instead (see `variable_instruction`).
8170                is_const: strict,
8171                ..VarDef::var(name)
8172            });
8173            let index = stack[owner].vars.len() as u32 - 1;
8174            Some(Found::Local(ClosureType::Local, index, strict, false))
8175        } else if let Some(index) = stack[owner]
8176            .closure_vars
8177            .iter()
8178            .position(|c| c.name == name)
8179        {
8180            let closure = &stack[owner].closure_vars[index];
8181            Some(match closure.closure_type {
8182                // `GlobalRef` belongs here too: it is a *global* reached through this
8183                // frame's reference table, so treating it as a `Ref` to a local cell makes
8184                // the reader look for a cell no frame ever fills. That is how a second
8185                // function using `eval` in its parameter list read `undefined` after a
8186                // sibling had already made `eval` a closure entry.
8187                ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
8188                    Found::Global(index as u32)
8189                }
8190                // A module variable is a cell in the *module's* environment, which is
8191                // the module body's parent as far as a nested function is concerned — so
8192                // it is captured as a plain reference, not looked up as a global.
8193                ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
8194                    ClosureType::Ref,
8195                    index as u32,
8196                    closure.is_const,
8197                    closure.is_lexical,
8198                ),
8199                _ => Found::Local(
8200                    ClosureType::Ref,
8201                    index as u32,
8202                    closure.is_const,
8203                    closure.is_lexical,
8204                ),
8205            })
8206        } else {
8207            None
8208        };
8209        let Some(found) = found else { continue };
8210
8211        let (is_const, is_lexical) = match found {
8212            Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
8213            Found::Global(_) => (false, false),
8214        };
8215        // Mark the owner's binding as captured so it moves into a reference cell.
8216        if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
8217            let slot = match found {
8218                Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
8219                _ => &mut stack[owner].vars[index as usize],
8220            };
8221            slot.is_captured = true;
8222        }
8223        // Forward the reference through every function in between.
8224        let mut previous = match found {
8225            Found::Local(kind, index, _, _) => (kind, index),
8226            Found::Global(index) => (ClosureType::Global, index),
8227        };
8228        for level in owner + 1..=current {
8229            let kind = match (previous.0, level) {
8230                // A global stays a global at *every* level. Without `GlobalRef` in
8231                // this arm the second nested function over the same global got a
8232                // `Ref` to a cell no frame ever held, so the innermost closure read
8233                // `undefined` — which is how a two-deep getter lost its outer
8234                // variable.
8235                (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
8236                    ClosureType::GlobalRef
8237                }
8238                (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
8239                _ => ClosureType::Ref,
8240            };
8241            let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
8242            previous = (kind, index);
8243        }
8244        let index = previous.1;
8245        return slot_for_closure(&stack[current].closure_vars[index as usize], index);
8246    }
8247
8248    // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
8249    // creating a property. The top-level function holds the entry.
8250    let mut previous = (
8251        ClosureType::Global,
8252        ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
8253    );
8254    for level in 1..=current {
8255        let index = ensure_closure(
8256            stack,
8257            level,
8258            name,
8259            false,
8260            false,
8261            ClosureType::GlobalRef,
8262            previous.1,
8263        );
8264        previous = (ClosureType::GlobalRef, index);
8265    }
8266    Slot::Global(previous.1)
8267}
8268
8269/// What an outward search turned up.
8270#[derive(Debug, Clone, Copy)]
8271enum Found {
8272    /// A binding in an enclosing function, reachable through a closure of this
8273    /// type, with its const/lexical flags.
8274    Local(ClosureType, u32, bool, bool),
8275    /// A global, reached through the enclosing function's closure entry.
8276    Global(u32),
8277}
8278
8279/// Add a closure entry to `level` if it is not there yet.
8280fn ensure_closure(
8281    stack: &mut [FnState],
8282    level: usize,
8283    name: &str,
8284    is_const: bool,
8285    is_lexical: bool,
8286    closure_type: ClosureType,
8287    var_idx: u32,
8288) -> u32 {
8289    if let Some(index) = stack[level]
8290        .closure_vars
8291        .iter()
8292        .position(|c| c.name == name)
8293    {
8294        return index as u32;
8295    }
8296    stack[level].closure_vars.push(ClosureVar {
8297        name: name.to_string(),
8298        is_const,
8299        is_lexical,
8300        closure_type,
8301        var_idx: var_idx as u16,
8302    });
8303    stack[level].closure_vars.len() as u32 - 1
8304}
8305
8306fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
8307    match closure.closure_type {
8308        // A `global_ref` only says *how* the binding is found (through the
8309        // parent's closure table); the access itself is an ordinary global one.
8310        ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
8311        ClosureType::GlobalDecl => Slot::GlobalDecl(index),
8312        // A module variable is a real cell in the module's environment, so it is reached
8313        // exactly like a captured local — the host, not the global object, is what fills
8314        // the slot.
8315        ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
8316        _ => Slot::VarRef(index),
8317    }
8318}
8319
8320/// Pick the opcode for one variable access.
8321///
8322/// The `_check` variants are what enforce the temporal dead zone. They are used
8323/// for every access to a `let`/`const` binding except its own initialisation —
8324/// which is exactly the operation that takes the binding out of the dead zone.
8325fn variable_instruction(
8326    stack: &[FnState],
8327    current: usize,
8328    action: VarAction,
8329    slot: Slot,
8330) -> (Opcode, Vec<Op>) {
8331    let lexical = match slot {
8332        Slot::Loc(index) => stack[current]
8333            .vars
8334            .get(index as usize)
8335            .is_some_and(|v| v.needs_check()),
8336        Slot::VarRef(index) => stack[current]
8337            .closure_vars
8338            .get(index as usize)
8339            .is_some_and(|c| c.is_lexical),
8340        _ => false,
8341    };
8342    let operand = vec![Op::Slot(slot)];
8343    match (action, slot) {
8344        (VarAction::Get, Slot::Loc(index)) => (
8345            if lexical {
8346                Opcode::GetLocCheck
8347            } else {
8348                Opcode::GetLoc
8349            },
8350            vec![Op::Slot(Slot::Loc(index))],
8351        ),
8352        (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
8353        (VarAction::Get, Slot::VarRef(index)) => (
8354            if lexical {
8355                Opcode::GetVarRefCheck
8356            } else {
8357                Opcode::GetVarRef
8358            },
8359            vec![Op::Slot(Slot::VarRef(index))],
8360        ),
8361        (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
8362        (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
8363        (VarAction::GetUndef, Slot::Loc(_)) => (Opcode::GetLoc, operand),
8364        (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
8365        (VarAction::GetUndef, Slot::VarRef(_)) => (Opcode::GetVarRef, operand),
8366        (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8367            (Opcode::GetVarUndef, operand)
8368        }
8369
8370        (VarAction::Put, Slot::Loc(_)) => (
8371            if lexical {
8372                Opcode::PutLocCheck
8373            } else {
8374                Opcode::PutLoc
8375            },
8376            operand,
8377        ),
8378        (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
8379        (VarAction::Put, Slot::VarRef(_)) => (
8380            if lexical {
8381                Opcode::PutVarRefCheck
8382            } else {
8383                Opcode::PutVarRef
8384            },
8385            operand,
8386        ),
8387        (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
8388        (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8389        // Initialisation is what ends the dead zone, so it never checks.
8390        (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8391        (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
8392        // `this` in a derived constructor is always a local, so these cannot happen;
8393        // routing them to the ordinary forms keeps the match total without inventing
8394        // opcodes the reference does not have.
8395        (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
8396        (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8397        (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8398            (Opcode::PutVarInit, operand)
8399        }
8400        (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
8401        (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8402        (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8403            (Opcode::PutVarInit, operand)
8404        }
8405        (VarAction::Set, Slot::Loc(_)) => (
8406            if lexical {
8407                Opcode::SetLocCheck
8408            } else {
8409                Opcode::SetLoc
8410            },
8411            operand,
8412        ),
8413        (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
8414        (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
8415        (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8416        (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8417        (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
8418        (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8419        (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
8420        (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
8421        (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8422        (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
8423        (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8424        (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
8425    }
8426}
8427
8428/// The instruction-rewriting pass.
8429///
8430/// These are the reference implementation's patterns, restricted to the ones the
8431/// constructs this compiler supports can produce. Each entry is a comment on the
8432/// bytecode it removes, because the whole point is that the result is one
8433/// instruction shorter than the literal translation of the AST.
8434fn peephole(
8435    insns: &mut [Option<(Opcode, Vec<Op>)>],
8436    label_at: &[Option<u32>],
8437    placed: &[Option<usize>],
8438) {
8439    fold_dup_patterns(insns, label_at);
8440
8441    // `drop` before `return_undef` is dead: the return discards the whole frame
8442    // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
8443    // consumes its own `drop`; removing the drop first would leave the `dup` and
8444    // produce a `set_` where the reference has a `put_`.
8445    for index in 0..insns.len() {
8446        if opcode_at(insns, index) != Some(Opcode::Drop) {
8447            continue;
8448        }
8449        // Skip over a run of drops, but stop at a jump target: removing code on
8450        // one side of a label would silently retarget the jump.
8451        let mut next = index + 1;
8452        while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
8453            next += 1;
8454        }
8455        if is_label_at(label_at, next) {
8456            continue;
8457        }
8458        if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
8459            for entry in &mut insns[index..next] {
8460                *entry = None;
8461            }
8462        }
8463    }
8464
8465    // The rewrites below all decide against one fixed snapshot, which is what the
8466    // reference sees: `code_match` reads the bytecode buffer as it was on entry to
8467    // the pass, so a rule never observes what an earlier rule removed. Gathering
8468    // every deletion first and applying them together reproduces that.
8469    let snapshot: Vec<Option<Opcode>> = insns
8470        .iter()
8471        .map(|entry| entry.as_ref().map(|(op, _)| *op))
8472        .collect();
8473    // The next instruction that is still there. Holes left by dead-code
8474    // elimination are not instructions, so a rule looks past them.
8475    let next_op = |index: usize| -> Option<usize> {
8476        (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
8477    };
8478
8479    let mut doomed = vec![false; insns.len()];
8480    for index in 0..insns.len() {
8481        // A constant pushed only to be dropped does nothing at all. This is what a
8482        // comma expression with a literal left operand compiles to — `(0, f)()` — and
8483        // the reference removes the pair rather than making the reader step over it.
8484        let constant = matches!(
8485            snapshot[index],
8486            Some(
8487                Opcode::Undefined
8488                    | Opcode::Null
8489                    | Opcode::PushMinus1
8490                    | Opcode::Push0
8491                    | Opcode::Push1
8492                    | Opcode::Push2
8493                    | Opcode::Push3
8494                    | Opcode::Push4
8495                    | Opcode::Push5
8496                    | Opcode::Push6
8497                    | Opcode::Push7
8498                    | Opcode::PushTrue
8499                    | Opcode::PushFalse
8500                    | Opcode::PushI32
8501            )
8502        );
8503        if constant
8504            && let Some(next) = next_op(index)
8505            && snapshot[next] == Some(Opcode::Drop)
8506        {
8507            doomed[index] = true;
8508            doomed[next] = true;
8509        }
8510    }
8511    for (index, entry) in insns.iter_mut().enumerate() {
8512        if doomed[index] {
8513            *entry = None;
8514        }
8515    }
8516
8517    // A conditional whose destination is the very next instruction just pops its
8518    // condition, so it becomes a plain `drop`. This is what an empty `case` clause
8519    // compiles to.
8520    //
8521    // Order matters, and it is the reference's order: this runs *before* the
8522    // folding below, on the instruction the conditional originally had. Folding
8523    // moves a conditional's destination, and the reference never re-examines it
8524    // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
8525    // a conditional even though folding leaves it pointing at the next
8526    // instruction.
8527    for (index, entry) in insns.iter_mut().enumerate() {
8528        let Some((op, operands)) = entry.clone() else {
8529            continue;
8530        };
8531        if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
8532            continue;
8533        }
8534        let Some(id) = label_id(&operands) else {
8535            continue;
8536        };
8537        if placed.get(id as usize).copied().flatten() == Some(index + 1) {
8538            *entry = Some((Opcode::Drop, Vec::new()));
8539        }
8540    }
8541
8542    // A constant condition is decided here rather than at run time.
8543    fold_constant_conditions(insns);
8544    // The conditional folding below is about pairs of *real* branches, so it runs
8545    // before a jump to the next instruction is dropped: `do { … if (c) continue }
8546    // while (t)` puts `continue` exactly on the condition, and the reference inverts
8547    // the branch first and only then notices the jump goes nowhere.
8548    fold_conditional_jumps(insns, label_at, placed);
8549
8550    // A jump whose destination is the very next instruction does nothing, which is
8551    // what constant folding leaves behind for `while (1) { … }`.
8552    remove_jump_to_next(insns, placed);
8553
8554    // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
8555    // a use of the same variable boils down to.
8556    for index in 0..insns.len() {
8557        let Some((put_op, _)) = insns[index].clone() else {
8558            continue;
8559        };
8560        if !is_foldable_put(put_op) {
8561            continue;
8562        }
8563        if is_label_at(label_at, index + 1) {
8564            continue;
8565        }
8566        let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
8567            continue;
8568        };
8569        if get_op != get_form_of(put_op) {
8570            continue;
8571        }
8572        let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
8573        if put_slot.is_none() || put_slot != get_operands.first().cloned() {
8574            continue;
8575        }
8576        insns[index] = Some((set_form_of(put_op), get_operands));
8577        insns[index + 1] = None;
8578    }
8579}
8580
8581/// Drop `gosub`s that call an empty subroutine.
8582///
8583/// A `gosub` whose target starts with `ret` returns immediately, so the reference
8584/// drops the call. This is how `try`/`catch` without a `finally` loses its
8585/// finalizer plumbing: the finalizer block is empty, its first instruction is
8586/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
8587/// [`eliminate_dead_code`] then removes.
8588fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
8589    let state = &stack[current];
8590    let mut targets = Vec::new();
8591    for insn in &state.insns {
8592        if let Insn::Fixed { op, operands } = insn
8593            && *op == Opcode::Gosub
8594            && let Some(id) = label_id(operands)
8595            && let Some(target) = state.labels.get(id as usize).copied().flatten()
8596        {
8597            targets.push(target);
8598        }
8599    }
8600    let empty: Vec<usize> = targets
8601        .into_iter()
8602        .filter(|target| {
8603            stack[current]
8604                .insns
8605                .get(*target)
8606                .map(|insn| {
8607                    matches!(
8608                        insn,
8609                        Insn::Fixed {
8610                            op: Opcode::Ret,
8611                            ..
8612                        }
8613                    )
8614                })
8615                .unwrap_or(false)
8616        })
8617        .collect();
8618    if empty.is_empty() {
8619        return;
8620    }
8621    for insn in stack[current].insns.iter_mut() {
8622        if let Insn::Fixed { op, operands } = insn
8623            && *op == Opcode::Gosub
8624            && let Some(id) = label_id(operands)
8625            && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
8626            && empty.contains(&target)
8627        {
8628            *insn = Insn::Dead;
8629        }
8630    }
8631}
8632
8633/// Replace unreachable instructions with [`Insn::Dead`].
8634fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
8635    let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
8636    for (index, insn) in stack[current].insns.iter_mut().enumerate() {
8637        if !reachable[index] {
8638            *insn = Insn::Dead;
8639        }
8640    }
8641}
8642
8643/// Mark every instruction index reachable from the entry, plus the index one past
8644/// the last instruction.
8645///
8646/// `seen[len]` answers "can control reach the end of this function", and the
8647/// entries before it identify dead code. Both DCE and the implicit-return decision
8648/// read the same result, which keeps them from disagreeing.
8649fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
8650    let mut seen = vec![false; count + 1];
8651    let mut worklist = vec![0usize];
8652    while let Some(index) = worklist.pop() {
8653        if index > count || seen[index] {
8654            continue;
8655        }
8656        seen[index] = true;
8657        if index == count {
8658            continue;
8659        }
8660        let (op, operands) = match &state.insns[index] {
8661            Insn::Fixed { op, operands } => (*op, operands.as_slice()),
8662            // A variable access never transfers control, and a removed
8663            // instruction is only reachable if it is already marked.
8664            Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
8665                worklist.push(index + 1);
8666                continue;
8667            }
8668        };
8669        match op {
8670            // A return, a throw and a `ret` all leave this instruction stream: the
8671            // first two give control to the caller or the handler, and `ret`
8672            // returns to a `gosub` elsewhere.
8673            // A tail call leaves the function too: the callee's result becomes this
8674            // function's result, so nothing after it runs.
8675            Opcode::Return
8676            | Opcode::ReturnUndef
8677            | Opcode::ReturnAsync
8678            | Opcode::TailCall
8679            | Opcode::TailCallMethod
8680            | Opcode::Throw
8681            | Opcode::ThrowError
8682            | Opcode::Ret => {}
8683            // A `catch` records where exceptions from the code that follows go.
8684            // That code is not reachable through normal control flow, but it is
8685            // reachable — through the exception edge — so the walk has to follow
8686            // it, or dead-code elimination would delete every handler.
8687            Opcode::Catch => {
8688                if let Some(target) = placed_label(state, operands) {
8689                    worklist.push(target);
8690                }
8691                worklist.push(index + 1);
8692            }
8693            // A `gosub` calls a subroutine and then continues, so both edges count.
8694            Opcode::Gosub => {
8695                if let Some(target) = placed_label(state, operands) {
8696                    worklist.push(target);
8697                }
8698                worklist.push(index + 1);
8699            }
8700            Opcode::Goto => {
8701                if let Some(target) = placed_label(state, operands) {
8702                    worklist.push(target);
8703                }
8704            }
8705            Opcode::IfTrue | Opcode::IfFalse => {
8706                if let Some(target) = placed_label(state, operands) {
8707                    worklist.push(target);
8708                }
8709                worklist.push(index + 1);
8710            }
8711            _ => worklist.push(index + 1),
8712        }
8713    }
8714    seen
8715}
8716
8717/// The instruction index a jump operand points at, resolved through the label
8718/// placement table.
8719fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
8720    let id = label_id(operands)?;
8721    state.labels.get(id as usize).copied().flatten()
8722}
8723
8724/// The label an instruction refers to.
8725fn label_id(operands: &[Op]) -> Option<u32> {
8726    operands.iter().find_map(|operand| match operand {
8727        Op::Label(label) => Some(label.0),
8728        _ => None,
8729    })
8730}
8731
8732/// Turn `if_false L; goto M; L:` into `if_true M`.
8733///
8734/// A conditional whose alternate branch is an unconditional jump needs one jump,
8735/// not two. This is the shape `if (c) break;` produces, so folding it removes an
8736/// instruction and a label from every conditional `break`.
8737/// The boolean a constant-push instruction produces, or `None` if it is not one.
8738///
8739/// Only the operators whose truthiness is decided by the opcode are covered; a
8740/// constant that needs the constant pool (a string) is left alone, because reading it
8741/// would mean threading the pool through the peephole for a case the reference also
8742/// skips.
8743fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
8744    match op {
8745        // `push_0` returns -1 for zero, `push_1` 1, and so on.
8746        Opcode::PushMinus1 => Some(true),
8747        Opcode::Push0 => Some(false),
8748        Opcode::Push1
8749        | Opcode::Push2
8750        | Opcode::Push3
8751        | Opcode::Push4
8752        | Opcode::Push5
8753        | Opcode::Push6
8754        | Opcode::Push7 => Some(true),
8755        Opcode::PushTrue => Some(true),
8756        Opcode::PushFalse => Some(false),
8757        Opcode::Undefined | Opcode::Null => Some(false),
8758        Opcode::PushI32 => match operands.first() {
8759            Some(Op::Int(value)) => Some(*value != 0),
8760            _ => None,
8761        },
8762        _ => None,
8763    }
8764}
8765
8766/// Fold a branch on a constant condition.
8767///
8768/// `if (0) a() else b()` must not test anything at run time, and the reference
8769/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
8770/// which is why the bytecode for a `while (1)` loop has no condition at all.
8771///
8772/// Two instructions become one, so the slot the test occupied is left empty rather
8773/// than shifting everything after it: labels have already been resolved to indices.
8774fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>]) {
8775    for index in 0..insns.len() {
8776        let Some((push_op, push_operands)) = insns[index].clone() else {
8777            continue;
8778        };
8779        let Some(truth) = constant_truth(push_op, &push_operands) else {
8780            continue;
8781        };
8782        let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
8783            continue;
8784        };
8785        let (destination, taken) = match branch_op {
8786            Opcode::IfTrue => (branch_operands.first().cloned(), truth),
8787            Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
8788            _ => continue,
8789        };
8790        let Some(destination) = destination else {
8791            continue;
8792        };
8793        insns[index] = if taken {
8794            // The branch is always taken, so it becomes an unconditional jump.
8795            Some((Opcode::Goto, vec![destination]))
8796        } else {
8797            // The branch never runs: both instructions disappear and control falls
8798            // through to what came after.
8799            None
8800        };
8801        insns[index + 1] = None;
8802    }
8803}
8804
8805/// Remove a jump whose destination is the instruction right after it.
8806///
8807/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
8808/// its test into nothing, and the loop-end jump then points at the following
8809/// instruction. The reference drops them, so `stack_size` and the listing agree.
8810fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
8811    for index in 0..insns.len() {
8812        let Some((op, operands)) = insns[index].clone() else {
8813            continue;
8814        };
8815        if !is_goto(op) {
8816            continue;
8817        }
8818        let Some(id) = label_id(&operands) else {
8819            continue;
8820        };
8821        // The next instruction that still exists, which is what "the instruction
8822        // after this jump" means once earlier folds have punched holes.
8823        let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
8824        if placed.get(id as usize).copied().flatten() == next {
8825            insns[index] = None;
8826        }
8827    }
8828}
8829
8830fn fold_conditional_jumps(
8831    insns: &mut [Option<(Opcode, Vec<Op>)>],
8832    label_at: &[Option<u32>],
8833    placed: &[Option<usize>],
8834) {
8835    for index in 0..insns.len() {
8836        let Some((op, operands)) = insns[index].clone() else {
8837            continue;
8838        };
8839        let inverted = match op {
8840            Opcode::IfFalse => Opcode::IfTrue,
8841            Opcode::IfTrue => Opcode::IfFalse,
8842            _ => continue,
8843        };
8844        // Next must be an unconditional jump that is not itself a target, and the
8845        // instruction after it must be exactly where the conditional goes.
8846        let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
8847            continue;
8848        };
8849        if !is_goto(next_op) || is_label_at(label_at, index + 1) {
8850            continue;
8851        }
8852        // The conditional must land on the instruction *after* the jump. Several
8853        // labels can share a position, so this asks where *this* label was put
8854        // rather than what label happens to sit there.
8855        let Some(taken) = label_id(&operands) else {
8856            continue;
8857        };
8858        if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
8859            continue;
8860        }
8861        let Some(destination) = next_operands.first().cloned() else {
8862            continue;
8863        };
8864        insns[index] = Some((inverted, vec![destination]));
8865        insns[index + 1] = None;
8866    }
8867}
8868
8869/// Whether a jump target is placed at this instruction index.
8870fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
8871    label_at.get(index).copied().flatten().is_some()
8872}
8873
8874fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
8875    // `dup put_x(n)` -> `set_x(n)`
8876    // `dup put_x(n) drop` -> `put_x(n)`
8877    // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
8878    for index in 0..insns.len() {
8879        if opcode_at(insns, index) != Some(Opcode::Dup) {
8880            continue;
8881        }
8882        if is_label_at(label_at, index + 1) {
8883            continue;
8884        }
8885        let Some((put_op, put_operands)) = insns[index + 1].clone() else {
8886            continue;
8887        };
8888        if !is_foldable_put(put_op) {
8889            continue;
8890        }
8891        let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
8892            continue;
8893        };
8894        let mut new_op = set_form_of(put_op);
8895        let mut end = index + 2;
8896        if is_label_at(label_at, end) {
8897            // The `put` has to stay as it is; only the `dup` can be folded.
8898            insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
8899            insns[index + 1] = None;
8900            continue;
8901        }
8902        // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
8903        // Deleting it moves the label's target onto whatever follows, and the code that
8904        // jumps there arrives with a different stack than the fall-through path: that is
8905        // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
8906        // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
8907        // an empty stack. The store had already consumed the value it was supposed to
8908        // leave behind.
8909        if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
8910            new_op = put_op;
8911            end += 1;
8912            if opcode_at(insns, end) == Some(get_form_of(put_op))
8913                && !is_label_at(label_at, end)
8914                && insns[end]
8915                    .as_ref()
8916                    .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
8917            {
8918                new_op = set_form_of(put_op);
8919                end += 1;
8920            }
8921        }
8922        insns[index] = Some((new_op, vec![Op::Slot(slot)]));
8923        for entry in &mut insns[index + 1..end] {
8924            *entry = None;
8925        }
8926    }
8927}
8928
8929fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
8930    insns
8931        .get(index)
8932        .and_then(|entry| entry.as_ref())
8933        .map(|(op, _)| *op)
8934}
8935
8936/// The four `put_` families that have a `set_` twin. Deliberately not including
8937/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
8938/// these, and folding the others would produce instructions that do not exist.
8939fn is_foldable_put(op: Opcode) -> bool {
8940    matches!(
8941        op,
8942        Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
8943    )
8944}
8945
8946fn set_form_of(op: Opcode) -> Opcode {
8947    match op {
8948        Opcode::PutLoc => Opcode::SetLoc,
8949        Opcode::PutLocCheck => Opcode::SetLocCheck,
8950        Opcode::PutArg => Opcode::SetArg,
8951        Opcode::PutVarRef => Opcode::SetVarRef,
8952        other => other,
8953    }
8954}
8955
8956fn get_form_of(op: Opcode) -> Opcode {
8957    match op {
8958        Opcode::PutLoc => Opcode::GetLoc,
8959        Opcode::PutLocCheck => Opcode::GetLocCheck,
8960        Opcode::PutArg => Opcode::GetArg,
8961        Opcode::PutVarRef => Opcode::GetVarRef,
8962        other => other,
8963    }
8964}
8965
8966/// Atom interning, per function.
8967///
8968/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
8969/// identifiers, so the array-index rule applies here rather than at the handful of
8970/// call sites that build property keys.
8971fn intern_atom(state: &mut FnState, name: &str) -> u32 {
8972    intern_atom_value(state, Atom::from_text(name))
8973}
8974
8975/// [`intern_atom`] for an operand that is already an [`Atom`].
8976///
8977/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
8978/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
8979/// would have looked up.
8980fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
8981    if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
8982        return index as u32;
8983    }
8984    state.atoms.push(atom);
8985    state.atoms.len() as u32 - 1
8986}
8987
8988fn binary_opcode(op: BinaryOp) -> Opcode {
8989    match op {
8990        BinaryOp::Add => Opcode::Add,
8991        BinaryOp::Sub => Opcode::Sub,
8992        BinaryOp::Mul => Opcode::Mul,
8993        BinaryOp::Div => Opcode::Div,
8994        BinaryOp::Mod => Opcode::Mod,
8995        BinaryOp::Pow => Opcode::Pow,
8996        BinaryOp::BitOr => Opcode::Or,
8997        BinaryOp::BitXor => Opcode::Xor,
8998        BinaryOp::BitAnd => Opcode::And,
8999        BinaryOp::Shl => Opcode::Shl,
9000        BinaryOp::Shr => Opcode::Sar,
9001        BinaryOp::UShr => Opcode::Shr,
9002        BinaryOp::Lt => Opcode::Lt,
9003        BinaryOp::LtEq => Opcode::Lte,
9004        BinaryOp::Gt => Opcode::Gt,
9005        BinaryOp::GtEq => Opcode::Gte,
9006        BinaryOp::Eq => Opcode::Eq,
9007        BinaryOp::NotEq => Opcode::Neq,
9008        BinaryOp::StrictEq => Opcode::StrictEq,
9009        BinaryOp::StrictNotEq => Opcode::StrictNeq,
9010        BinaryOp::In => Opcode::In,
9011        BinaryOp::Instanceof => Opcode::Instanceof,
9012    }
9013}
9014
9015fn compound_opcode(op: AssignOp) -> Opcode {
9016    match op {
9017        AssignOp::Add => Opcode::Add,
9018        AssignOp::Sub => Opcode::Sub,
9019        AssignOp::Mul => Opcode::Mul,
9020        AssignOp::Div => Opcode::Div,
9021        AssignOp::Mod => Opcode::Mod,
9022        AssignOp::Pow => Opcode::Pow,
9023        AssignOp::Shl => Opcode::Shl,
9024        AssignOp::Shr => Opcode::Sar,
9025        AssignOp::UShr => Opcode::Shr,
9026        AssignOp::BitOr => Opcode::Or,
9027        AssignOp::BitXor => Opcode::Xor,
9028        AssignOp::BitAnd => Opcode::And,
9029        AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
9030    }
9031}
9032
9033/// Encode the resolved instruction stream, choosing short forms where possible.
9034///
9035/// The peephole pass leaves holes in the instruction list so that label indices
9036/// stay valid. A label names an *instruction index*, and an index that was
9037/// deleted has to resolve to the next surviving instruction, which is what
9038/// [`resolve_label`] does before the byte offsets are known.
9039fn assemble(
9040    insns: &mut [Option<(Opcode, Vec<Op>)>],
9041    insn_pos: &[Option<Position>],
9042    state: &mut FnState,
9043) -> (Vec<u8>, u32, Vec<LineCol>) {
9044    // Compaction: surviving instructions in order, plus the index mapping.
9045    //
9046    // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
9047    // point below where instructions are removed — otherwise a stack trace would point
9048    // at the wrong source line as soon as dead-code elimination kicked in.
9049    let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
9050    let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
9051    let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
9052    for (original, entry) in insns.iter_mut().enumerate() {
9053        if let Some((op, operands)) = entry.take() {
9054            original_to_kept[original] = Some(kept.len());
9055            kept.push((op, operands));
9056            spans.push(insn_pos.get(original).copied().flatten());
9057        }
9058    }
9059
9060    if std::env::var_os("QJS_DEBUG").is_some() {
9061        eprintln!("--- assemble entry --- {kept:?}");
9062    }
9063    // How many labels are real, as opposed to the per-instruction ones allocated
9064    // just below. Only a real label marks a spot in the source program.
9065    let real_labels = state.labels.len();
9066
9067    // Give every surviving instruction a label of its own. Jump cleanup below
9068    // redirects jumps to arbitrary instructions, and a jump target has to be a
9069    // label; pre-allocating one per index means a redirect never has to invent
9070    // anything.
9071    let existing = state.labels.len();
9072    let base = kept.len();
9073    let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
9074    for offset in 0..=kept.len() {
9075        state.labels.push(Some(0));
9076        index_label.push(Label((existing + offset) as u32));
9077    }
9078    // Point each pre-allocated label at its instruction, reusing the count from
9079    // `original_to_kept` so the mapping survives compaction.
9080    let place_index_labels = |state: &mut FnState,
9081                              original_to_kept: &[Option<usize>],
9082                              kept_len: usize,
9083                              index_label: &[Label]| {
9084        for (original, mapped) in original_to_kept.iter().enumerate() {
9085            if let Some(kept_index) = mapped {
9086                let label = index_label[*kept_index].0 as usize;
9087                state.labels[label] = Some(original);
9088            }
9089        }
9090        state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
9091    };
9092    place_index_labels(state, &original_to_kept, base, &index_label);
9093
9094    // Resolve every label to a kept index once; the placement table maps labels
9095    // to original indices, so a second hop lands in kept space.
9096    let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
9097    for (id, placed) in state.labels.iter().enumerate() {
9098        let Some(original) = placed else { continue };
9099        label_kept[id] = if *original == usize::MAX {
9100            Some(base)
9101        } else {
9102            (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
9103        };
9104    }
9105
9106    // Code after an unconditional transfer is unreachable, and the reference drops it
9107    // as it walks past the transfer — the `skip_dead_code` in its first pass. It
9108    // scans forward until it finds a label something still jumps to, so a run of
9109    // dead instructions between a `throw` and the next live target disappears.
9110    //
9111    // The scan repeats because dropping a jump lowers the reference count of the
9112    // label it pointed at, which can strand what follows. Only a real label keeps an
9113    // instruction alive here; the per-instruction labels allocated above belong to
9114    // this pass, not to the program.
9115    loop {
9116        let mut references = vec![false; kept.len() + 1];
9117        for (_, operands) in &kept {
9118            if let Some(target) = target_kept_index(operands, &label_kept)
9119                && target < references.len()
9120            {
9121                references[target] = true;
9122            }
9123        }
9124        let mut doomed = vec![false; kept.len()];
9125        let mut any = false;
9126        for (index, (op, _)) in kept.iter().enumerate() {
9127            if !is_transfer(*op) {
9128                continue;
9129            }
9130            for next in index + 1..kept.len() {
9131                if references[next] {
9132                    break;
9133                }
9134                doomed[next] = true;
9135                any = true;
9136            }
9137        }
9138        if !any {
9139            break;
9140        }
9141        (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
9142    }
9143
9144    // A label that lands on an unconditional jump stands for wherever that jump
9145    // goes, so retarget it once and every jump to the label follows for free.
9146    // This is what makes `continue` in a `for` head reach the loop top instead of
9147    // stopping at the update's trailing jump.
9148    let folded: Vec<Option<usize>> = label_kept
9149        .iter()
9150        .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
9151        .collect();
9152    label_kept = folded;
9153
9154    // Jump cleanup, in compacted index space. Two rewrites the reference also
9155    // applies while it resolves labels:
9156    //   * a jump whose destination is the very next instruction does nothing;
9157    //   * a jump to a jump is redirected to its final destination.
9158    // The second can expose the first, so this repeats until it settles.
9159    loop {
9160        let mut delete = vec![false; kept.len()];
9161        let mut changed = false;
9162        for index in 0..kept.len() {
9163            let (op, operands) = &kept[index];
9164            if !is_goto(*op) {
9165                continue;
9166            }
9167            let Some(immediate) = target_kept_index(operands, &label_kept) else {
9168                continue;
9169            };
9170            let target = follow_jump_chain(&kept, &label_kept, immediate);
9171            if target == index + 1 {
9172                delete[index] = true;
9173                changed = true;
9174            } else if matches!(
9175                kept.get(target).map(|(op, _)| *op),
9176                Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
9177            ) {
9178                // Jumping straight to a return or throw is the same as doing it
9179                // here, so the jump becomes that instruction.
9180                kept[index] = (kept[target].0, Vec::new());
9181                changed = true;
9182            } else if target != immediate {
9183                // Redirect to the end of the chain.
9184                let label = index_label[target];
9185                kept[index].1 = vec![Op::Label(label)];
9186                changed = true;
9187            }
9188        }
9189        if !changed {
9190            break;
9191        }
9192        if !delete.iter().any(|deleted| *deleted) {
9193            break;
9194        }
9195        // Drop the deleted instructions and renumber everything.
9196        let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9197        let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9198        let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9199        for (old, entry) in kept.into_iter().enumerate() {
9200            if delete[old] {
9201                continue;
9202            }
9203            moved[old] = Some(next.len());
9204            next.push(entry);
9205            next_spans.push(spans[old]);
9206        }
9207        for (id, slot) in label_kept.iter_mut().enumerate() {
9208            let Some(old) = *slot else { continue };
9209            *slot = match moved.get(old).copied().flatten() {
9210                Some(new) => Some(new),
9211                // The target was deleted: the jump now lands on whatever follows.
9212                None => (old..moved.len())
9213                    .find_map(|i| moved[i])
9214                    .or(Some(next.len())),
9215            };
9216            let _ = id;
9217        }
9218        kept = next;
9219        spans = next_spans;
9220    }
9221
9222    // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
9223    // jump to the next instruction and is deleted, leaving the label at the end with
9224    // nothing pointing at it. If that also strands the last instruction, it goes
9225    // too — which is how a `try` whose body always returns ends on its `ret` rather
9226    // than an implicit `return_undef`.
9227    // Which instructions something still jumps to. Reading the surviving jumps is
9228    // what the reference's reference counts amount to: once a jump has been folded
9229    // away the label it named is unreferenced, even though the program still has a
9230    // label there.
9231    let mut references = vec![false; kept.len() + 1];
9232    let _ = real_labels;
9233    for (_, operands) in &kept {
9234        if let Some(target) = target_kept_index(operands, &label_kept)
9235            && target < references.len()
9236        {
9237            references[target] = true;
9238        }
9239    }
9240    let mut end = kept.len();
9241    while end > 0 {
9242        let last = end - 1;
9243        let reachable = references[last] || end < kept.len();
9244        if reachable {
9245            break;
9246        }
9247        let after_transfer = last
9248            .checked_sub(1)
9249            .map(|previous| {
9250                matches!(
9251                    kept[previous].0,
9252                    Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
9253                )
9254            })
9255            .unwrap_or(false);
9256        if !after_transfer {
9257            break;
9258        }
9259        end = last;
9260    }
9261    kept.truncate(end);
9262    spans.truncate(end);
9263
9264    // Choose an opcode for each instruction and its size, so label offsets can be
9265    // computed.
9266    let chosen = choose_opcodes(&kept, &label_kept);
9267    let offsets = instruction_offsets(&chosen);
9268    let offset = *offsets.last().unwrap_or(&0);
9269
9270    let mut code = Vec::with_capacity(offset);
9271    for (position, (_, operands)) in kept.iter().enumerate() {
9272        let op = chosen[position];
9273        code.push(op as u8);
9274        let operands = retarget_labels(operands, &label_kept, kept.len());
9275        encode_operands(&mut code, op, &operands, offsets[position], &offsets);
9276    }
9277    let stack_size = compute_stack_size(&code);
9278    // Keep only the offsets where the position actually changes: a run of
9279    // instructions on one line is one table entry, and the runtime binary searches
9280    // the table for the frame's pc.
9281    //
9282    // The table always starts at pc 0 with the *function's own* position, because the
9283    // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
9284    // last_line_num)` from `fd->source_pos`, the token the function definition starts at
9285    // (`function`, `async`, a method's property name). An instruction before the first
9286    // recorded operator therefore reports the function's own start, which is what makes a
9287    // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
9288    let mut positions: Vec<LineCol> = vec![LineCol {
9289        pc: 0,
9290        line: state.line,
9291        column: state.column,
9292    }];
9293    let mut last: Option<Position> = None;
9294    for (index, span) in spans.iter().enumerate() {
9295        let Some(pos) = *span else { continue };
9296        if last == Some(pos) {
9297            continue;
9298        }
9299        last = Some(pos);
9300        if pos.line == state.line && pos.column == state.column {
9301            // Already the seed entry above.
9302            continue;
9303        }
9304        positions.push(LineCol {
9305            pc: offsets[index] as u32,
9306            line: pos.line,
9307            column: pos.column,
9308        });
9309    }
9310    (code, stack_size, positions)
9311}
9312
9313/// Whether an instruction always transfers control away, so anything after it in the
9314/// same stream is unreachable.
9315fn is_transfer(op: Opcode) -> bool {
9316    matches!(
9317        op,
9318        Opcode::Goto
9319            | Opcode::Goto8
9320            | Opcode::Goto16
9321            | Opcode::Return
9322            | Opcode::ReturnUndef
9323            | Opcode::Throw
9324            | Opcode::ThrowError
9325            | Opcode::Ret
9326    )
9327}
9328
9329/// Remove the marked instructions and renumber the label table so it keeps pointing
9330/// at the same instructions. A label whose instruction went away moves to whatever
9331/// follows it, since a jump is never left with nowhere to land.
9332fn drop_instructions(
9333    kept: Vec<(Opcode, Vec<Op>)>,
9334    spans: Vec<Option<Position>>,
9335    label_kept: &mut [Option<usize>],
9336    doomed: &[bool],
9337) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
9338    let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9339    let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9340    let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9341    for (old, entry) in kept.into_iter().enumerate() {
9342        if doomed.get(old).copied().unwrap_or(false) {
9343            continue;
9344        }
9345        moved[old] = Some(result.len());
9346        result.push(entry);
9347        result_spans.push(spans[old]);
9348    }
9349    for slot in label_kept.iter_mut() {
9350        let Some(old) = *slot else { continue };
9351        *slot = match moved.get(old).copied().flatten() {
9352            Some(new) => Some(new),
9353            None => (old..moved.len())
9354                .find_map(|i| moved[i])
9355                .or(Some(result.len())),
9356        };
9357    }
9358    (result, result_spans)
9359}
9360
9361fn is_goto(op: Opcode) -> bool {
9362    matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
9363}
9364
9365/// The kept index a jump operand points at.
9366fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
9367    let id = label_id(operands)?;
9368    label_kept.get(id as usize).copied().flatten()
9369}
9370
9371/// Follow a chain of unconditional jumps to its first real destination.
9372fn follow_jump_chain(
9373    kept: &[(Opcode, Vec<Op>)],
9374    label_kept: &[Option<usize>],
9375    start: usize,
9376) -> usize {
9377    let mut current = start;
9378    // `for(;;)` jumps to itself, so the walk has to be bounded.
9379    for _ in 0..kept.len() {
9380        let Some((op, operands)) = kept.get(current) else {
9381            return current;
9382        };
9383        if !is_goto(*op) {
9384            return current;
9385        }
9386        let Some(next) = target_kept_index(operands, label_kept) else {
9387            return current;
9388        };
9389        if next == current {
9390            return current;
9391        }
9392        current = next;
9393    }
9394    current
9395}
9396
9397/// Rewrite label operands from label ids to kept instruction indices.
9398fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
9399    operands
9400        .iter()
9401        .map(|operand| match operand {
9402            Op::Label(label) => {
9403                let target = label_kept
9404                    .get(label.0 as usize)
9405                    .copied()
9406                    .flatten()
9407                    .unwrap_or(kept_len);
9408                Op::Label(Label(target as u32))
9409            }
9410            other => other.clone(),
9411        })
9412        .collect()
9413}
9414
9415/// Encode the resolved instruction stream, choosing short forms where possible.
9416///
9417/// Compute the maximum value-stack depth by exploring the control-flow graph.
9418///
9419/// This is a breadth-first walk from the first instruction, tracking the stack
9420/// depth on entry to each instruction. Every instruction has at most two
9421/// successors (fall through, and a jump target), so a worklist over byte offsets
9422/// is enough. The reference does the same thing in `compute_stack_size`, which is
9423/// why the resulting numbers match exactly.
9424///
9425/// Instructions that pop a variable number of values (`call`, `array_from`, …)
9426/// encode that count in their operand, which is added to the static `n_pop`.
9427fn compute_stack_size(code: &[u8]) -> u32 {
9428    let mut depth_at = vec![u16::MAX; code.len()];
9429    // Each entry carries the enclosing `catch` levels, innermost last, because
9430    // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
9431    // offset and forgets that level.
9432    let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
9433    let mut max_depth = 0u32;
9434
9435    while let Some((pc, depth, catch_levels)) = worklist.pop() {
9436        if pc >= code.len() {
9437            continue;
9438        }
9439        if depth_at[pc] != u16::MAX {
9440            continue;
9441        }
9442        force_depth(&mut depth_at, pc, depth);
9443
9444        let Some(op) = Opcode::from_u8(code[pc]) else {
9445            break;
9446        };
9447        let info = op.info();
9448        let next = pc + info.size as usize;
9449        if next > code.len() {
9450            break;
9451        }
9452        let mut n_pop = info.n_pop as u32;
9453        let mut n_push = info.n_push as u32;
9454        // Variable-length forms carry their count in the operand.
9455        match info.format {
9456            crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
9457                n_pop += read_u16(code, pc + 1) as u32;
9458            }
9459            crate::opcode::OpFormat::Npopx => {
9460                n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
9461            }
9462            _ => {}
9463        }
9464        // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
9465        // are the `set_` variant; the table already records that, so nothing to
9466        // adjust here.
9467        let _ = &mut n_push;
9468
9469        // The depth before this instruction's own push, which is what a `catch`
9470        // records as its level.
9471        let depth_before = depth;
9472        let mut depth = depth.saturating_sub(n_pop) + n_push;
9473        let mut catch_levels = catch_levels;
9474        if op == Opcode::NipCatch {
9475            // Discard everything above the innermost catch offset, keeping the value
9476            // on top: the frame the code after this sees is the same shape it would
9477            // have had if the `try` were not there.
9478            if let Some(base) = catch_levels.pop() {
9479                depth = base + 1;
9480            }
9481        }
9482        max_depth = max_depth.max(depth);
9483
9484        // Successors.
9485        let target = jump_target_of(code, pc, op);
9486        match op {
9487            Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9488                if let Some(target) = target {
9489                    worklist.push((target, depth, catch_levels));
9490                }
9491            }
9492            Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
9493                if let Some(target) = target {
9494                    worklist.push((target, depth, catch_levels.clone()));
9495                }
9496                worklist.push((next, depth, catch_levels));
9497            }
9498            // A `catch` records an exception edge to the handler. The handler is
9499            // entered with the thrown value on top of the stack, in the slot the
9500            // catch offset occupies on the normal path — which is why the handler's
9501            // first instruction can `put_loc` the exception away, and why the depth
9502            // is the same on both paths.
9503            Opcode::Catch => {
9504                if let Some(target) = target {
9505                    // The handler is protected by the *enclosing* catch, not by this
9506                    // one: an error raised inside it is what the handler's own
9507                    // `catch` catches.
9508                    worklist.push((target, depth, catch_levels.clone()));
9509                }
9510                catch_levels.push(depth_before);
9511                worklist.push((next, depth, catch_levels));
9512            }
9513            // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
9514            // rewind past it too. Its level sits one slot higher than a `catch`'s:
9515            // the iterator and next-method slots occupy the offset's place.
9516            Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
9517                if let Some(target) = target {
9518                    worklist.push((target, depth, catch_levels.clone()));
9519                }
9520                catch_levels.push(depth_before + 1);
9521                worklist.push((next, depth, catch_levels));
9522            }
9523            // `gosub` calls a subroutine with the return address on top. The opcode
9524            // table records no push for it — `ret` is what pops the slot — so the
9525            // extra one is added here, where the depth of the subroutine's first
9526            // instruction is being computed.
9527            Opcode::Gosub => {
9528                if let Some(target) = target {
9529                    worklist.push((target, depth + 1, catch_levels.clone()));
9530                }
9531                worklist.push((next, depth, catch_levels));
9532            }
9533            // `ret` goes back to a `gosub`; nothing here follows it.
9534            Opcode::Ret
9535            | Opcode::Return
9536            | Opcode::ReturnUndef
9537            | Opcode::Throw
9538            | Opcode::ThrowError => {}
9539            _ => worklist.push((next, depth, catch_levels)),
9540        }
9541    }
9542    max_depth
9543}
9544
9545/// Record the stack depth on entry to `pc`, keeping the deeper value if the
9546/// instruction is reachable more than once.
9547fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
9548    let clamped = depth.min(u16::MAX as u32 - 1) as u16;
9549    if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
9550        depth_at[pc] = clamped;
9551    }
9552}
9553
9554fn read_u16(code: &[u8], at: usize) -> u16 {
9555    let mut value = 0u16;
9556    for i in 0..2 {
9557        value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
9558    }
9559    value
9560}
9561
9562/// The absolute target of a jump instruction, if it has one.
9563fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
9564    let info = op.info();
9565    let position = pc + 1;
9566    match info.format {
9567        crate::opcode::OpFormat::Label8 => {
9568            let offset = *code.get(position)? as i8 as i64;
9569            Some((position as i64 + offset) as usize)
9570        }
9571        crate::opcode::OpFormat::Label16 => {
9572            let offset = read_u16(code, position) as i16 as i64;
9573            Some((position as i64 + offset) as usize)
9574        }
9575        crate::opcode::OpFormat::Label => {
9576            let mut offset = 0i32;
9577            for i in 0..4 {
9578                offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
9579            }
9580            Some((position as i64 + offset as i64) as usize)
9581        }
9582        _ => None,
9583    }
9584}
9585
9586fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
9587    use Opcode::*;
9588    match (op, operands.first()) {
9589        (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
9590            op.short_form(*value as u32).unwrap_or(op)
9591        }
9592        (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
9593        (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
9594        (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
9595        | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
9596        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
9597        // A declared global is reached through its reference cell, so it shares
9598        // the `var_ref` encodings, short forms included.
9599        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
9600            op.short_form(*index).unwrap_or(op)
9601        }
9602        (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
9603            op.short_form(*count as u32).unwrap_or(op)
9604        }
9605        _ => op,
9606    }
9607}
9608
9609/// The byte offset each instruction will start at, plus the total code size.
9610fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
9611    let mut offsets = Vec::with_capacity(chosen.len() + 1);
9612    let mut offset = 0usize;
9613    for op in chosen {
9614        offsets.push(offset);
9615        offset += op.size() as usize;
9616    }
9617    offsets.push(offset);
9618    offsets
9619}
9620
9621/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
9622/// the offset actually fits.
9623///
9624/// The choice is circular: an instruction's size decides the offsets of everything after
9625/// it, and the offsets decide whether a jump may be short. So this starts with every jump
9626/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
9627/// Shrinking only ever *shortens* distances, so the loop converges.
9628///
9629/// Doing it in one pass instead — which is what this used to do — silently truncated any
9630/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
9631/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
9632/// with four closures in its body simply stopped, with no error and no output past the
9633/// first iteration.
9634fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
9635    let mut chosen: Vec<Opcode> = kept
9636        .iter()
9637        .map(|(op, operands)| choose_short_form(*op, operands))
9638        .collect();
9639    // A jump the compiler emitted in its widest form, and the forms it may shrink to.
9640    let candidates = |op: Opcode| match op {
9641        Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
9642        Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
9643        Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
9644        _ => None,
9645    };
9646    loop {
9647        let offsets = instruction_offsets(&chosen);
9648        let mut changed = false;
9649        for index in 0..kept.len() {
9650            let (op, operands) = &kept[index];
9651            let Some((short, medium, has_medium)) = candidates(*op) else {
9652                continue;
9653            };
9654            if chosen[index] == short {
9655                continue;
9656            }
9657            let Some(target) = target_kept_index(operands, label_kept) else {
9658                continue;
9659            };
9660            let Some(&target_offset) = offsets.get(target) else {
9661                continue;
9662            };
9663            // A jump is relative to the byte after its opcode, which is the convention
9664            // `jump_target_of` decodes with.
9665            let relative = target_offset as i64 - (offsets[index] as i64 + 1);
9666            if (-128..=127).contains(&relative) {
9667                chosen[index] = short;
9668                changed = true;
9669            } else if has_medium
9670                && chosen[index] == Opcode::Goto
9671                && (-32_768..=32_767).contains(&relative)
9672            {
9673                // Too far for 8 bits and close enough for 16. Only `goto` has a medium
9674                // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
9675                // the reference encodes them.
9676                chosen[index] = medium;
9677                changed = true;
9678            }
9679        }
9680        if !changed {
9681            return chosen;
9682        }
9683    }
9684}
9685
9686fn encode_operands(
9687    code: &mut Vec<u8>,
9688    op: Opcode,
9689    operands: &[Op],
9690    position: usize,
9691    offsets: &[usize],
9692) {
9693    use crate::opcode::OpFormat::*;
9694    let info = op.info();
9695    let write_slot = |code: &mut Vec<u8>, slot: Slot| {
9696        let index = match slot {
9697            Slot::Arg(i)
9698            | Slot::Loc(i)
9699            | Slot::VarRef(i)
9700            | Slot::Global(i)
9701            | Slot::GlobalDecl(i) => i,
9702        };
9703        code.extend_from_slice(&(index as u16).to_be_bytes());
9704    };
9705    match info.format {
9706        None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
9707        U8 | Const8 => {
9708            if let Some(value) = operands.first().and_then(operand_uint) {
9709                code.push(value as u8);
9710            }
9711        }
9712        // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
9713        // like their wide counterparts, only one byte wide.
9714        Loc8 => {
9715            if let Some(Op::Slot(slot)) = operands.first() {
9716                let index = match slot {
9717                    Slot::Arg(i)
9718                    | Slot::Loc(i)
9719                    | Slot::VarRef(i)
9720                    | Slot::Global(i)
9721                    | Slot::GlobalDecl(i) => *i,
9722                };
9723                code.push(index as u8);
9724            }
9725        }
9726        I8 => {
9727            if let Some(value) = operands.first().and_then(operand_int) {
9728                code.push(value as i8 as u8);
9729            }
9730        }
9731        U16 | Npop => {
9732            if let Some(value) = operands.first().and_then(operand_int) {
9733                code.extend_from_slice(&(value as u16).to_be_bytes());
9734            }
9735        }
9736        I16 => {
9737            if let Some(value) = operands.first().and_then(operand_int) {
9738                code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
9739            }
9740        }
9741        I32 => {
9742            if let Some(value) = operands.first().and_then(operand_int) {
9743                code.extend_from_slice(&value.to_be_bytes());
9744            }
9745        }
9746        U32 | Const => {
9747            if let Some(value) = operands.first().and_then(operand_uint) {
9748                code.extend_from_slice(&value.to_be_bytes());
9749            }
9750        }
9751        Loc | Arg | VarRef => {
9752            if let Some(Op::Slot(slot)) = operands.first() {
9753                write_slot(code, *slot);
9754            }
9755        }
9756        Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
9757            if let Some(Op::AtomId(index)) = operands.first() {
9758                code.extend_from_slice(&index.to_be_bytes());
9759            }
9760            // The trailing immediate means different things per format, and the
9761            // atom forms that carry a *label* have to resolve it like any other
9762            // jump, so they cannot share the `U8`/`U16` arms above.
9763            match info.format {
9764                AtomU8 | AtomLabelU8 => {
9765                    if let Some(value) = operands.get(1).and_then(operand_uint) {
9766                        code.push(value as u8);
9767                    }
9768                }
9769                AtomU16 | AtomLabelU16 => {
9770                    if let Some(value) = operands.get(1).and_then(operand_uint) {
9771                        code.extend_from_slice(&(value as u16).to_be_bytes());
9772                    }
9773                }
9774                _ => {}
9775            }
9776        }
9777        NpopU16 => {
9778            for operand in operands.iter().take(2) {
9779                if let Some(value) = operand_uint(operand) {
9780                    code.extend_from_slice(&(value as u16).to_be_bytes());
9781                }
9782            }
9783        }
9784        Label | Label8 | Label16 | LabelU16 => {
9785            if let Some(Op::Label(label)) = operands.first() {
9786                // Labels were already remapped to kept-instruction indices.
9787                let Some(&target) = offsets.get(label.0 as usize) else {
9788                    debug_assert!(false, "label {} is past the end", label.0);
9789                    return;
9790                };
9791                let relative = target as i64 - (position as i64 + 1);
9792                match info.format {
9793                    Label8 => code.push(relative as i8 as u8),
9794                    Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
9795                    // `label_u16` stores the target followed by an unrelated u16.
9796                    LabelU16 => {
9797                        code.extend_from_slice(&(relative as i32).to_be_bytes());
9798                        if let Some(value) = operands.get(1).and_then(operand_uint) {
9799                            code.extend_from_slice(&(value as u16).to_be_bytes());
9800                        }
9801                    }
9802                    _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
9803                }
9804            }
9805        }
9806    }
9807}
9808
9809fn operand_int(op: &Op) -> Option<i32> {
9810    match op {
9811        Op::Int(value) => Some(*value),
9812        _ => None,
9813    }
9814}
9815
9816fn operand_uint(op: &Op) -> Option<u32> {
9817    match op {
9818        Op::Const(value) | Op::AtomId(value) => Some(*value),
9819        Op::Int(value) => Some(*value as u32),
9820        _ => None,
9821    }
9822}
9823
9824/// Disassemble a compiled function.
9825pub fn disassemble(function: &CompiledFunction) -> String {
9826    disasm::disassemble_program(function)
9827}