Skip to main content

js_compile/
compiler.rs

1//! The bytecode compiler.
2//!
3//! Compilation is a single walk over the AST that emits *symbolic* instructions
4//! (jump targets are label ids, variable references are names), followed by a
5//! resolution pass that turns them into final bytecode. Splitting it this way
6//! keeps the emitter readable: nothing has to know slot indices or byte offsets
7//! while it is still discovering them.
8//!
9//! Variable resolution follows the reference implementation's model:
10//!
11//! * every function has a flat table of arguments and locals;
12//! * block scopes form a chain through [`VarDef::scope_next`], which is what makes
13//!   `let`/`const` bindings visible only inside their block and lets the runtime
14//!   put them back into the temporal dead zone on entry;
15//! * a name that is not in the current function is looked up in the enclosing
16//!   ones; if found, the variable is marked captured and reached through a
17//!   closure reference;
18//! * a name found nowhere is a global, reached through a closure entry as well.
19//!
20//! Emission order and instruction choice deliberately mirror `quickjs.c`: the
21//! differential test compares disassembly with the reference opcode by opcode, so
22//! an unnecessary `dup` or a differently chosen short form shows up immediately.
23
24use crate::bytecode::LineCol;
25use crate::bytecode::{
26    ANONYMOUS_BINDING, Atom, ClosureType, ClosureVar, Constant, EvalSite, EvalVisible, ExportEntry,
27    Function as CompiledFunction, FunctionKind, ImportEntry, ModuleMeta, ModuleRequest, VarDef,
28    VarKind,
29};
30use crate::disasm;
31use crate::opcode::Opcode;
32use js_parse::Position;
33use js_parse::Span;
34use js_parse::SyntaxError;
35use js_parse::Wtf8;
36use js_parse::ast::{self, *};
37
38/// A label id, local to the function being compiled.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub struct Label(u32);
41
42/// The name of the hidden local that carries a function's `[[HomeObject]]` for `super`.
43///
44/// The reference calls the variable `home_object` and prints it as `"<home_object>"`, which
45/// is why the brackets are part of the name; nothing a program writes can collide with it.
46const HOME_OBJECT: &str = "<home_object>";
47
48/// The local holding the function `super()` constructs from.
49///
50/// The reference's `JS_ATOM_this_active_func`. Unlike `<home_object>` this one is printed
51/// with its dots, because that is the atom's text: its dump shows `1: var this.active_func`.
52const ACTIVE_FUNC: &str = "this.active_func";
53
54/// The local holding `new.target`, likewise spelled the way the reference's dump shows it.
55const NEW_TARGET: &str = "new.target";
56
57/// Stand-in for a constant-pool index that is only known later in the instruction stream.
58///
59/// One user: the class constructor's `fclosure`, whose slot the reference assigns after the
60/// members have taken theirs. `u32::MAX` is not a reachable pool index — a class with four
61/// billion members is not a thing — and the compiler patches it before resolution runs, so a
62/// missed patch is a panic-free compiler error rather than a wrong jump.
63const CTOR_INDEX_PLACEHOLDER: u32 = u32::MAX;
64
65/// One step of a class's initialisation, in source order.
66///
67/// A static block is not a member the class keeps — it is a run of statements that executes
68/// at the point the class definition reaches it — so it belongs *inside* the initialiser
69/// function rather than alongside the fields as a separate pass. Merging the two is what
70/// makes `static a = 1; static {}` and `static {}; static a = 1` order-sensitive in the
71/// same way the reference is.
72enum StaticInitItem<'a> {
73    /// `static x = value`, or `x = value` for the instance half.
74    Field(FieldKey<'a>, Option<&'a Expr>),
75    /// `static { … }`
76    Block {
77        body: &'a [Stmt],
78        /// Position of the `{`, which is where the reference puts the function.
79        body_start: Position,
80    },
81}
82
83/// How one field names its property.
84///
85/// A computed key is *not* re-evaluated per instance: the reference evaluates it once at
86/// class definition and stores it in a `<computed_field>N` binding, because the key of a field
87/// is fixed when the class is created. Keeping the expression here instead made
88/// `class C { [k] = 1 }` re-read `k` on every `new`, which is a different program when `k`
89/// changes — and worse, the operand order was wrong, so `class C { ["a"] = 1 }` produced
90/// `{1: "a"}`.
91enum FieldKey<'a> {
92    /// `x`, `"x"`, `0` — the property name is static text.
93    Literal(&'a PropKey),
94    /// `#x`: the class-scope binding that holds the private symbol.
95    Private(String),
96    /// `[expr]`: the class-scope binding that holds the evaluated key.
97    Computed(String),
98}
99
100/// The `var_block` sentinel for a binding that lives at function scope.
101///
102/// It has to be a value a *real* block key can never take. Block keys are source
103/// offsets, so `0` is a perfectly ordinary key — the first block statement of a file
104/// gets it — and using `0` as the sentinel made `{ let y = 2 }` at offset zero look
105/// like a function-scoped `var`, which is how a top-level block's `let` leaked out of
106/// its block. The body block already uses `u64::MAX` to stay clear of offsets, so the
107/// sentinel takes the slot below it.
108const FUNCTION_SCOPE: u64 = u64::MAX - 3;
109
110/// The `var_block` sentinel for a binding of the parameter list.
111///
112/// A function whose parameter list contains a default expression gets *two* variable
113/// environments: one for the parameters and one for the body, so a `var` in the body
114/// that shares a name with a parameter is a different binding. The parameter bindings
115/// therefore need a scope key of their own: reachable while the defaults are
116/// evaluated, invisible to the body, and never merged with a body `var` of the same
117/// name.
118///
119/// Without this, `function f(a = 1, p = () => a) { var a = 2 }` made `p()` return 2:
120/// the closure and the body shared one slot, when only the parameters were in scope
121/// when it was created.
122const PARAM_SCOPE: u64 = u64::MAX - 4;
123
124/// The name of the hidden local a `using` declaration caches its dispose method in.
125///
126/// It has to be a name no source can produce, because a script may declare anything: the
127/// angle brackets keep it out of the identifier grammar, exactly like `<ret>`.
128fn using_method_name(name: &str) -> String {
129    format!("<using.method {name}>")
130}
131
132/// The `blocks` parent sentinel for "this block has no enclosing block".
133///
134/// Same reasoning as [`FUNCTION_SCOPE`]: `0` is a legal block key, and when it was
135/// also the terminator the chain walk from the script body reached the file's
136/// offset-zero block and treated it as an *enclosing* block — so that block's `let`
137/// leaked into the body scope.
138const NO_PARENT: u64 = u64::MAX - 2;
139
140/// The block key for a script body. Distinct from both sentinels and unreachable from
141/// any source offset.
142const SCRIPT_BODY: u64 = u64::MAX - 1;
143
144/// An operand of a symbolic instruction.
145#[derive(Debug, Clone, PartialEq)]
146enum Op {
147    /// An immediate integer.
148    Int(i32),
149    /// A jump target.
150    Label(Label),
151    /// A constant pool index.
152    Const(u32),
153    /// An atom, before interning.
154    Atom(Atom),
155    /// An interned atom, as an index into [`Function::atoms`].
156    AtomId(u32),
157    /// A resolved slot.
158    Slot(Slot),
159}
160
161/// Where a resolved variable lives.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163enum Slot {
164    Arg(u32),
165    Loc(u32),
166    VarRef(u32),
167    /// A global, by closure-var index.
168    Global(u32),
169    /// A global *declared* in this script. The reference keeps these bindings in
170    /// reference cells so that the script and any closure share one variable, so
171    /// a store goes through `put_var_ref` while a read uses `get_var`.
172    GlobalDecl(u32),
173}
174
175/// What a symbolic variable access does, which decides the final opcode.
176#[derive(Debug, Clone, Copy, PartialEq, Eq)]
177enum VarAction {
178    /// Read the value.
179    Get,
180    /// Read the value, yielding `undefined` for an undeclared global.
181    GetUndef,
182    /// Write, leaving nothing on the stack.
183    Put,
184    /// Write and initialise, leaving the value on the stack.
185    PutInit,
186    /// Write, leaving the value on the stack.
187    Set,
188    /// Initialise a binding that may only be initialised once, such as a derived
189    /// constructor's `this`.
190    PutInitChecked,
191    /// Initialise, leaving the value on the stack and without the `const` check.
192    ///
193    /// A class's own scope binding is a `const` that has to be initialised in the middle
194    /// of the definition — after the constructor exists but before the static fields run
195    /// — and the value has to survive for the outer store to use.
196    SetInit,
197    /// Write a binding that lives in a reference cell.
198    PutRef,
199}
200
201#[derive(Debug, Clone)]
202enum Insn {
203    /// A fully determined instruction.
204    Fixed { op: Opcode, operands: Vec<Op> },
205    /// A variable access, resolved in the second pass.
206    ///
207    /// `block` is the lexical block the access appears in, which is what makes
208    /// shadowing work: two bindings can share a name, and the one that wins is
209    /// whichever scope encloses the access.
210    Var {
211        action: VarAction,
212        name: String,
213        block: u64,
214        /// Whether the access was written in the parameter list; see
215        /// [`FnState::in_params`].
216        in_params: bool,
217    },
218    /// Close a binding *if* it turned out to be captured.
219    ///
220    /// Whether a `for (let i ...)` loop variable needs a fresh per-iteration cell is
221    /// only known once the body has been compiled — a closure created there is the
222    /// thing that makes it necessary. The reference emits `close_loc` exactly in that
223    /// case and nothing otherwise, so the decision is deferred to [`resolve`] instead
224    /// of emitted blind.
225    CloseCaptured { name: String, block: u64 },
226    /// `delete name`, which can only answer `false` once the binding is known.
227    ///
228    /// It is not a `Var` action because `delete_var` carries an *atom*: the runtime
229    /// looks the name up on the global object, which is what distinguishes an implicit
230    /// global (configurable, deletable) from a declared one (a binding, always `false`).
231    DeleteVar { name: String },
232    /// An instruction that dead-code elimination removed. It keeps its slot so
233    /// that label indices stay valid, and resolves to no bytecode.
234    Dead,
235}
236
237/// Where `break` and `continue` jump to.
238///
239/// Targets are stacked as the compiler enters loops and labelled statements, so a
240/// bare `break` needs no analysis: it is simply the innermost target. A labelled
241/// one searches outward by name.
242#[derive(Debug, Clone)]
243struct JumpTarget {
244    /// The labels attached to this target. `l: for(;;)` gives one name; a bare
245    /// loop gives none; `a: b: for(;;)` gives two, because both labels name the
246    /// same statement and `break a` must reach the same place as `break b`.
247    names: Vec<String>,
248    /// Where `break` lands. `None` for a construct `break` may only leave, not
249    /// target — a `try`, whose entry exists purely to unwind.
250    break_label: Option<Label>,
251    /// Where `continue` lands. `None` for anything that is not a loop.
252    continue_label: Option<Label>,
253    /// Stack slots to discard when control leaves this construct by a jump.
254    ///
255    /// Both `switch` and `try` leave something on the value stack for the duration
256    /// of the construct — the discriminant, or the `catch` offset — and a jump out
257    /// has to take it with it. A loop leaves nothing.
258    drop_count: u32,
259    /// The finalizer to run when control leaves this construct.
260    ///
261    /// Set on a `try` even when it has no `finally`: the label is always emitted and
262    /// the empty-subroutine removal cleans up afterwards, so the code that unwinds
263    /// does not have to know whether a finalizer exists.
264    finally_label: Option<Label>,
265    /// Whether this is a labelled non-loop statement, which an unlabelled `break`
266    /// does not reach.
267    is_regular_stmt: bool,
268    /// Whether leaving this construct has to close an iterator.
269    ///
270    /// A `for`/`of` loop keeps an iterator on the value stack, and leaving early has
271    /// to run its `return` method. `for`/`in` keeps only an enumeration object, which
272    /// is dropped rather than closed.
273    has_iterator: bool,
274    /// Whether that iterator speaks the *async* protocol.
275    ///
276    /// An async close has to `await` the inner `return`, so it is an inline instruction
277    /// sequence rather than one opcode — the reference's `emit_iterator_close`.
278    is_async_iterator: bool,
279}
280
281/// Whether a named property read should be `get_field2` rather than `dup; get_field`.
282///
283/// Both leave `source value` on the stack, so this is purely which spelling the reference
284/// picked, and it picked it by whether it had to build a *reference* for the target:
285///
286/// * a target that is itself a pattern starts by boxing the value, so the copy is what it
287///   consumes — `get_field2` (and a default does not change that: `{a: {b} = {}}` still
288///   destructures);
289/// * a `let`/`const` binding needs no reference, so the reference takes the short form;
290/// * a `var`, and any assignment target, go through `dup; get_field`, because the
291///   reference builds a reference for them — which is what `with` needs.
292fn reads_with_get_field2(decl: Option<VarDeclKind>, value: &Pattern) -> bool {
293    nests_a_pattern(value) || matches!(decl, Some(VarDeclKind::Let) | Some(VarDeclKind::Const))
294}
295
296/// Whether binding this pattern starts by boxing the value it was handed.
297fn nests_a_pattern(pattern: &Pattern) -> bool {
298    match &pattern.kind {
299        PatternKind::Array { .. } | PatternKind::Object { .. } => true,
300        PatternKind::Assign { target, .. } => nests_a_pattern(target),
301        _ => false,
302    }
303}
304
305/// `copy_data_properties` flags for an object-literal spread.
306///
307/// The byte packs three fields: the low bits are the stack offset of the source,
308/// the next three the offset of the exclusion list, and bit 2 asks for symbol keys
309/// as well as string keys. A spread passes a literal `null` exclusion list right
310/// below the source, so that field stays zero and only the source offset and the
311/// symbol bit are set — hence `{...v}` copies symbols, which the flag name says.
312const COPY_ALL_PROPERTIES: i32 = 2 | (1 << 2);
313
314/// The expression a `...` introduces.
315///
316/// The parser marks the spread in two places — the element/property variant and an
317/// [`ExprKind::Spread`] wrapper around the argument — so the wrapper has to be
318/// stepped through before the argument can be compiled.
319fn spread_argument(spread: &Expr) -> &Expr {
320    match &spread.kind {
321        ExprKind::Spread(inner) => inner,
322        _ => spread,
323    }
324}
325
326/// The flag byte `define_method` takes.
327///
328/// The low two bits pick value/getter/setter; bit 2 marks the property
329/// enumerable, which every object-literal method is.
330/// What kind of class constructor a function is being compiled as.
331///
332/// A constructor is not an ordinary method: a base one materialises `this` and refuses
333/// to run without `new`, and a derived one starts with `this` in the dead zone until
334/// `super()` produces it.
335#[derive(Debug, Clone, Copy, PartialEq, Eq)]
336enum CtorKind {
337    /// Not a class constructor.
338    None,
339    /// A constructor of a class without `extends`.
340    Base,
341    /// A constructor of a class with `extends`.
342    Derived,
343}
344
345/// The flag byte `define_method` takes for a class member.
346///
347/// The low two bits pick value/getter/setter; bit 2 marks the property enumerable, which
348/// a class method is *not* — that is the whole difference from an object-literal method,
349/// and the reason `Object.keys(C.prototype)` stays empty.
350fn class_method_flags(kind: MethodKind) -> i32 {
351    match kind {
352        MethodKind::Constructor | MethodKind::Method => 0,
353        MethodKind::Get => 1,
354        MethodKind::Set => 2,
355    }
356}
357
358fn define_method_flags(kind: PropertyKind) -> i32 {
359    let base = match kind {
360        PropertyKind::Value | PropertyKind::Method => 0,
361        PropertyKind::Get => 1,
362        PropertyKind::Set => 2,
363    };
364    base | 4
365}
366
367/// Convert a numeric property key to the text an atom would be made from.
368///
369/// Only the range where Rust and JavaScript agree on the spelling is accepted.
370/// Both print the shortest representation that round-trips, so plain decimal
371/// digits match; they diverge at the extremes, where JavaScript switches to an
372/// exponent (`1e-7`, `1e+21`) and Rust does not. Rather than emit an atom that
373/// differs from the reference, those keys are rejected.
374fn numeric_key_text(value: f64, span: Span) -> Result<String, SyntaxError> {
375    if !value.is_finite() {
376        return Err(SyntaxError::new(
377            "a non-finite numeric property key is not supported by the compiler yet",
378            span,
379        ));
380    }
381    if value == value.trunc() && value.abs() < 1e21 {
382        return Ok(format!("{}", value as i64));
383    }
384    if value.abs() >= 1e-6 && value.abs() < 1e21 {
385        return Ok(format!("{value}"));
386    }
387    Err(SyntaxError::new(
388        "a numeric property key outside [1e-6, 1e21) is not supported by the compiler yet",
389        span,
390    ))
391}
392
393/// Collect the operands of a same-operator logical run, in source order.
394///
395/// Recurses down the left spine only: `((a || b) || c)` contributes `a`, `b`, then
396/// the caller appends `c`. A node with a different operator is one operand.
397fn collect_same_operator<'a>(op: LogicalOp, expr: &'a Expr, out: &mut Vec<&'a Expr>) {
398    if let ExprKind::Logical {
399        op: inner_op,
400        left,
401        right,
402    } = &expr.kind
403        && *inner_op == op
404    {
405        collect_same_operator(op, left, out);
406        out.push(right);
407        return;
408    }
409    out.push(expr);
410}
411
412/// The jump a logical assignment or `??` takes when the value is kept.
413///
414/// `||` and `&&` branch on truthiness, so the same opcode serves both the operator
415/// and `??` once [`Compiler::emit_logical_test`] has pushed a boolean. `??` keeps
416/// the value when it is *not* null-ish, so it is the `if_false` side.
417fn logical_jump(op: AssignOp) -> Opcode {
418    match op {
419        AssignOp::Or => Opcode::IfTrue,
420        AssignOp::And | AssignOp::Coalesce => Opcode::IfFalse,
421        _ => Opcode::IfFalse,
422    }
423}
424
425/// Whether a loop enumerates keys or values.
426#[derive(Debug, Clone, Copy, PartialEq, Eq)]
427enum ForLoopKind {
428    /// `for (x in o)` — the keys of an object.
429    In,
430    /// `for (x of o)` — the values of an iterable.
431    Of,
432    /// `for await (x of o)` — the values of an async iterable, or of a sync one.
433    AwaitOf,
434}
435
436/// Which part of a `try` statement a block key refers to.
437#[derive(Debug, Clone, Copy)]
438enum TryPart {
439    /// The guarded block.
440    Block = 0,
441    /// The handler body, excluding the catch parameter.
442    Catch = 1,
443    /// The finalizer block.
444    Finally = 2,
445    /// The catch parameter's own scope.
446    Param = 3,
447}
448
449/// A lexical scope, identified while hoisting and numbered at the end.
450///
451/// Scope identity is needed in two passes that must agree: declarations are
452/// hoisted in source order (so slots come out in source order, as in the
453/// reference), but a binding belongs to the block it was written in, which is only
454/// entered later. Blocks are therefore keyed by the source position of their
455/// opening brace, which is stable across both walks.
456#[derive(Debug, Clone, Copy)]
457struct Block {
458    /// Source position of the block.
459    key: u64,
460    /// The block this one is nested in; `0` for the function scope.
461    parent: u64,
462}
463
464/// One function under construction.
465struct FnState {
466    name: String,
467    kind: FunctionKind,
468    strict: bool,
469    args: Vec<VarDef>,
470    vars: Vec<VarDef>,
471    closure_vars: Vec<ClosureVar>,
472    cpool: Vec<Constant>,
473    atoms: Vec<Atom>,
474    /// Every lexical scope, in creation order.
475    blocks: Vec<Block>,
476    /// The block currently being parsed or compiled.
477    current_block: u64,
478    /// The block a *nested* function was created in, so a capture made from here can be
479    /// resolved against the enclosing function's lexical scopes rather than against a
480    /// flat name table. Without it, `function f(){ class S{} }` capturing `S` found the
481    /// function's own `let S` instead of the class body's `const S`.
482    created_in_block: u64,
483    /// The block each local was declared in, parallel to `vars`. `0` means the
484    /// function scope, where `var` bindings live.
485    var_block: Vec<u64>,
486    /// Set when the expression just compiled left no value on the stack.
487    ///
488    /// Only a store can do that: `put_field` consumes the object and the value, so
489    /// an assignment whose result is unused emits nothing extra. The expression
490    /// statement then has nothing to drop.
491    no_value: bool,
492    /// Whether a label was placed since the last instruction was emitted.
493    ///
494    /// The `put`/`get` fold is only valid when the two are adjacent in the final
495    /// stream; a label in between means a jump can land on the read, so the store has
496    /// to keep consuming its value. A flag is enough and avoids having to reason about
497    /// which index a label recorded.
498    label_since_insn: bool,
499    /// Whether the value of the expression being compiled is thrown away.
500    ///
501    /// Only an expression *statement* discards its value, and only the outermost
502    /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
503    /// still has to produce a value. Consumed by [`Compiler::assign`], which is
504    /// the one construct whose bytecode depends on it.
505    discard_value: bool,
506    /// The block that holds the function body.
507    body_block: u64,
508    /// Head of each scope's binding chain, indexed by level. Filled in by
509    /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
510    block_heads: Vec<i32>,
511    /// Enclosing `break`/`continue` targets, innermost last.
512    jump_targets: Vec<JumpTarget>,
513    insns: Vec<Insn>,
514    labels: Vec<Option<usize>>,
515    /// Captured locals, which need a reference cell.
516    var_ref_count: u32,
517    line: u32,
518    column: u32,
519    /// Whether this is a script body. A script's top-level declarations create
520    /// global properties rather than locals, which is why they show up as
521    /// closure variables with `[global_decl]`.
522    is_script: bool,
523    /// Whether this is a module body.
524    ///
525    /// A module body is a script in every respect that matters here — no `arguments`,
526    /// no `this` of its own — but its top-level declarations are *module*-scoped
527    /// instead of global, which is what this flag changes.
528    is_module: bool,
529    /// Whether the function is an arrow, which never gets its own `arguments`.
530    is_arrow: bool,
531    /// The name a *named function expression* binds inside its own body.
532    /// How many parameters count towards `.length`.
533    defined_args: u32,
534    /// Parameters that are not a plain name, with the argument slot each came from.
535    param_prologue: Vec<(usize, Pattern)>,
536    /// What kind of class constructor this function is, if any.
537    ctor_kind: CtorKind,
538    /// Whether the class has instance fields, so the constructor has to run their
539    /// initialiser before it returns.
540    /// What the nested function about to be compiled should be told about its class.
541    class_ctor_pending: Option<CtorKind>,
542    /// Whether this function needs the hidden `this` local, because an arrow inside it
543    /// refers to `this`.
544    ///
545    /// An arrow has no `this` of its own, so the reference materialises the enclosing
546    /// function's receiver into a local and lets the arrow capture it as an ordinary
547    /// closure variable. Declaring the local is not enough on its own: the store that
548    /// fills it has to be prepended to the body, which is what this flag arranges.
549    needs_this_local: bool,
550    /// The same, for `arguments`.
551    needs_arguments_local: bool,
552    /// The same, for `new.target`.
553    needs_new_target_local: bool,
554    /// Whether the body already opens by filling a `this` local, which
555    /// [`Compiler::begin_this_local`] does for a constructor and a field initialiser.
556    has_this_prologue: bool,
557    /// The same, for `<home_object>`: the object `super` resolves against.
558    ///
559    /// An arrow and a static block have no home object of their own — only the method or
560    /// initialiser they were written in does — so `super.x` inside one is a read of the
561    /// enclosing function's `[[HomeObject]]`. The value is materialised into a local there
562    /// by `special_object 4`, the same way `this` is.
563    needs_home_object_local: bool,
564    /// The same, for `this.active_func`: the function `super()` constructs from.
565    ///
566    /// An arrow has no `super` of its own, so it reads the enclosing function's — and that
567    /// is a *lexical* relationship, not a stack one. The reference keeps `this_active_func`
568    /// as a local of the enclosing function; an arrow that escaped the constructor
569    /// (`iter.return = () => super()`) then finds it in its closure even with the
570    /// constructor nowhere on the call stack.
571    needs_active_func_local: bool,
572    /// Hidden locals of the `with` blocks currently open, innermost last.
573    with_names: Vec<String>,
574    /// Set while a with-guard is being emitted, so the guard's own accesses are not
575    /// wrapped in another guard.
576    emitting_with_guard: bool,
577    self_name: Option<String>,
578    /// Where the function body starts, in source order; see [`Function::body_start`].
579    body_start: (u32, u32),
580    /// Whether the body contains a *direct* `eval(...)` call.
581    ///
582    /// A direct eval sees every binding of the function that called it, including ones
583    /// no other code mentions. It also hands those bindings to any closure it creates,
584    /// which can outlive the function. Both need the bindings to live in cells, so this
585    /// flag makes the function treat all of them as captured.
586    has_direct_eval: bool,
587    /// Whether the parameter list contains a default expression, which is what gives
588    /// the function a second variable environment (see [`PARAM_SCOPE`]).
589    has_parameter_expressions: bool,
590    /// Whether the instructions being emitted belong to the parameter list.
591    ///
592    /// References made here must not see the body's `var`s: the body has not run yet,
593    /// and the reference's own model keeps the two scopes apart.
594    in_params: bool,
595    /// Whether an arrow created in this function's parameter list needs the parameter
596    /// scope's `arguments` binding.
597    needs_param_arguments: bool,
598    /// Whether this function was *created* inside a parameter list.
599    ///
600    /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
601    /// arrow too. The name reference is the arrow's, but the scope it must not see
602    /// belongs to the function the arrow was born in.
603    created_in_params: bool,
604    /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
605    ///
606    /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
607    /// final while the body is still being compiled: a named function expression declares
608    /// its own name binding *after* the body, and that binding is exactly what
609    /// `eval("myfunc = 1")` has to find.
610    eval_sites: Vec<EvalSite>,
611    /// Direct `eval` call sites seen so far: where, and the block that was current.
612    pending_eval_sites: Vec<(Span, u64, bool)>,
613    /// Whether this body contains `await`.
614    ///
615    /// For a *module* this decides whether its body is an async function: top-level
616    /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
617    /// to survive to the compiled function rather than being a local of the compiler.
618    has_await: bool,
619    /// The module tables, when this body is a module.
620    ///
621    /// Only the top-level state ever has one: `export` and `import` are top-level
622    /// statements, so nothing nested can add to these tables.
623    module: Option<ModuleMeta>,
624    /// Whether the self-name prologue (`special_object 2` then the store) has been
625    /// emitted for this function.
626    ///
627    /// A *nested* function's lookup declares the binding early (see
628    /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
629    /// prologue is still needed — the binding existing is not the same as it being
630    /// initialised.
631    self_name_initialized: bool,
632    /// Whether the code emitted so far leaves the program's result on the stack.
633    /// The reference tracks this for the hidden `<ret>` local of an eval script.
634    leaves_value: bool,
635    /// Statement nesting depth, used to tell top-level statements apart.
636    stmt_depth: u32,
637    /// Function declarations waiting to be instantiated at scope entry, as
638    /// (target slot, constant pool index). The reference emits these from
639    /// `instantiate_hoisted_definitions` rather than at the statement, because a
640    /// declaration is visible before it is reached.
641    hoisted: Vec<(u64, HoistTarget, u32)>,
642    /// Function declarations whose bodies are compiled only once the enclosing scope
643    /// has finished hoisting, as (owning block, declaration).
644    ///
645    /// Compiling a body at the declaration makes the result depend on source order: in
646    /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
647    /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
648    /// names first and the bodies second is what removes that dependence.
649    deferred_funcs: Vec<(u64, Box<ast::Function>)>,
650    /// The source position of the node being compiled. Every instruction emitted
651    /// takes it, which is how the position table that feeds stack traces is built.
652    cur_pos: Option<Position>,
653    /// One position per entry in `insns`, index-aligned.
654    insn_pos: Vec<Option<Position>>,
655}
656
657/// Where a hoisted function declaration is stored.
658#[derive(Debug, Clone)]
659enum HoistTarget {
660    Arg(u32),
661    Loc(u32),
662    /// A global, which the resolver looks up by name.
663    Global(String),
664}
665
666impl FnState {
667    /// Whether this function suspends: a generator or an async function.
668    ///
669    /// A suspending function's `return` is a `return_async` and its body starts with an
670    /// `initial_yield`, so almost every statement that touches control flow asks this.
671    fn is_suspending(&self) -> bool {
672        self.kind.is_generator() || self.kind.is_async()
673    }
674
675    fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
676        FnState {
677            name: name.into(),
678            kind,
679            strict: false,
680            args: Vec::new(),
681            vars: Vec::new(),
682            closure_vars: Vec::new(),
683            cpool: Vec::new(),
684            atoms: Vec::new(),
685            blocks: Vec::new(),
686            current_block: 0,
687            created_in_block: NO_PARENT,
688            var_block: Vec::new(),
689            no_value: false,
690            label_since_insn: false,
691            discard_value: false,
692            body_block: 0,
693            block_heads: Vec::new(),
694            jump_targets: Vec::new(),
695            insns: Vec::new(),
696            labels: Vec::new(),
697            var_ref_count: 0,
698            line: 1,
699            column: 1,
700            is_script: false,
701            is_module: false,
702            is_arrow: false,
703            defined_args: 0,
704            param_prologue: Vec::new(),
705            ctor_kind: CtorKind::None,
706            class_ctor_pending: None,
707            needs_this_local: false,
708            needs_arguments_local: false,
709            needs_new_target_local: false,
710            has_this_prologue: false,
711            needs_home_object_local: false,
712            needs_active_func_local: false,
713            with_names: Vec::new(),
714            emitting_with_guard: false,
715            self_name: None,
716            has_direct_eval: false,
717            body_start: (0, 0),
718            has_parameter_expressions: false,
719            in_params: false,
720            needs_param_arguments: false,
721            created_in_params: false,
722            eval_sites: Vec::new(),
723            pending_eval_sites: Vec::new(),
724            has_await: false,
725            module: None,
726            self_name_initialized: false,
727            leaves_value: false,
728            stmt_depth: 0,
729            hoisted: Vec::new(),
730            deferred_funcs: Vec::new(),
731            cur_pos: None,
732            insn_pos: Vec::new(),
733        }
734    }
735
736    /// The scope a declaration lands in: a script's top-level declarations are
737    /// globals, everything else gets a slot.
738    /// Whether a binding declared *now* becomes a property of the global object.
739    ///
740    /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
741    /// The `var` case is decided by the keyword rather than by the cursor position:
742    /// `var` is function-scoped, so a `var i` in a `for` head is still the same
743    /// binding as a `var i` in the body, even though the head has its own block.
744    fn declares_globally(&self, def: &VarDef) -> bool {
745        // A module's top-level declarations are *module*-scoped: they live in the module
746        // record, never on the global object. Two modules can both declare `var x`
747        // without seeing each other, which is the whole point.
748        if self.is_module {
749            return false;
750        }
751        self.is_script && (!def.is_lexical || self.current_block == self.body_block)
752    }
753}
754
755/// The compiler's entry point.
756pub struct Compiler {
757    module: bool,
758    /// Whether the program itself is the body of an `async` function.
759    ///
760    /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
761    /// completion value is wrapped so a returned promise is not adopted.
762    async_body: bool,
763    /// Enclosing functions, outermost first. The last entry is the current one.
764    stack: Vec<FnState>,
765    /// The private names visible at this point, innermost class body last.
766    ///
767    /// A stack rather than a field of `FnState` because a private name is *lexically* scoped
768    /// to the class body: a method, an arrow inside it and a class nested inside that arrow
769    /// all resolve against the same entries, and the parser accepts exactly that set
770    /// (`self.private` in `parser.rs`). `FnState` is per-function, so it would lose the outer
771    /// class's names the moment a method started.
772    private_scopes: Vec<std::collections::HashMap<String, PrivateUse>>,
773}
774
775/// How a use site of a private name compiles.
776///
777/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
778/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
779/// of a setter-only accessor pair.
780#[derive(Clone, Copy, PartialEq, Eq)]
781enum PrivateKind {
782    /// `#x = 1`: an own property keyed by the symbol in the binding.
783    Field,
784    /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
785    Method,
786    /// `get #a() {}`: the binding holds the getter, and a read calls it.
787    Getter,
788    /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
789    /// the same `TypeError` as reading an uninitialised `const`.
790    Setter,
791}
792
793/// What the compiler knows about one `#name` where it is used.
794#[derive(Clone)]
795struct PrivateUse {
796    kind: PrivateKind,
797    /// `#a<set>` when the class defines a setter for this name.
798    ///
799    /// A second binding, not a second field of the first: the reference stores the setter
800    /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
801    setter: Option<String>,
802}
803
804/// The class-scope bindings one class body needs, in declaration order.
805#[derive(Default)]
806struct ClassPlan {
807    /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
808    /// at class entry, in member order.
809    bindings: Vec<String>,
810    /// The private names, for the use sites inside the body.
811    uses: std::collections::HashMap<String, PrivateUse>,
812    /// Computed field keys, by element index, so the emission pass does not have to redo the
813    /// per-half counter that names them.
814    computed: std::collections::HashMap<usize, String>,
815    /// Whether the instance initialiser has to add the brand to `this`.
816    instance_brand: bool,
817    /// Whether the constructor itself has to carry the brand.
818    static_brand: bool,
819}
820
821impl ClassPlan {
822    /// Walk a class body once and decide every class-scope binding it needs.
823    ///
824    /// Order is the reference's: a member's binding is created when the member is parsed, so
825    /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
826    /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
827    /// the disassembly stops matching even when every instruction is right.
828    fn build(class: &Class) -> ClassPlan {
829        let mut plan = ClassPlan::default();
830        let mut instance_keys = 0usize;
831        let mut static_keys = 0usize;
832        for (index, element) in class.elements.iter().enumerate() {
833            match element {
834                ClassElement::Method {
835                    key: PropName::Private(ident),
836                    kind,
837                    is_static,
838                    ..
839                } => {
840                    let name = format!("#{}", ident.name);
841                    let first = !plan.uses.contains_key(&name);
842                    if first {
843                        plan.bindings.push(name.clone());
844                        plan.uses.insert(
845                            name.clone(),
846                            PrivateUse {
847                                kind: match kind {
848                                    MethodKind::Get => PrivateKind::Getter,
849                                    MethodKind::Set => PrivateKind::Setter,
850                                    _ => PrivateKind::Method,
851                                },
852                                setter: None,
853                            },
854                        );
855                    }
856                    match kind {
857                        MethodKind::Set => {
858                            let binding = format!("{name}<set>");
859                            plan.bindings.push(binding.clone());
860                            if let Some(use_) = plan.uses.get_mut(&name) {
861                                use_.setter = Some(binding);
862                            }
863                        }
864                        // A getter is what makes the name readable, so a pair that started
865                        // as a setter becomes readable once the getter arrives.
866                        MethodKind::Get => {
867                            if let Some(use_) = plan.uses.get_mut(&name) {
868                                use_.kind = PrivateKind::Getter;
869                            }
870                        }
871                        _ => {}
872                    }
873                    if *is_static {
874                        plan.static_brand = true;
875                    } else {
876                        plan.instance_brand = true;
877                    }
878                }
879                ClassElement::Method {
880                    key: PropName::Computed(_),
881                    ..
882                } => {}
883                ClassElement::Method { .. } => {}
884                ClassElement::Field {
885                    key: PropName::Private(ident),
886                    ..
887                } => {
888                    let name = format!("#{}", ident.name);
889                    if !plan.uses.contains_key(&name) {
890                        plan.bindings.push(name.clone());
891                        plan.uses.insert(
892                            name,
893                            PrivateUse {
894                                kind: PrivateKind::Field,
895                                setter: None,
896                            },
897                        );
898                    }
899                }
900                ClassElement::Field {
901                    key: PropName::Computed(_),
902                    is_static,
903                    ..
904                } => {
905                    let index_in_half = if *is_static {
906                        static_keys += 1;
907                        static_keys - 1
908                    } else {
909                        instance_keys += 1;
910                        instance_keys - 1
911                    };
912                    let binding = computed_field_binding(index_in_half, *is_static);
913                    plan.bindings.push(binding.clone());
914                    plan.computed.insert(index, binding);
915                }
916                ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
917            }
918        }
919        plan
920    }
921
922    /// How a private name used inside the body compiles, or `None` if no enclosing class
923    /// declares it.
924    fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
925        compiler
926            .private_scopes
927            .iter()
928            .rev()
929            .find_map(|scope| scope.get(name))
930    }
931}
932
933/// Compile a script.
934pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
935    Compiler::new(false).compile(program)
936}
937
938/// Compile a script whose top level is the body of an `async` function.
939///
940/// The body is an ordinary script in every other way — it still reports a completion value
941/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
942/// it answers a promise instead of a value. The wrapper is what keeps that promise from
943/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
944/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
945/// documents.
946pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
947    Compiler::for_suspensible_script().compile(program)
948}
949
950/// Compile a module.
951pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
952    Compiler::new(true).compile(program)
953}
954
955impl Compiler {
956    /// Create a compiler.
957    pub fn new(module: bool) -> Compiler {
958        Compiler {
959            module,
960            async_body: false,
961            stack: Vec::new(),
962            private_scopes: Vec::new(),
963        }
964    }
965
966    /// Create a compiler for a script whose top level is an `async` function body.
967    fn for_suspensible_script() -> Compiler {
968        Compiler {
969            module: false,
970            async_body: true,
971            stack: Vec::new(),
972            private_scopes: Vec::new(),
973        }
974    }
975
976    /// Compile a whole program into its top-level function.
977    pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
978        let mut state = FnState::new("<eval>", FunctionKind::Normal);
979        // A module body is *not* a script: it has no completion value, so no hidden
980        // `<ret>` local and no `put_loc0` before each statement. What it shares with one
981        // is having no `arguments` of its own and no receiver — see `is_module`.
982        state.is_script = !self.module;
983        state.is_module = self.module;
984        if self.module {
985            state.module = Some(ModuleMeta::default());
986        }
987        state.strict = program.strict || self.module;
988        state.line = program.span.start.line;
989        state.column = program.span.start.column;
990        // Locals are numbered in declaration order; `<ret>` is always slot 0.
991        //
992        // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
993        // slot that only appears in one of the two arrays shifts every later
994        // binding's block and silently loses the temporal-dead-zone marking for
995        // the script's own blocks. A function frame has no `<ret>`, which is why
996        // the misalignment only showed up at the top level.
997        if !self.module {
998            state.vars.push(VarDef::var("<ret>"));
999            state.var_block.push(FUNCTION_SCOPE);
1000        }
1001        self.stack.push(state);
1002        // The body is its own scope, keyed by the position of the program.
1003        // The script body needs a key no statement can produce. Statement keys are
1004        // source offsets, and the program's own start offset is `0` — which is also
1005        // the offset of the first statement, so a top-level `{ let x }` or
1006        // `for (let i …)` used to share the body's block and lose its scope.
1007        let body_key = SCRIPT_BODY;
1008        self.push_block(body_key, NO_PARENT);
1009        self.state().body_block = body_key;
1010        // A module body opens with a re-entry guard. The host evaluates a module exactly
1011        // once, so the guard never fires in practice — but the reference emits it, and a
1012        // module function called a second time (through `eval` of its own source, say)
1013        // must not run its body again.
1014        let module_guard = self.module.then(|| self.new_label());
1015        if let Some(body) = module_guard {
1016            // The guard wraps the *hoisting* too: a second evaluation of the same module
1017            // body must not even re-create its function declarations.
1018            self.emit(Opcode::PushThis, &[]);
1019            self.emit_jump(Opcode::IfFalse, body, &[]);
1020        }
1021        self.hoist(&program.body, body_key)?;
1022        // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
1023        // come before the guard's `return_undef`: the reference's jump target sits past
1024        // both, and a second evaluation therefore re-creates nothing.
1025        self.emit_scope_enter(body_key);
1026        if let Some(body) = module_guard {
1027            self.emit(Opcode::ReturnUndef, &[]);
1028            self.place_label(body);
1029        }
1030        // Through `stmts` rather than the loop, so a `using` region at the top level of an
1031        // eval'd body or a module gets its disposal epilogue like any other block.
1032        self.stmts(&program.body)?;
1033        if self.module {
1034            // A module has no completion value; its body simply ends.
1035            self.emit(Opcode::Undefined, &[]);
1036            self.emit(Opcode::ReturnAsync, &[]);
1037            // Top-level `await` makes the body an async function, so the host runs it as
1038            // a coroutine and waits. Without this the `await` opcode would suspend in a
1039            // body that nothing knows how to resume — which is what "a generator body ran
1040            // as an ordinary call" was reporting.
1041            if self.cur().has_await {
1042                self.state().kind = FunctionKind::Async;
1043            }
1044        } else if self.async_body {
1045            // An async body reports its completion value the same way, but through an
1046            // object: the function answers a promise, and resolving that promise *with*
1047            // the completion value would adopt a promise completion instead of reporting
1048            // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
1049            // resolve to `{value: <promise>}` rather than to `7`.
1050            //
1051            // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
1052            // value in an object so that promises can be safely returned").
1053            self.emit(Opcode::Object, &[]);
1054            self.emit(Opcode::Dup, &[]);
1055            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1056            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
1057            self.emit(Opcode::Return, &[]);
1058            self.state().kind = FunctionKind::Async;
1059        } else {
1060            // The program's value is whatever the last expression statement stored in
1061            // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
1062            // case into a single `set_loc0`.
1063            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1064            self.emit(Opcode::Return, &[]);
1065        }
1066        Ok(self.finish_current())
1067    }
1068
1069    // -- emitting ----------------------------------------------------------
1070
1071    fn state(&mut self) -> &mut FnState {
1072        self.stack.last_mut().expect("a function is being compiled")
1073    }
1074
1075    fn cur(&self) -> &FnState {
1076        self.stack.last().expect("a function is being compiled")
1077    }
1078
1079    fn emit(&mut self, op: Opcode, operands: &[Op]) {
1080        self.state().label_since_insn = false;
1081        let pos = self.cur().cur_pos;
1082        self.state().insns.push(Insn::Fixed {
1083            op,
1084            operands: operands.to_vec(),
1085        });
1086        self.state().insn_pos.push(pos);
1087    }
1088
1089    /// Reset the script's hidden return value to `undefined`.
1090    ///
1091    /// Called at the start of every statement that does not itself produce the
1092    /// program's value, which is how the reference keeps `if`/loop results from
1093    /// leaking into an eval result.
1094    fn reset_value(&mut self) {
1095        if !self.cur().is_script {
1096            return;
1097        }
1098        self.emit(Opcode::Undefined, &[]);
1099        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1100        self.state().leaves_value = false;
1101    }
1102
1103    /// Whether `name` is a local or argument slot rather than a global.
1104    fn is_slot(&self, name: &str) -> bool {
1105        self.cur().vars.iter().any(|v| v.name == name)
1106            || self.cur().args.iter().any(|a| a.name == name)
1107    }
1108
1109    /// `with (object) body`
1110    ///
1111    /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
1112    /// what makes the object reachable from a closure created inside the block, and it
1113    /// is also what lets an `eval` find it: the runtime collects the active `With`
1114    /// locals of every frame and resolves names against them before the realm.
1115    ///
1116    /// Inside the block every name reference is spelled as "look in the with objects
1117    /// first", innermost outwards, and falls through to the ordinary access. The test is
1118    /// `in`, which is `HasProperty` — the same question the spec's Object Environment
1119    /// Record asks.
1120    fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
1121        let name = self.next_with_name();
1122        // The object expression is evaluated *outside* the scope it introduces, so no
1123        // wrapper may be emitted for the names it mentions.
1124        let saved = std::mem::take(&mut self.state().with_names);
1125        self.expr(object)?;
1126        self.state().with_names = saved;
1127        self.emit(Opcode::ToObject, &[]);
1128        self.declare_hidden_local(&name, VarKind::With);
1129        // Pushed before the store so the store itself is not guarded by an *outer*
1130        // `with` — the object being stored is the new one, not something to look up.
1131        self.state().with_names.push(name.clone());
1132        self.emit_var(VarAction::Put, &name);
1133        let result = self.stmt(body);
1134        self.state().with_names.pop();
1135        result
1136    }
1137
1138    /// A hidden-local name for one `with` block, distinct from every enclosing one.
1139    fn next_with_name(&self) -> String {
1140        let depth = self.cur().with_names.len();
1141        if depth == 0 {
1142            "<with>".to_string()
1143        } else {
1144            format!("<with{depth}>")
1145        }
1146    }
1147
1148    /// Declare a hidden local that must stay a *local* even in a script.
1149    ///
1150    /// A script's `var` is a property of the global object, but the `with` object is not
1151    /// part of the source program's name space at all — it only exists for the compiler
1152    /// and the runtime — so it goes straight into the frame's slot list.
1153    fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
1154        let state = self.state();
1155        if state.vars.iter().any(|v| v.name == name) {
1156            return;
1157        }
1158        state.var_block.push(FUNCTION_SCOPE);
1159        state.vars.push(VarDef {
1160            kind,
1161            ..VarDef::var(name)
1162        });
1163    }
1164
1165    /// Emit a name access, guarded by every active `with` object.
1166    ///
1167    /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
1168    /// the read itself; the outer guards and the plain access are what the `if_false`
1169    /// jumps to, so the innermost object wins.
1170    fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
1171        let names = self.cur().with_names.clone();
1172        let done = self.new_label();
1173        let mut starts = Vec::new();
1174        // Innermost object first: the last `with` opened is the one that shadows the
1175        // others, so its guard has to be the first chance to satisfy the name.
1176        for with_name in names.iter().rev() {
1177            let next = self.new_label();
1178            // `in` takes the key then the object.
1179            self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1180            self.emit_var(VarAction::Get, with_name);
1181            self.emit(Opcode::In, &[]);
1182            self.emit_jump(Opcode::IfFalse, next, &[]);
1183            starts.push(next);
1184            match action {
1185                // A store keeps the value under the receiver, which is where
1186                // `put_field` expects it.
1187                VarAction::Put | VarAction::PutInit => {
1188                    self.emit_var(VarAction::Get, with_name);
1189                    self.emit(Opcode::Swap, &[]);
1190                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(name))]);
1191                }
1192                _ => {
1193                    self.emit_var(VarAction::Get, with_name);
1194                    self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1195                    self.emit(Opcode::GetArrayEl, &[]);
1196                }
1197            }
1198            self.emit_jump(Opcode::Goto, done, &[]);
1199            self.place_label(next);
1200        }
1201        self.emit_var(action, name);
1202        self.place_label(done);
1203    }
1204
1205    fn emit_var(&mut self, action: VarAction, name: &str) {
1206        // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
1207        // stores and keeps the value in one instruction. The reference does this
1208        // in a post-pass; folding it at emit time keeps instruction indices
1209        // stable, which matters because labels are recorded as indices.
1210        //
1211        // Only slots have a `set_` form: a global is stored with `put_var` and
1212        // read with `get_var`, and the reference does not fold those.
1213        //
1214        // A label between the two cancels the fold. `set_x v` leaves the value on
1215        // the stack, which is only equivalent when the read immediately follows the
1216        // store; when a jump target sits in between, the store must *consume* the
1217        // value and the read must fetch it afresh. A loop head is exactly that
1218        // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
1219        // condition re-reads it — and folding across the label would make the
1220        // condition compare whatever the previous iteration left on the stack.
1221        if action == VarAction::Get {
1222            let is_slot = self.is_slot(name);
1223            let at_label = std::mem::take(&mut self.state().label_since_insn);
1224            //
1225            // `arguments` is excluded because the reference treats it as a special
1226            // binding: it is initialised once and read many times, and folding its
1227            // initialisation into a `set_` would leave the object on the stack where
1228            // the reference leaves nothing.
1229            if is_slot
1230                && name != "arguments"
1231                && !at_label
1232                && let Some(Insn::Var {
1233                    action: previous,
1234                    name: previous_name,
1235                    ..
1236                }) = self.state().insns.last_mut()
1237                && *previous == VarAction::Put
1238                && previous_name == name
1239            {
1240                *previous = VarAction::Set;
1241                return;
1242            }
1243        }
1244        // Inside a `with`, every name lookup consults the with objects first. The
1245        // hidden `<with…>` locals themselves are exempt, or the guard would recurse.
1246        let guarded = !self.cur().with_names.is_empty()
1247            && !self.cur().with_names.iter().any(|hidden| hidden == name)
1248            && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1249            && !self.state().emitting_with_guard;
1250        if guarded {
1251            self.state().emitting_with_guard = true;
1252            self.emit_with_guarded(action, name);
1253            self.state().emitting_with_guard = false;
1254            return;
1255        }
1256        let block = self.cur().current_block;
1257        self.state().label_since_insn = false;
1258        let pos = self.cur().cur_pos;
1259        let in_params = self.cur().in_params;
1260        self.state().insns.push(Insn::Var {
1261            action,
1262            name: name.to_string(),
1263            block,
1264            in_params,
1265        });
1266        self.state().insn_pos.push(pos);
1267    }
1268
1269    fn new_label(&mut self) -> Label {
1270        let state = self.state();
1271        state.labels.push(None);
1272        Label(state.labels.len() as u32 - 1)
1273    }
1274
1275    fn place_label(&mut self, label: Label) {
1276        let index = self.cur().insns.len();
1277        self.state().label_since_insn = true;
1278        self.state().labels[label.0 as usize] = Some(index);
1279    }
1280
1281    fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1282        let mut operands = vec![Op::Label(label)];
1283        operands.extend_from_slice(extra);
1284        self.emit(op, &operands);
1285    }
1286
1287    // -- scopes ------------------------------------------------------------
1288
1289    /// Start a new lexical scope inside `parent`.
1290    fn push_block(&mut self, key: u64, parent: u64) {
1291        let state = self.state();
1292        if !state.blocks.iter().any(|b| b.key == key) {
1293            state.blocks.push(Block { key, parent });
1294        }
1295        state.current_block = key;
1296    }
1297
1298    /// Emit the code that runs when a lexical scope is entered.
1299    ///
1300    /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1301    /// so entering its block marks it uninitialised. Hoisted function
1302    /// declarations are created here instead, which is why a call before the
1303    /// declaration still works.
1304    ///
1305    /// The order is not obvious: bindings are emitted in *reverse* declaration
1306    /// order, because the reference walks its scope chain, which is built by
1307    /// prepending.
1308    fn emit_scope_enter(&mut self, block: u64) {
1309        // Only *this* scope's hoisted declarations are consumed here; the rest stay in the
1310        // list for the scope that owns them. `std::mem::take` used to empty the whole list,
1311        // so entering an outer scope threw away every nested block's function
1312        // declarations: `function h(){ { function k(){} } return k; }` answered
1313        // `undefined`, and `{ function g(){} }` was `undefined` even *inside* the block.
1314        // That is one Annex B rule the engine otherwise implements (a sloppy-mode function
1315        // in a block is also a `var` of the enclosing function), and it is what makes the
1316        // `for (const ctor of ctors) { function f(){} … }` shape in test262 work.
1317        let mut hoisted = std::mem::take(&mut self.state().hoisted);
1318        let mut rest = Vec::with_capacity(hoisted.len());
1319        let mut mine: Vec<(HoistTarget, u32)> = Vec::new();
1320        for (owner, target, pool_index) in hoisted.drain(..) {
1321            if owner == block {
1322                mine.push((target, pool_index));
1323            } else {
1324                rest.push((owner, target, pool_index));
1325            }
1326        }
1327        self.state().hoisted = rest;
1328        mine.sort_by_key(|(target, _)| match target {
1329            HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1330            HoistTarget::Global(_) => u32::MAX,
1331        });
1332        for (target, pool_index) in mine {
1333            self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1334            match target {
1335                HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1336                HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1337                HoistTarget::Global(name) => {
1338                    // A global binding lives in a reference cell, so the store
1339                    // goes through `put_var_ref` while reads use `get_var`.
1340                    let block = self.cur().current_block;
1341                    let pos = self.cur().cur_pos;
1342                    let in_params = self.cur().in_params;
1343                    self.state().insns.push(Insn::Var {
1344                        action: VarAction::PutRef,
1345                        name,
1346                        block,
1347                        in_params,
1348                    });
1349                    self.state().insn_pos.push(pos);
1350                }
1351            }
1352        }
1353        for index in self.block_vars_reversed(block) {
1354            self.emit(
1355                Opcode::SetLocUninitialized,
1356                &[Op::Slot(Slot::Loc(index as u32))],
1357            );
1358        }
1359    }
1360
1361    /// Emit the code that runs when a lexical scope is exited.
1362    ///
1363    /// A captured binding has to be closed: detaching its reference cell freezes
1364    /// the value the binding had when the block ended, which is what a closure
1365    /// created inside the block must keep seeing.
1366    fn emit_scope_leave(&mut self, block: u64) {
1367        for index in self.block_vars_reversed(block) {
1368            if self.cur().vars[index].is_captured {
1369                self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1370            }
1371        }
1372    }
1373
1374    /// Locals declared in `block`, in reverse declaration order.
1375    fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1376        let state = self.cur();
1377        let mut out: Vec<usize> = (0..state.vars.len())
1378            .filter(|index| {
1379                state.var_block.get(*index).copied() == Some(block)
1380                    && state.vars[*index].is_lexical
1381                    // A derived constructor's `this` is lexical but is not initialised by
1382                    // entering the scope: `check_ctor` proves it, so its dead-zone marker
1383                    // was emitted with the constructor's own prologue.
1384                    && state.vars[*index].name != "this"
1385            })
1386            .collect();
1387        out.reverse();
1388        out
1389    }
1390
1391    /// Declare a local, even at the top level of a script.
1392    ///
1393    /// A `catch` parameter is always a local: the reference puts it in the
1394    /// function's own variable list (`1: catch e`), never in the global object,
1395    /// because it only exists while the handler runs.
1396    fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1397        let state = self.state();
1398        let index = state.vars.len() as u32;
1399        // A `catch` parameter belongs to a scope even though it is not lexical: the
1400        // runtime instantiates it per handler entry, but it never sits in the
1401        // temporal dead zone.
1402        let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1403            state.current_block
1404        } else {
1405            0
1406        };
1407        state.var_block.push(block);
1408        state.vars.push(def);
1409        index
1410    }
1411
1412    fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1413        if self.cur().is_module
1414            && self.cur().current_block == self.cur().body_block
1415            && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1416        {
1417            // Only the body's own block: a `let` inside a module-level `{}` is still an
1418            // ordinary local of that block, not a module variable.
1419            //
1420            // A `using` binding is excluded on purpose, and the reference excludes it in
1421            // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1422            // "'using' variables are currently not exported in modules"): a module-level
1423            // `using` is an ordinary *local* of the module body function, not a module
1424            // cell. Two things follow, and both are what the reference does — `export {a}`
1425            // of a `using` binding is "exported variable 'a' does not exist", and
1426            // disposal works, because the disposal epilogue addresses locals by slot.
1427            //
1428            // The hidden dispose-method variable is excluded for a stronger reason: it is
1429            // *always* a local (`add_scope_var` in the reference), and it must sit
1430            // immediately after its value so `using_dispose` can find it at `slot + 1`.
1431            return self.declare_module(name, &def);
1432        }
1433        if self.cur().declares_globally(&def) {
1434            self.declare_global(name, &def);
1435            return 0;
1436        }
1437        let state = self.state();
1438        let index = state.vars.len() as u32;
1439        let block = if def.is_lexical {
1440            state.current_block
1441        } else {
1442            0
1443        };
1444        state.var_block.push(block);
1445        state.vars.push(def);
1446        index
1447    }
1448
1449    /// Declare a `using` binding and its cached dispose method, returning both slots.
1450    ///
1451    /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1452    /// `(value, value + 1)` — the reference does the same and documents the constraint.
1453    fn declare_using(&mut self, name: &str) -> (u32, u32) {
1454        let mut def = VarDef::lexical(name);
1455        def.kind = VarKind::Using;
1456        let value = self.declare(name, def);
1457        let mut method = VarDef::lexical(using_method_name(name));
1458        method.kind = VarKind::UsingMethod;
1459        let method_slot = self.declare(&using_method_name(name), method);
1460        (value, method_slot)
1461    }
1462
1463    /// The slot a `using` binding's dispose method lives in.
1464    fn using_method_slot(&self, name: &str) -> Option<u32> {
1465        let hidden = using_method_name(name);
1466        self.cur()
1467            .vars
1468            .iter()
1469            .position(|var| var.name == hidden)
1470            .map(|index| index as u32)
1471    }
1472
1473    // -- statements --------------------------------------------------------
1474
1475    fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1476        self.stmt_labelled(stmt, &[])
1477    }
1478
1479    /// Compile a statement that a chain of labels names.
1480    ///
1481    /// Only a loop consumes `labels`; every other statement ignores them (the
1482    /// parser has already rejected a label on a statement that cannot use it).
1483    fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1484        // Only a *top-level* expression statement supplies the program's value.
1485        let saved = self.cur().leaves_value;
1486        self.state().leaves_value =
1487            matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1488        self.state().stmt_depth += 1;
1489        let result = self.stmt_inner(stmt, labels);
1490        self.state().stmt_depth -= 1;
1491        // A nested statement never contributes the program's value, so the flag
1492        // the wrapper set above is what survives.
1493        let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1494        self.state().leaves_value = produced;
1495        let _ = saved;
1496        result
1497    }
1498
1499    fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1500        match &stmt.kind {
1501            StmtKind::Empty | StmtKind::Debugger => {}
1502            StmtKind::Expr(expr) => {
1503                // The statement's first token is a position the reference records: an
1504                // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1505                // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1506                // is why an error from a construct with no position of its own (`[...it]`
1507                // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1508                let saved = self.cur().cur_pos;
1509                self.state().cur_pos = Some(expr.span.start);
1510                // An expression statement's value is thrown away — except in a
1511                // script, where it becomes the program's result. `assign` reads this
1512                // and clears it, so a nested assignment still produces a value.
1513                self.state().discard_value = !self.cur().is_script;
1514                let result = self.expr(expr);
1515                self.state().discard_value = false;
1516                result?;
1517                if std::mem::take(&mut self.state().no_value) {
1518                    // A store whose value was discarded left nothing to drop.
1519                } else if self.cur().is_script {
1520                    // The program's value lands in the hidden `<ret>` local.
1521                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1522                } else {
1523                    self.emit(Opcode::Drop, &[]);
1524                }
1525                // Restored last: the trailing `drop` is part of the statement, and in the
1526                // reference it simply inherits whatever the expression last recorded.
1527                self.state().cur_pos = saved;
1528            }
1529            StmtKind::Block(body) => {
1530                // The block's declarations were hoisted with its enclosing
1531                // statement list, so there is nothing left to declare here.
1532                let key = stmt.span.start.offset as u64;
1533                let parent = self.cur().current_block;
1534                self.push_block(key, parent);
1535                self.emit_scope_enter(key);
1536                // A block is where a `using` region lives, so its statements have to go
1537                // through `stmts`: that is what emits the disposal epilogue.
1538                self.stmts(body)?;
1539                self.emit_scope_leave(key);
1540                self.state().current_block = parent;
1541            }
1542            StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1543            // A function declaration was already instantiated when its scope was
1544            // entered, so the statement itself emits nothing.
1545            StmtKind::FuncDecl(_) => {}
1546            StmtKind::If { test, cons, alt } => {
1547                self.reset_value();
1548                let else_label = self.new_label();
1549                let end_label = self.new_label();
1550                self.expr(test)?;
1551                self.emit_jump(Opcode::IfFalse, else_label, &[]);
1552                self.stmt(cons)?;
1553                if alt.is_some() {
1554                    self.emit_jump(Opcode::Goto, end_label, &[]);
1555                }
1556                self.place_label(else_label);
1557                if let Some(alt) = alt {
1558                    self.stmt(alt)?;
1559                    self.place_label(end_label);
1560                }
1561            }
1562            StmtKind::While { test, body } => {
1563                self.reset_value();
1564                let top = self.new_label();
1565                let end = self.new_label();
1566                self.place_label(top);
1567                self.expr(test)?;
1568                // The condition's false branch and `break` share one target,
1569                // which is why a `while` loop needs only one end label.
1570                self.emit_jump(Opcode::IfFalse, end, &[]);
1571                self.loop_body(body, labels, top, end)?;
1572                self.emit_jump(Opcode::Goto, top, &[]);
1573                self.place_label(end);
1574            }
1575            StmtKind::DoWhile { body, test } => {
1576                self.reset_value();
1577                let top = self.new_label();
1578                let cont = self.new_label();
1579                let end = self.new_label();
1580                self.place_label(top);
1581                // `continue` in a `do…while` runs the test, so it lands on `cont`
1582                // rather than on the loop head.
1583                self.loop_body(body, labels, cont, end)?;
1584                self.place_label(cont);
1585                self.expr(test)?;
1586                self.emit_jump(Opcode::IfTrue, top, &[]);
1587                self.place_label(end);
1588            }
1589            StmtKind::For {
1590                init,
1591                test,
1592                update,
1593                body,
1594            } => {
1595                self.reset_value();
1596                let for_key = stmt.span.start.offset as u64;
1597                let for_parent = self.cur().current_block;
1598                self.push_block(for_key, for_parent);
1599                self.emit_scope_enter(for_key);
1600                if let Some(init) = init {
1601                    match init {
1602                        ForInit::VarDecl(decl) => {
1603                            self.var_decl(decl)?;
1604                        }
1605                        ForInit::Expr(expr) => {
1606                            // The head's value is discarded. Saying so lets an
1607                            // assignment store with `put` instead of `dup`+`put`, which
1608                            // is what the reference emits — and the difference matters:
1609                            // a `dup`/`drop` pair around the store gives the peephole a
1610                            // chance to fold the store into the *condition's* read.
1611                            self.state().discard_value = true;
1612                            let result = self.expr(expr);
1613                            self.state().discard_value = false;
1614                            result?;
1615                            if !std::mem::take(&mut self.state().no_value) {
1616                                self.emit(Opcode::Drop, &[]);
1617                            }
1618                        }
1619                    }
1620                }
1621                // A `let`/`const` in the head gets a *fresh binding per iteration*,
1622                // so a closure made in the body captures that iteration's value
1623                // instead of sharing one. The reference expresses this with
1624                // `close_loc`, which swaps in a new reference cell holding the
1625                // current value; the three points below are the ones it uses — after
1626                // the initialiser, before the update, and after the loop.
1627                let loop_bindings = match init {
1628                    Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
1629                        let mut names: Vec<String> = Vec::new();
1630                        for declarator in &decl.declarators {
1631                            let mut idents = Vec::new();
1632                            declarator.target.bound_names(&mut idents);
1633                            names.extend(idents.into_iter().map(|ident| ident.name));
1634                        }
1635                        names
1636                    }
1637                    _ => Vec::new(),
1638                };
1639                // The reference also closes right after the initialiser, so the first
1640                // iteration's closures get their own cell rather than sharing the one
1641                // the initialiser wrote into.
1642                for name in &loop_bindings {
1643                    let pos = self.cur().cur_pos;
1644                    self.state().insns.push(Insn::CloseCaptured {
1645                        name: name.clone(),
1646                        block: for_key,
1647                    });
1648                    self.state().insn_pos.push(pos);
1649                }
1650                let top = self.new_label();
1651                let cont = self.new_label();
1652                let end = self.new_label();
1653                self.place_label(top);
1654                if let Some(test) = test {
1655                    self.expr(test)?;
1656                    self.emit_jump(Opcode::IfFalse, end, &[]);
1657                }
1658                // `continue` runs the update expression first, so it lands on
1659                // `cont`, which sits just before the update.
1660                self.loop_body(body, labels, cont, end)?;
1661                self.place_label(cont);
1662                // Each iteration ends with a fresh cell, so the closures the body just
1663                // created keep the cell they captured and the update writes to a new
1664                // one. Without this every closure in the loop shares one binding.
1665                let binding_block = for_key;
1666                for name in &loop_bindings {
1667                    let pos = self.cur().cur_pos;
1668                    self.state().insns.push(Insn::CloseCaptured {
1669                        name: name.clone(),
1670                        block: binding_block,
1671                    });
1672                    self.state().insn_pos.push(pos);
1673                }
1674                if let Some(update) = update {
1675                    self.state().discard_value = true;
1676                    let result = self.expr(update);
1677                    self.state().discard_value = false;
1678                    result?;
1679                    if !std::mem::take(&mut self.state().no_value) {
1680                        self.emit(Opcode::Drop, &[]);
1681                    }
1682                }
1683                self.emit_jump(Opcode::Goto, top, &[]);
1684                self.place_label(end);
1685                self.emit_scope_leave(for_key);
1686                self.state().current_block = for_parent;
1687            }
1688            StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1689            StmtKind::Throw(expr) => {
1690                self.expr(expr)?;
1691                self.emit(Opcode::Throw, &[]);
1692            }
1693            StmtKind::Break(_) | StmtKind::Continue(_) => {
1694                // Labels and loops are wired up in a later milestone; a bare
1695                // break/continue jumps to the innermost enclosing target, which
1696                // the loop helpers register.
1697                self.control_transfer(stmt)?;
1698            }
1699            StmtKind::Labeled { label, body } => {
1700                self.labeled(label, body, stmt)?;
1701            }
1702            StmtKind::Switch {
1703                discriminant,
1704                cases,
1705            } => {
1706                self.switch(discriminant, cases, stmt)?;
1707            }
1708            StmtKind::Try {
1709                block,
1710                handler,
1711                finalizer,
1712            } => {
1713                self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
1714            }
1715            StmtKind::ForIn { left, right, body } => {
1716                self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
1717            }
1718            StmtKind::ForOf {
1719                left,
1720                right,
1721                body,
1722                is_await,
1723            } => {
1724                let kind = if *is_await {
1725                    ForLoopKind::AwaitOf
1726                } else {
1727                    ForLoopKind::Of
1728                };
1729                self.for_in_of(stmt, left, right, body, kind, labels)?;
1730            }
1731            StmtKind::With { object, body } => self.with_stmt(object, body)?,
1732            StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
1733            // `import` emits nothing: hoisting already bound its names, and the host
1734            // fills their cells before the body runs.
1735            StmtKind::Import(_) => {}
1736            StmtKind::Export(decl) => self.export_stmt(decl)?,
1737        }
1738        Ok(())
1739    }
1740
1741    /// Compile `return`, running every enclosing finalizer on the way out.
1742    ///
1743    /// `nip_catch` is what makes this possible: it discards everything on the stack
1744    /// down to and including the `catch` offset while keeping the return value on
1745    /// top, so the frame the finalizer sees has the same shape as on the normal
1746    /// path.
1747    fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
1748        let mut has_value = value.is_some();
1749        if let Some(expr) = value {
1750            // `return f(x)` is a tail call *only* when nothing has to happen to the
1751            // value afterwards. A `finally` or an open iterator in scope forces the
1752            // normal path, because the cleanup has to run after the call returns —
1753            // which is exactly what a tail call refuses to do.
1754            let plain = self
1755                .cur()
1756                .jump_targets
1757                .iter()
1758                .all(|target| target.finally_label.is_none() && !target.has_iterator);
1759            if plain && self.expr_if_tail_call(expr)? {
1760                return Ok(());
1761            }
1762            self.expr(expr)?;
1763        }
1764        // `return v` in an *async generator* awaits `v` before anything else happens —
1765        // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
1766        // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
1767        // exactly that reason ("the await must be done before handling the finally in case
1768        // it raises an exception").
1769        if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
1770            self.emit(Opcode::Await, &[]);
1771            self.state().has_await = true;
1772        }
1773        has_value = self.emit_unwind_for_return(has_value);
1774        // A generator or async function does not return to its caller: it either
1775        // finishes, and the value becomes `{value, done: true}`, or it suspends.
1776        // `return_async` is the "finished" half, and it reads the value off the stack
1777        // rather than carrying it, which is what the resume machinery expects.
1778        if self.cur().is_suspending() {
1779            if !has_value {
1780                self.emit(Opcode::Undefined, &[]);
1781            }
1782            self.emit(Opcode::ReturnAsync, &[]);
1783            return Ok(());
1784        }
1785        if has_value {
1786            self.emit(Opcode::Return, &[]);
1787        } else {
1788            self.emit(Opcode::ReturnUndef, &[]);
1789        }
1790        Ok(())
1791    }
1792
1793    /// Close an iterator: the reference's `emit_iterator_close`.
1794    ///
1795    /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
1796    /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
1797    /// sequence, and three details in it are load-bearing:
1798    ///
1799    /// * the iterator object is compared against `undefined` first, because a loop that
1800    ///   ran to completion clears that slot rather than closing an exhausted iterator;
1801    /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
1802    /// * `preserve_completion` keeps whatever was underneath (the return value of the
1803    ///   function being left), which is why one branch ends on `nip` and the other on `drop`.
1804    fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
1805        if !is_async {
1806            if preserve_completion {
1807                self.emit(Opcode::Rot3r, &[]);
1808                self.emit(Opcode::Undefined, &[]);
1809            }
1810            self.emit(Opcode::IteratorClose, &[]);
1811            return;
1812        }
1813        if preserve_completion {
1814            // `iter next completion -> completion iter`
1815            self.emit(Opcode::Nip, &[]);
1816            self.emit(Opcode::Swap, &[]);
1817        } else {
1818            // `iter next catch_offset -> iter`
1819            self.emit(Opcode::Drop, &[]);
1820            self.emit(Opcode::Drop, &[]);
1821        }
1822        let done = self.new_label();
1823        let no_return = self.new_label();
1824        self.emit(Opcode::Dup, &[]);
1825        self.emit(Opcode::IsUndefined, &[]);
1826        self.emit_jump(Opcode::IfTrue, done, &[]);
1827        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
1828        self.emit(Opcode::Dup, &[]);
1829        self.emit(Opcode::IsUndefinedOrNull, &[]);
1830        self.emit_jump(Opcode::IfTrue, no_return, &[]);
1831        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
1832        self.emit(Opcode::Await, &[]);
1833        self.state().has_await = true;
1834        self.emit_jump(Opcode::Goto, done, &[]);
1835        self.place_label(no_return);
1836        self.emit(Opcode::Drop, &[]);
1837        self.place_label(done);
1838        self.emit(Opcode::Drop, &[]);
1839    }
1840
1841    /// Emit the finalizer/iterator cleanup for leaving the current position with a
1842    /// return, and report whether a value is now on the stack for it to carry.
1843    ///
1844    /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
1845    /// enclosing `finally` at once, and the two used to be separate — the `yield` path
1846    /// simply emitted `return_async`, so `it.return()` ended the generator without ever
1847    /// running `finally` blocks the body was sitting inside.
1848    fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
1849        let targets = self.cur().jump_targets.clone();
1850        for target in targets.iter().rev() {
1851            if target.finally_label.is_none() && !target.has_iterator {
1852                continue;
1853            }
1854            if !has_value {
1855                // The cleanup expects a value to pass through; with nothing to
1856                // return, `undefined` stands in.
1857                self.emit(Opcode::Undefined, &[]);
1858                has_value = true;
1859            }
1860            self.emit(Opcode::NipCatch, &[]);
1861            if target.has_iterator {
1862                // Rewind to the loop's own slots and hand the close a dummy catch offset:
1863                // the loop is being abandoned, so there is nothing left to catch.
1864                self.emit_iterator_close(target.is_async_iterator, true);
1865            } else if let Some(finally) = target.finally_label {
1866                self.emit_jump(Opcode::Gosub, finally, &[]);
1867            }
1868        }
1869        has_value
1870    }
1871
1872    /// Compile a statement list, stopping at the first statement that cannot
1873    /// fall through.
1874    fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
1875        for (index, stmt) in body.iter().enumerate() {
1876            // A `using` declaration is not just a binding: everything after it, to the end
1877            // of the list, runs inside its disposal region. Compiling the rest of the list
1878            // recursively is what gives nested regions their innermost-first order.
1879            if Self::using_declaration(stmt).is_some() {
1880                return self.using_region(stmt, &body[index + 1..]);
1881            }
1882            self.stmt(stmt)?;
1883            if Self::terminates(stmt) {
1884                break;
1885            }
1886        }
1887        Ok(())
1888    }
1889
1890    /// The declaration a `using` statement carries, if it is one.
1891    fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
1892        match &stmt.kind {
1893            StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
1894            _ => None,
1895        }
1896    }
1897
1898    /// Compile `decl` and then the rest of its block, disposing when the block ends.
1899    ///
1900    /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
1901    /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
1902    /// exception — and this engine already funnels all of those through `catch` plus
1903    /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
1904    /// `return` and `break` dispose without knowing anything about `using`.
1905    ///
1906    /// ```text
1907    ///   <declaration>              value -> x, method -> x+1
1908    ///   catch CATCH                <- an exception in the rest lands here
1909    /// REST:
1910    ///   <the rest of the block>
1911    ///   drop                       <- the catch offset, on the fall-through path
1912    ///   undefined; gosub DISPOSE; drop
1913    ///   goto END
1914    /// CATCH:
1915    ///   using_dispose x            <- merges the failure into the pending exception
1916    ///   throw
1917    /// DISPOSE:
1918    ///   using_dispose_init
1919    ///   using_dispose x
1920    ///   using_dispose_end          <- rethrows if a dispose failed
1921    ///   ret
1922    /// END:
1923    /// ```
1924    fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
1925        let Some(decl) = Self::using_declaration(stmt) else {
1926            unreachable!("using_region is only called for a using declaration");
1927        };
1928        // `using` binds exactly one name and has no pattern form, which the parser
1929        // enforces; the region still has to know *which* slot to dispose.
1930        let name = decl
1931            .declarators
1932            .first()
1933            .and_then(|declarator| match &declarator.target.kind {
1934                PatternKind::Ident(ident) => Some(ident.name.clone()),
1935                _ => None,
1936            });
1937        self.stmt(stmt)?;
1938        let Some(name) = name else {
1939            // Unreachable for a well-formed `using`, but a bare `using` with no declarator
1940            // must not make the compiler panic.
1941            return self.stmts(rest);
1942        };
1943        let Some(value_slot) = self.using_value_slot(&name) else {
1944            // Declared globally, which the parser rules out for a script; a module's
1945            // top level is a scope, and there the disposal stays a known gap.
1946            return self.stmts(rest);
1947        };
1948        // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
1949        // exit path already disposed.
1950        let live = !rest.last().is_some_and(Self::terminates);
1951        self.using_region_around(value_slot, live, |compiler| compiler.stmts(rest))
1952    }
1953
1954    /// The slot a `using` binding's value lives in.
1955    fn using_value_slot(&self, name: &str) -> Option<u32> {
1956        self.cur()
1957            .vars
1958            .iter()
1959            .position(|var| var.name == name && var.kind == VarKind::Using)
1960            .map(|index| index as u32)
1961    }
1962
1963    /// Wrap `inside` in a disposal region for the resource in `value_slot`.
1964    ///
1965    /// Shared between a `using` statement — which owns the rest of its block — and a
1966    /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
1967    /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
1968    /// the end, `return`, `break`, `continue`, and an exception — and this engine already
1969    /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
1970    /// target with a `finally_label` is what makes `return` and `break` dispose without
1971    /// knowing anything about `using`.
1972    ///
1973    /// ```text
1974    ///   catch CATCH                <- an exception inside lands here
1975    ///   <inside>
1976    ///   drop                       <- the catch offset, on the fall-through path
1977    ///   undefined; gosub DISPOSE; drop
1978    ///   goto END
1979    /// CATCH:
1980    ///   using_dispose slot         <- merges the failure into the pending exception
1981    ///   throw
1982    /// DISPOSE:
1983    ///   using_dispose_init
1984    ///   using_dispose slot
1985    ///   using_dispose_end          <- rethrows if a dispose failed
1986    ///   ret
1987    /// END:
1988    /// ```
1989    fn using_region_around(
1990        &mut self,
1991        value_slot: u32,
1992        live: bool,
1993        inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
1994    ) -> Result<(), SyntaxError> {
1995        let catch_label = self.new_label();
1996        let end_label = self.new_label();
1997        let dispose_label = self.new_label();
1998
1999        self.emit_jump(Opcode::Catch, catch_label, &[]);
2000        self.push_jump_target(JumpTarget {
2001            names: Vec::new(),
2002            break_label: None,
2003            continue_label: None,
2004            // The catch offset is the one thing on the stack that leaving has to remove.
2005            drop_count: 1,
2006            finally_label: Some(dispose_label),
2007            is_regular_stmt: false,
2008            has_iterator: false,
2009            is_async_iterator: false,
2010        });
2011        inside(self)?;
2012        self.pop_jump_target();
2013
2014        if live {
2015            self.emit(Opcode::Drop, &[]);
2016            self.emit(Opcode::Undefined, &[]);
2017            self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2018            self.emit(Opcode::Drop, &[]);
2019            self.emit_jump(Opcode::Goto, end_label, &[]);
2020        }
2021
2022        // An exception unwinds to here with the thrown value on the stack, which is exactly
2023        // the shape `using_dispose` expects as its error state.
2024        self.place_label(catch_label);
2025        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2026        self.emit(Opcode::Throw, &[]);
2027
2028        self.place_label(dispose_label);
2029        // Inside the subroutine the return value and the `gosub` return address are both
2030        // live, and neither an outer finalizer nor another region may run before this one
2031        // has finished.
2032        self.push_jump_target(JumpTarget {
2033            names: Vec::new(),
2034            break_label: None,
2035            continue_label: None,
2036            drop_count: 2,
2037            finally_label: None,
2038            is_regular_stmt: false,
2039            has_iterator: false,
2040            is_async_iterator: false,
2041        });
2042        self.emit(Opcode::UsingDisposeInit, &[]);
2043        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2044        self.emit(Opcode::UsingDisposeEnd, &[]);
2045        self.pop_jump_target();
2046        self.emit(Opcode::Ret, &[]);
2047        self.place_label(end_label);
2048        Ok(())
2049    }
2050
2051    /// Declare every name a statement list introduces, before compiling any of
2052    /// it, so a reference that appears textually before a declaration still
2053    /// resolves.
2054    ///
2055    /// Declarations are walked in source order because that is the order the
2056    /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2057    /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2058    /// declarations hoist out to the function scope; lexical names belong to the
2059    /// block they were written in, which `block` records.
2060    fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2061        let saved = self.cur().current_block;
2062        self.state().current_block = block;
2063        let result = self.hoist_list(body);
2064        // Only now is every binding of this scope known, so the deferred function
2065        // bodies can be compiled against the finished list. Compiled at its own
2066        // declaration instead, a body that names a `var` written further down would
2067        // have resolved that name as a global.
2068        if result.is_ok() {
2069            let deferred = std::mem::take(&mut self.state().deferred_funcs);
2070            let mut outcome = Ok(());
2071            for (owner, func) in deferred {
2072                let previous = self.cur().current_block;
2073                self.state().current_block = owner;
2074                outcome = self.func_decl(&func);
2075                self.state().current_block = previous;
2076                if outcome.is_err() {
2077                    break;
2078                }
2079            }
2080            self.state().current_block = saved;
2081            return outcome;
2082        }
2083        // `current_block` is restored by the caller for a block statement, since
2084        // it needs it set while compiling; only clean up on the hoist path.
2085        self.state().current_block = saved;
2086        result
2087    }
2088
2089    fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2090        for stmt in body {
2091            self.hoist_stmt(stmt)?;
2092        }
2093        Ok(())
2094    }
2095
2096    /// Whether a statement always transfers control away, making everything after
2097    /// it in the same list unreachable.
2098    ///
2099    /// The reference drops such statements in `skip_dead_code`, so `return 1;
2100    /// let x = 2;` compiles to the same bytecode as `return 1;`.
2101    fn terminates(stmt: &Stmt) -> bool {
2102        matches!(
2103            stmt.kind,
2104            StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2105        )
2106    }
2107
2108    fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2109        match &stmt.kind {
2110            StmtKind::VarDecl(decl) => {
2111                for declarator in &decl.declarators {
2112                    let mut names = Vec::new();
2113                    declarator.target.bound_names(&mut names);
2114                    for name in names {
2115                        let text = name.name.clone();
2116                        if decl.kind == VarDeclKind::Var {
2117                            let def = VarDef::var(text.clone());
2118                            self.declare_var(&text, def);
2119                        } else if decl.kind.is_using() {
2120                            // Two adjacent slots: the resource, then the dispose method
2121                            // snapshotted at declaration. `using_dispose` reads them as a
2122                            // pair `(slot, slot + 1)`, so nothing may be declared between
2123                            // them — which is why both are declared here, in one step,
2124                            // rather than the method being added at emission time.
2125                            self.declare_using(&text);
2126                        } else {
2127                            let def = if decl.kind == VarDeclKind::Const {
2128                                VarDef::constant(text.clone())
2129                            } else {
2130                                VarDef::lexical(text.clone())
2131                            };
2132                            self.declare(&text, def);
2133                        }
2134                    }
2135                }
2136            }
2137            StmtKind::FuncDecl(func) => {
2138                if let Some(name) = &func.name {
2139                    // A function declaration is a `var` binding that happens to
2140                    // hold a function, not a lexical one.
2141                    let def = VarDef::var(name.name.clone());
2142                    self.declare_var(&name.name.clone(), def);
2143                }
2144                // The function object is created when the scope is entered, so it
2145                // exists before the declaration is reached. Its body is compiled
2146                // *after* this scope's hoisting finishes, so a name it uses resolves
2147                // even when the `var` that declares it comes later in the source.
2148                let owner = self.cur().current_block;
2149                self.state().deferred_funcs.push((owner, func.clone()));
2150            }
2151            StmtKind::ClassDecl(class) => {
2152                if let Some(name) = &class.name {
2153                    self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2154                }
2155            }
2156            // A module's imports are bound before any of its code runs, and its exports
2157            // declare the very bindings they export — so both hoist the declarations
2158            // their `StmtKind` arm will later emit code for.
2159            StmtKind::Import(decl) => self.hoist_import(decl)?,
2160            StmtKind::Export(decl) => self.hoist_export(decl)?,
2161            StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2162            StmtKind::If { cons, alt, .. } => {
2163                self.hoist_stmt(cons)?;
2164                if let Some(alt) = alt {
2165                    self.hoist_stmt(alt)?;
2166                }
2167            }
2168            StmtKind::While { body, .. }
2169            | StmtKind::DoWhile { body, .. }
2170            | StmtKind::Labeled { body, .. }
2171            | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2172            StmtKind::For { init, body, .. } => {
2173                // A `for` head gets its own scope even when it declares nothing,
2174                // because `let` in the head is scoped to the loop.
2175                let key = stmt.span.start.offset as u64;
2176                let parent = self.cur().current_block;
2177                self.push_block(key, parent);
2178                if let Some(init) = init
2179                    && let ForInit::VarDecl(decl) = init
2180                {
2181                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2182                }
2183                self.hoist_stmt(body)?;
2184                self.state().current_block = parent;
2185            }
2186            StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
2187                let key = stmt.span.start.offset as u64;
2188                let parent = self.cur().current_block;
2189                self.push_block(key, parent);
2190                if let ForHead::VarDecl(decl) = left {
2191                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2192                }
2193                self.hoist_stmt(body)?;
2194                self.state().current_block = parent;
2195            }
2196            StmtKind::Try {
2197                block,
2198                handler,
2199                finalizer,
2200            } => {
2201                self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2202                let try_parent = self.cur().current_block;
2203                if let Some(handler) = handler {
2204                    // The catch parameter belongs to the function scope, not to a
2205                    // block: it is a `catch` binding rather than a `let`, so it is
2206                    // never in the temporal dead zone and `emit_scope_enter` must
2207                    // not mark it uninitialised. It still has to be declared before
2208                    // the handler body is hoisted, so it takes the slot the
2209                    // reference gives it (bindings are numbered in source order).
2210                    if let Some(pattern) = &handler.param {
2211                        // The parameter gets its own scope, so entering the handler
2212                        // does not have to re-declare it. It is not lexical, so it
2213                        // is never marked uninitialised.
2214                        let key = Self::try_block_key(stmt, TryPart::Param);
2215                        let parent = self.cur().current_block;
2216                        self.push_block(key, parent);
2217                        // A destructuring parameter binds several names, one slot each,
2218                        // in the order they are written. The reference declares those as
2219                        // `let`s rather than as one `catch` binding — its dump prints
2220                        // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2221                        // so the kind follows the shape of the parameter.
2222                        //
2223                        // Neither form is in the dead zone: the stores run as the handler
2224                        // is entered, so both use the unchecked `put_loc`.
2225                        let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2226                        let mut names = Vec::new();
2227                        pattern.bound_names(&mut names);
2228                        for name in names {
2229                            let def = VarDef {
2230                                name: name.name.clone(),
2231                                is_const: false,
2232                                is_lexical: destructures,
2233                                kind: if destructures {
2234                                    crate::bytecode::VarKind::LexicalCatch
2235                                } else {
2236                                    crate::bytecode::VarKind::Catch
2237                                },
2238                                is_captured: false,
2239                                scope_level: 0,
2240                                scope_next: None,
2241                            };
2242                            self.declare_local(&name.name.clone(), def);
2243                        }
2244                        // The handler body nests inside the parameter's scope, so the
2245                        // body's bindings chain on to the parameter (the reference
2246                        // prints `let y [next:1]`, pointing at `e`).
2247                        self.state().current_block = key;
2248                    }
2249                    self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2250                    // Back to the block the `try` itself lives in, so the finalizer
2251                    // is a sibling of the handler rather than nested in it.
2252                    self.state().current_block = try_parent;
2253                }
2254                if let Some(finalizer) = finalizer {
2255                    self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2256                }
2257            }
2258            StmtKind::Switch { cases, .. } => {
2259                let key = stmt.span.start.offset as u64;
2260                let parent = self.cur().current_block;
2261                self.push_block(key, parent);
2262                for case in cases {
2263                    self.hoist_list(&case.body)?;
2264                }
2265                self.state().current_block = parent;
2266            }
2267            _ => {}
2268        }
2269        Ok(())
2270    }
2271
2272    /// Hoist a nested statement list, which is its own lexical scope.
2273    fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2274        let parent = self.cur().current_block;
2275        self.push_block(key, parent);
2276        self.hoist_list(body)?;
2277        self.state().current_block = parent;
2278        Ok(())
2279    }
2280
2281    /// A block key for one part of a `try` statement.
2282    ///
2283    /// The three parts are three separate scopes, so they cannot share the key a
2284    /// statement's own offset would give them: the try block, the handler body and
2285    /// the finalizer would then look like one scope, and their `let` bindings would
2286    /// be marked uninitialised only on entering the first of them.
2287    fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2288        (stmt.span.start.offset as u64) * 4 + part as u64
2289    }
2290
2291    /// Declare a `var`: it lives in the function's own scope, not the block's.
2292    fn declare_var(&mut self, name: &str, def: VarDef) {
2293        if self.cur().is_module {
2294            self.declare_module(name, &def);
2295            return;
2296        }
2297        if self.cur().declares_globally(&def) {
2298            self.declare_global(name, &def);
2299            return;
2300        }
2301        let state = self.state();
2302        // A binding of the *parameter* scope does not count: the body's `var` of the
2303        // same name is a different binding and needs a slot of its own.
2304        if state.vars.iter().enumerate().any(|(index, v)| {
2305            v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
2306        }) {
2307            return;
2308        }
2309        // A `var` belongs to the function scope, never to the enclosing block.
2310        state.var_block.push(FUNCTION_SCOPE);
2311        state.vars.push(def);
2312    }
2313
2314    /// Declare `name` as a binding of the parameter scope, returning its slot.
2315    fn declare_param_var(&mut self, name: &str) -> u32 {
2316        declare_param_var_at(self.state(), name)
2317    }
2318
2319    /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2320    ///
2321    /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2322    /// so each points at the one declared before it and the oldest ends the chain with
2323    /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2324    /// runtime walks when it instantiates them.
2325    fn declare_param_binding(&mut self, name: &str) -> u32 {
2326        let state = self.state();
2327        let previous = state
2328            .vars
2329            .iter()
2330            .enumerate()
2331            .rev()
2332            .find(|(index, var)| {
2333                state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2334            })
2335            .map(|(index, _)| index as i32);
2336        let index = state.vars.len() as u32;
2337        state.var_block.push(PARAM_SCOPE);
2338        let mut def = VarDef::lexical(name);
2339        // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2340        // the function's, and its bindings are initialised one by one rather than all at
2341        // once — which is exactly what the dead zone needs.
2342        def.scope_level = 1;
2343        def.scope_next = Some(previous.unwrap_or(-2));
2344        state.vars.push(def);
2345        index
2346    }
2347
2348    /// The slot of a parameter-list binding, if the list has one by that name.
2349    fn param_binding_slot(&self, name: &str) -> Option<u32> {
2350        let state = self.cur();
2351        state
2352            .vars
2353            .iter()
2354            .enumerate()
2355            .position(|(index, var)| {
2356                var.name == name
2357                    && var.is_lexical
2358                    && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2359            })
2360            .map(|index| index as u32)
2361    }
2362
2363    /// Every parameter-list binding, in declaration order.
2364    fn param_binding_names(&self) -> Vec<String> {
2365        let state = self.cur();
2366        state
2367            .vars
2368            .iter()
2369            .enumerate()
2370            .filter(|(index, var)| {
2371                var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2372            })
2373            .map(|(_, var)| var.name.clone())
2374            .collect()
2375    }
2376
2377    /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2378    fn body_var_slot(&self, name: &str) -> Option<u32> {
2379        let state = self.cur();
2380        state
2381            .vars
2382            .iter()
2383            .enumerate()
2384            .find(|(index, var)| {
2385                var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2386            })
2387            .map(|(index, _)| index as u32)
2388    }
2389
2390    /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2391    /// one.
2392    ///
2393    /// With parameter expressions the reference creates two: an unmapped one in the
2394    /// argument scope, for the defaults and anything they close over, and the body's own.
2395    /// They are separate bindings, which is what makes
2396    /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2397    /// report 1 from `p` and 2 from the body.
2398    fn provide_param_arguments(&mut self) {
2399        if !self.cur().has_parameter_expressions {
2400            return;
2401        }
2402        let mentioned = self.cur().needs_param_arguments
2403            || self
2404                .cur()
2405                .insns
2406                .iter()
2407                .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2408        if !mentioned {
2409            return;
2410        }
2411        let slot = self.declare_param_var("arguments");
2412        let magic = if self.cur().strict { 0 } else { 1 };
2413        self.prepend_initialiser_to(
2414            slot,
2415            Insn::Fixed {
2416                op: Opcode::SpecialObject,
2417                operands: vec![Op::Int(magic)],
2418            },
2419        );
2420    }
2421
2422    /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2423    fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2424        let current = self.stack.len() - 1;
2425        let init = [
2426            producer,
2427            Insn::Fixed {
2428                op: Opcode::PutLoc,
2429                operands: vec![Op::Slot(Slot::Loc(slot))],
2430            },
2431        ];
2432        let inserted = init.len();
2433        for (index, instruction) in init.into_iter().enumerate() {
2434            self.stack[current].insns.insert(index, instruction);
2435        }
2436        for placed in self.stack[current].labels.iter_mut().flatten() {
2437            *placed += inserted;
2438        }
2439        self.state().label_since_insn = false;
2440    }
2441
2442    /// Give the function an `arguments` binding if its body mentions one.
2443    ///
2444    /// The check runs on the *instruction* stream rather than the AST: by this point
2445    /// every reference has become an `Insn::Var`, so scanning is exact and needs no
2446    /// AST walker. Declaring lazily matters for more than tidiness — always declaring
2447    /// would renumber every later local slot and stop the bytecode matching the
2448    /// reference, which only adds the binding when the body uses it.
2449    ///
2450    /// `arguments` is a local, initialised at the top of the body by
2451    /// `special_object`; that is the reference's shape, so the disassembly agrees.
2452    fn provide_arguments(&mut self) {
2453        let current = self.stack.len() - 1;
2454        if self.stack[current].is_script || self.stack[current].is_module {
2455            // A module has no `arguments` binding; referring to it is a ReferenceError,
2456            // which is exactly what an unbound name produces.
2457            return;
2458        }
2459        // An arrow has no `arguments` of its own: the binding belongs to the enclosing
2460        // function, which is why `() => arguments` sees the caller's arguments.
2461        if self.stack[current].is_arrow {
2462            if self.mentions("arguments") {
2463                self.ensure_enclosing_arguments();
2464            }
2465            return;
2466        }
2467        // Only a *body* mention needs the body's binding: the parameter list has one of
2468        // its own (see [`Compiler::provide_param_arguments`]).
2469        let mentioned = self.cur().insns.iter().any(|insn| {
2470            matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params)
2471        });
2472        if !mentioned && !self.cur().needs_arguments_local {
2473            return;
2474        }
2475        // The request may have come only from a parameter-list arrow, in which case the
2476        // parameter scope's binding already answers for it and the body needs none.
2477        if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
2478            return;
2479        }
2480        // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`. The mapping itself is
2481        // not implemented, so the two behave alike for now.
2482        //
2483        // With parameter expressions the list and the body are separate environments, so
2484        // an assignment to a parameter cannot be reflected into `arguments` at all — the
2485        // arguments object is unmapped whatever the mode, which is why the reference emits
2486        // `special_object 0` here even in sloppy code.
2487        let magic = if self.stack[current].strict || self.stack[current].has_parameter_expressions {
2488            0
2489        } else {
2490            1
2491        };
2492        self.prepend_binding("arguments", magic);
2493    }
2494
2495    /// Whether a *body* instruction refers to `arguments`.
2496    fn body_mentions_arguments(&self) -> bool {
2497        self.cur()
2498            .insns
2499            .iter()
2500            .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
2501    }
2502
2503    /// Whether the function body's instruction stream refers to `name`.
2504    fn mentions(&self, name: &str) -> bool {
2505        let current = self.stack.len() - 1;
2506        // A binding of the parameter scope does not answer for the body: the body's own
2507        // `arguments` (or self-name) still has to be provided for it.
2508        if self.stack[current]
2509            .vars
2510            .iter()
2511            .enumerate()
2512            .any(|(index, v)| {
2513                v.name == name
2514                    && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
2515            })
2516        {
2517            return false;
2518        }
2519        self.stack[current]
2520            .insns
2521            .iter()
2522            .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
2523    }
2524
2525    /// Bind the name a named function expression uses to refer to itself.
2526    ///
2527    /// The value is `special_object 2`, the function currently running, so the binding
2528    /// is the closure itself and not a copy. It is a local of this function, which is
2529    /// what keeps `g` out of the enclosing scope.
2530    /// Give the function a local `this`, for an arrow inside it to capture.
2531    fn provide_this_local(&mut self) {
2532        let current = self.stack.len() - 1;
2533        if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
2534            return;
2535        }
2536        if !self.stack[current]
2537            .vars
2538            .iter()
2539            .any(|var| var.name == "this")
2540        {
2541            self.declare_hidden_local("this", VarKind::Normal);
2542        }
2543        self.prepend_initialiser(
2544            "this",
2545            Insn::Fixed {
2546                op: Opcode::PushThis,
2547                operands: vec![],
2548            },
2549        );
2550    }
2551
2552    /// Give the function a local `<home_object>`, for an arrow or a static block inside it
2553    /// to read through `super`.
2554    fn provide_home_object_local(&mut self) {
2555        let current = self.stack.len() - 1;
2556        if !self.stack[current].needs_home_object_local {
2557            return;
2558        }
2559        if !self.stack[current]
2560            .vars
2561            .iter()
2562            .any(|var| var.name == HOME_OBJECT)
2563        {
2564            self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
2565        }
2566        self.prepend_initialiser(
2567            HOME_OBJECT,
2568            Insn::Fixed {
2569                op: Opcode::SpecialObject,
2570                operands: vec![Op::Int(4)],
2571            },
2572        );
2573    }
2574
2575    fn provide_self_name(&mut self) {
2576        let current = self.stack.len() - 1;
2577        let Some(name) = self.stack[current].self_name.clone() else {
2578            return;
2579        };
2580        if self.stack[current].self_name_initialized {
2581            return;
2582        }
2583        // Either the body refers to the name, or a nested function already forced the
2584        // binding into existence while being resolved. A direct `eval` can name it
2585        // without mentioning it, so its presence is a third reason: in strict mode
2586        // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
2587        // that only happens if the binding exists.
2588        let declared = self.stack[current].vars.iter().any(|v| v.name == name);
2589        if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
2590            return;
2591        }
2592        self.stack[current].self_name_initialized = true;
2593        self.prepend_binding_with(&name, 2, VarKind::FunctionName);
2594    }
2595
2596    /// Insert `special_object magic` plus the store to `name` at the top of the body.
2597    ///
2598    /// Prepending shifts every label that has been placed, so they are all moved by
2599    /// the number of instructions inserted.
2600    fn prepend_binding(&mut self, name: &str, magic: i32) {
2601        self.prepend_binding_with(name, magic, VarKind::Normal);
2602    }
2603
2604    /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
2605    fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
2606        let current = self.stack.len() - 1;
2607        // A function-expression's own name is immutable in strict mode, which is what
2608        // makes `f = 1` inside a strict body throw instead of being dropped.
2609        let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
2610        self.declare_var(
2611            name,
2612            VarDef {
2613                kind,
2614                is_const,
2615                ..VarDef::var(name)
2616            },
2617        );
2618        let init = [
2619            Insn::Fixed {
2620                op: Opcode::SpecialObject,
2621                operands: vec![Op::Int(magic)],
2622            },
2623            Insn::Var {
2624                // An initialisation, not an assignment: sloppy mode drops stores to a
2625                // function-expression's own name, and the prologue is what puts the
2626                // value there in the first place.
2627                action: if kind == VarKind::FunctionName {
2628                    VarAction::PutInit
2629                } else {
2630                    VarAction::Put
2631                },
2632                name: name.to_string(),
2633                block: 0,
2634                in_params: false,
2635            },
2636        ];
2637        let inserted = init.len();
2638        for (index, instruction) in init.into_iter().enumerate() {
2639            self.stack[current].insns.insert(index, instruction);
2640        }
2641        for placed in self.stack[current].labels.iter_mut().flatten() {
2642            *placed += inserted;
2643        }
2644        // A store sits at the insertion point now, so the `put`/`get` fold must not
2645        // reach across it.
2646        self.stack[current].label_since_insn = true;
2647    }
2648
2649    /// Record a top-level script declaration as a global.
2650    ///
2651    /// A script's top-level `var`/`let`/`function` create properties of the
2652    /// global object, not slots in the script's frame, so they show up as closure
2653    /// variables instead.
2654    fn declare_global(&mut self, name: &str, def: &VarDef) {
2655        let state = self.state();
2656        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2657            // The name was already referenced, from a function compiled before this
2658            // declaration was reached — `function a(){ b() } function b(){}` resolves
2659            // `b` while `b` is still unknown, and that guess has to be corrected here.
2660            // Leaving it as a plain global meant the declaration was never registered,
2661            // so the binding did not exist at run time and `a()` threw
2662            // `b is not defined`.
2663            if matches!(existing.closure_type, ClosureType::Global) {
2664                existing.closure_type = ClosureType::GlobalDecl;
2665                existing.is_const = def.is_const;
2666                existing.is_lexical = def.is_lexical;
2667            }
2668            return;
2669        }
2670        state.closure_vars.push(ClosureVar {
2671            name: name.to_string(),
2672            is_const: def.is_const,
2673            is_lexical: def.is_lexical,
2674            closure_type: ClosureType::GlobalDecl,
2675            var_idx: 0,
2676        });
2677    }
2678
2679    /// Record a module-level declaration as a module variable.
2680    ///
2681    /// The binding is a closure variable of the module body, so reads and writes are
2682    /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
2683    /// *who fills the cell*: the module record does, before the body runs, and an import
2684    /// points its cell at the exporting module's, which is what makes bindings live and
2685    /// cycles work.
2686    fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
2687        let state = self.state();
2688        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
2689            // The name may have been referenced before this declaration was hoisted,
2690            // which resolved it as a plain global. Correct that here, the way
2691            // `declare_global` does.
2692            if matches!(existing.closure_type, ClosureType::Global) {
2693                existing.closure_type = ClosureType::ModuleDecl;
2694                existing.is_const = def.is_const;
2695                existing.is_lexical = def.is_lexical;
2696            }
2697            return 0;
2698        }
2699        state.closure_vars.push(ClosureVar {
2700            name: name.to_string(),
2701            is_const: def.is_const,
2702            is_lexical: def.is_lexical,
2703            closure_type: ClosureType::ModuleDecl,
2704            var_idx: 0,
2705        });
2706        0
2707    }
2708
2709    /// Declare a module variable and answer its closure-variable index.
2710    ///
2711    /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
2712    /// module variable is not one. The import table needs the real index instead, because
2713    /// that is the position the host writes the cell into.
2714    fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
2715        self.declare_module(name, def);
2716        self.cur()
2717            .closure_vars
2718            .iter()
2719            .position(|c| c.name == name)
2720            .map(|index| index as u32)
2721            .unwrap_or(0)
2722    }
2723
2724    /// Declare one imported binding as a module variable.
2725    ///
2726    /// Returns the closure-variable index, which is what the import table records: the
2727    /// host writes the exporter's cell into that slot before the body runs.
2728    fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
2729        let state = self.state();
2730        if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
2731            // Keep the slot, fix the kind: the name may already have been referenced.
2732            state.closure_vars[index].closure_type = ClosureType::ModuleImport;
2733            state.closure_vars[index].is_const = is_const;
2734            return index as u32;
2735        }
2736        state.closure_vars.push(ClosureVar {
2737            name: name.to_string(),
2738            // An imported binding cannot be assigned: `x = 1` on an import is a
2739            // `TypeError` at run time, which the const flag is what produces.
2740            is_const: true,
2741            // Lexical, so reads go through `get_var_ref_check`: before linking has filled
2742            // the cell an import is in its dead zone, and reading it there must say so
2743            // rather than answer `undefined`.
2744            is_lexical: true,
2745            closure_type: ClosureType::ModuleImport,
2746            var_idx: 0,
2747        });
2748        state.closure_vars.len() as u32 - 1
2749    }
2750
2751    /// Emit the code an `export` needs.
2752    ///
2753    /// Only `export default <expr>` has any: everything else is a table entry whose
2754    /// binding is declared elsewhere. The expression is stored into the hidden
2755    /// `*default*` variable rather than returned, because the module body has no value
2756    /// to speak of.
2757    fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2758        match &decl.kind {
2759            ExportKind::Declaration(stmt) => self.stmt(stmt),
2760            ExportKind::Default(expr) => {
2761                // A named default function/class is already a module binding; the export
2762                // points at it and there is nothing to evaluate.
2763                if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some())
2764                    || matches!(&expr.kind, ExprKind::Class(class) if class.name.is_some())
2765                {
2766                    return Ok(());
2767                }
2768                self.expr(expr)?;
2769                let index = self.declare_export_default();
2770                self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
2771                Ok(())
2772            }
2773            ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
2774        }
2775    }
2776
2777    /// A module name as the string it denotes.
2778    fn module_name_text(name: &ModuleName) -> &str {
2779        match name {
2780            ModuleName::Ident(ident) => &ident.name,
2781            ModuleName::Str(text) => text,
2782        }
2783    }
2784
2785    /// Bind `import`'s local names and record where each one comes from.
2786    ///
2787    /// Nothing is emitted: an import is not an instruction, it is a promise that the
2788    /// binding's cell will be filled before the body runs. The cell lands in the module's
2789    /// environment at a fixed index, and the host fills it from the exporter's cell —
2790    /// which is why a cyclic import can bind before the other module has evaluated.
2791    fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
2792        let request = self.module_request(&decl.source, &decl.attributes);
2793        for specifier in &decl.specifiers {
2794            let (local, name, is_star) = match specifier {
2795                ImportSpecifier::Default(ident) => {
2796                    (ident.name.clone(), "default".to_string(), false)
2797                }
2798                ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
2799                ImportSpecifier::Named { imported, local } => (
2800                    local.name.clone(),
2801                    Self::module_name_text(imported).to_string(),
2802                    false,
2803                ),
2804            };
2805            // `import * as ns` is *not* a live binding of another module's variable —
2806            // it is a value of its own, which is why the reference declares it like a
2807            // module variable and the host stores the namespace object in that cell.
2808            let var_idx = if is_star {
2809                // `const`: a namespace object is a value, and the binding is immutable.
2810                self.declare_module_var(&local, &VarDef::constant(local.clone()))
2811            } else {
2812                self.declare_import(&local, true)
2813            };
2814            self.module_meta().imports.push(ImportEntry {
2815                module: request,
2816                name,
2817                var_idx,
2818                is_star,
2819            });
2820        }
2821        Ok(())
2822    }
2823
2824    /// Record what an `export` offers, declaring the binding it exports.
2825    ///
2826    /// `export var x = 1` is a declaration like any other; only the table entry is extra.
2827    fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
2828        match &decl.kind {
2829            ExportKind::Declaration(stmt) => {
2830                // The inner declaration keeps its own hoisting, then every name it binds
2831                // becomes an export of the same name.
2832                self.hoist_stmt(stmt)?;
2833                let mut names = Vec::new();
2834                Self::declared_names(stmt, &mut names);
2835                for name in names {
2836                    let var_idx = self.module_binding_index(&name);
2837                    self.exports_local(&name, var_idx);
2838                }
2839            }
2840            ExportKind::Default(expr) => {
2841                // The reference puts a default export in a hidden `*default*` variable,
2842                // so `export default function f(){}` can export a *value* while `f` stays
2843                // a binding of the module.
2844                if let ExprKind::Function(func) = &expr.kind
2845                    && let Some(name) = &func.name
2846                {
2847                    let text = name.name.clone();
2848                    self.hoist_stmt(&Stmt {
2849                        kind: StmtKind::FuncDecl(func.clone()),
2850                        span: expr.span,
2851                    })?;
2852                    let var_idx = self.module_binding_index(&text);
2853                    self.module_meta().exports.push(ExportEntry::Local {
2854                        export_name: "default".to_string(),
2855                        var_idx,
2856                    });
2857                    return Ok(());
2858                }
2859                if let ExprKind::Class(class) = &expr.kind
2860                    && let Some(name) = &class.name
2861                {
2862                    let text = name.name.clone();
2863                    self.hoist_stmt(&Stmt {
2864                        kind: StmtKind::ClassDecl(class.clone()),
2865                        span: expr.span,
2866                    })?;
2867                    let var_idx = self.module_binding_index(&text);
2868                    let _ = var_idx;
2869                }
2870                let var_idx = self.declare_export_default();
2871                self.module_meta().exports.push(ExportEntry::Local {
2872                    export_name: "default".to_string(),
2873                    var_idx,
2874                });
2875            }
2876            ExportKind::Named {
2877                specifiers,
2878                source,
2879                attributes,
2880            } => match source {
2881                Some(source) => {
2882                    let request = self.module_request(source, attributes);
2883                    for specifier in specifiers {
2884                        self.module_meta().exports.push(ExportEntry::Indirect {
2885                            export_name: Self::module_name_text(&specifier.exported).to_string(),
2886                            module: request,
2887                            import_name: Self::module_name_text(&specifier.local).to_string(),
2888                        });
2889                    }
2890                }
2891                None => {
2892                    for specifier in specifiers {
2893                        let local = Self::module_name_text(&specifier.local).to_string();
2894                        let var_idx = self.module_binding_index(&local);
2895                        let export_name = Self::module_name_text(&specifier.exported).to_string();
2896                        self.module_meta().exports.push(ExportEntry::Local {
2897                            export_name,
2898                            var_idx,
2899                        });
2900                    }
2901                }
2902            },
2903            ExportKind::All {
2904                source,
2905                exported,
2906                attributes,
2907            } => {
2908                let request = self.module_request(source, attributes);
2909                match exported {
2910                    Some(name) => {
2911                        self.module_meta().exports.push(ExportEntry::StarAs {
2912                            export_name: Self::module_name_text(name).to_string(),
2913                            module: request,
2914                        });
2915                    }
2916                    None => {
2917                        self.module_meta()
2918                            .exports
2919                            .push(ExportEntry::Star { module: request });
2920                    }
2921                }
2922            }
2923        }
2924        Ok(())
2925    }
2926
2927    /// The names a declaration binds, which is what `export <decl>` exports.
2928    fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
2929        match &stmt.kind {
2930            StmtKind::VarDecl(decl) => {
2931                for declarator in &decl.declarators {
2932                    let mut names = Vec::new();
2933                    declarator.target.bound_names(&mut names);
2934                    out.extend(names.into_iter().map(|name| name.name));
2935                }
2936            }
2937            StmtKind::FuncDecl(func) => {
2938                if let Some(name) = &func.name {
2939                    out.push(name.name.clone());
2940                }
2941            }
2942            StmtKind::ClassDecl(class) => {
2943                if let Some(name) = &class.name {
2944                    out.push(name.name.clone());
2945                }
2946            }
2947            _ => {}
2948        }
2949    }
2950
2951    /// The closure-variable index of a module binding, declaring it if the name was
2952    /// exported without being declared here.
2953    ///
2954    /// `export { x }` where `x` is not declared in the module is a link-time
2955    /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
2956    fn module_binding_index(&mut self, name: &str) -> u32 {
2957        if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
2958            return index as u32;
2959        }
2960        self.declare_module_var(name, &VarDef::lexical(name.to_string()))
2961    }
2962
2963    fn exports_local(&mut self, export_name: &str, var_idx: u32) {
2964        self.module_meta().exports.push(ExportEntry::Local {
2965            export_name: export_name.to_string(),
2966            var_idx,
2967        });
2968    }
2969
2970    /// The hidden `*default*` binding `export default <expr>` stores into.
2971    fn declare_export_default(&mut self) -> u32 {
2972        const DEFAULT: &str = "*default*";
2973        if let Some(index) = self
2974            .cur()
2975            .closure_vars
2976            .iter()
2977            .position(|c| c.name == DEFAULT)
2978        {
2979            return index as u32;
2980        }
2981        self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
2982    }
2983
2984    /// The module tables, which only the top-level state has.
2985    fn module_meta(&mut self) -> &mut ModuleMeta {
2986        self.state()
2987            .module
2988            .as_mut()
2989            .expect("module tables are only touched while compiling a module")
2990    }
2991
2992    /// The index of `specifier`'s request, adding it if it is new.
2993    ///
2994    /// Deduplicated on the specifier *and* its attributes: the same file imported once as
2995    /// JSON and once as text is two modules with two different contents, which is exactly
2996    /// what `hello_module.js` does.
2997    fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
2998        let attributes: Vec<(String, String)> = attributes
2999            .iter()
3000            .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
3001            .collect();
3002        let meta = self.module_meta();
3003        if let Some(index) = meta
3004            .requests
3005            .iter()
3006            .position(|request| request.specifier == specifier && request.attributes == attributes)
3007        {
3008            return index as u32;
3009        }
3010        meta.requests.push(ModuleRequest {
3011            specifier: specifier.to_string(),
3012            attributes,
3013        });
3014        meta.requests.len() as u32 - 1
3015    }
3016
3017    /// Compile a loop body with a `break`/`continue` target pushed for it.
3018    fn loop_body(
3019        &mut self,
3020        body: &Stmt,
3021        labels: &[String],
3022        continue_label: Label,
3023        break_label: Label,
3024    ) -> Result<(), SyntaxError> {
3025        self.push_jump_target(JumpTarget {
3026            names: labels.to_vec(),
3027            break_label: Some(break_label),
3028            continue_label: Some(continue_label),
3029            // A loop leaves nothing of its own on the value stack.
3030            drop_count: 0,
3031            finally_label: None,
3032            is_regular_stmt: false,
3033            has_iterator: false,
3034            is_async_iterator: false,
3035        });
3036        let result = self.stmt(body);
3037        self.pop_jump_target();
3038        result
3039    }
3040
3041    fn push_jump_target(&mut self, target: JumpTarget) {
3042        self.state().jump_targets.push(target);
3043    }
3044
3045    fn pop_jump_target(&mut self) {
3046        self.state().jump_targets.pop();
3047    }
3048
3049    fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3050        let (label, is_break) = match &stmt.kind {
3051            StmtKind::Break(label) => (label.as_ref(), true),
3052            StmtKind::Continue(label) => (label.as_ref(), false),
3053            _ => unreachable!("control_transfer is only called for break and continue"),
3054        };
3055
3056        // Walk outward from the innermost construct. Everything considered before
3057        // the match is a construct control is leaving, and leaving it has a cost:
3058        // its stack slots go, and its finalizer runs.
3059        let targets = self.cur().jump_targets.clone();
3060        for target in targets.iter().rev() {
3061            let destination = match (label, is_break) {
3062                // An unlabelled `break` skips a labelled non-loop statement: `break`
3063                // may name one, but the bare form only means "leave the loop".
3064                (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3065                (None, false) => target.continue_label,
3066                (Some(name), true) => target
3067                    .break_label
3068                    .filter(|_| target.names.contains(&name.name)),
3069                (Some(name), false) => target
3070                    .continue_label
3071                    .filter(|_| target.names.contains(&name.name)),
3072            };
3073
3074            if let Some(destination) = destination {
3075                self.emit_jump(Opcode::Goto, destination, &[]);
3076                return Ok(());
3077            }
3078
3079            // Closing the iterator consumes the three slots the loop keeps on the
3080            // stack (iterator, next method, catch offset), so those are not dropped
3081            // again below.
3082            let mut remaining = target.drop_count;
3083            if target.has_iterator {
3084                self.emit_iterator_close(target.is_async_iterator, false);
3085                remaining = remaining.saturating_sub(3);
3086            }
3087            for _ in 0..remaining {
3088                self.emit(Opcode::Drop, &[]);
3089            }
3090            if let Some(finally) = target.finally_label {
3091                // The finalizer runs as a subroutine and is handed a dummy return
3092                // value, which is dropped afterwards to keep the stack the depth it
3093                // had before.
3094                self.emit(Opcode::Undefined, &[]);
3095                self.emit_jump(Opcode::Gosub, finally, &[]);
3096                self.emit(Opcode::Drop, &[]);
3097            }
3098        }
3099
3100        // The parser rejects a break/continue with no target, so reaching here
3101        // means the compiler's own bookkeeping is wrong.
3102        Err(SyntaxError::new(
3103            if is_break {
3104                "break has no enclosing loop or switch"
3105            } else {
3106                "continue has no enclosing loop"
3107            },
3108            stmt.span,
3109        ))
3110    }
3111
3112    /// Compile a labelled statement.
3113    ///
3114    /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3115    /// that loop's targets, so the chain is collected and handed to the loop. A
3116    /// label on a non-loop statement only provides a `break` target, because
3117    /// `continue` may not target it.
3118    fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3119        let mut names = vec![label.name.clone()];
3120        let mut inner = body;
3121        while let StmtKind::Labeled {
3122            label: next,
3123            body: deeper,
3124        } = &inner.kind
3125        {
3126            names.push(next.name.clone());
3127            inner = deeper;
3128        }
3129        if Self::is_loop(inner) {
3130            return self.stmt_labelled(inner, &names);
3131        }
3132        let end = self.new_label();
3133        self.push_jump_target(JumpTarget {
3134            names,
3135            break_label: Some(end),
3136            continue_label: None,
3137            drop_count: 0,
3138            finally_label: None,
3139            is_regular_stmt: true,
3140            has_iterator: false,
3141            is_async_iterator: false,
3142        });
3143        let result = self.stmt(inner);
3144        self.pop_jump_target();
3145        result?;
3146        self.place_label(end);
3147        let _ = stmt;
3148        Ok(())
3149    }
3150
3151    /// Whether a statement is a loop, i.e. a valid target for `continue`.
3152    fn is_loop(stmt: &Stmt) -> bool {
3153        matches!(
3154            stmt.kind,
3155            StmtKind::While { .. }
3156                | StmtKind::DoWhile { .. }
3157                | StmtKind::For { .. }
3158                | StmtKind::ForIn { .. }
3159                | StmtKind::ForOf { .. }
3160        )
3161    }
3162
3163    /// Compile `switch`.
3164    ///
3165    /// The discriminant is evaluated once and stays on the value stack while the
3166    /// clauses compare against copies of it, so it is dropped at the end — which is
3167    /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3168    /// clause's body jumps over the *next* clause's tests straight into its body.
3169    ///
3170    /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3171    /// the next run's tests. Only the last run's miss reaches the `default` body, or
3172    /// the end of the switch when there is no `default`. That failure path can point
3173    /// backwards (`default` written first), so the runs and their labels are worked
3174    /// out before any code is emitted.
3175    fn switch(
3176        &mut self,
3177        discriminant: &Expr,
3178        cases: &[SwitchCase],
3179        stmt: &Stmt,
3180    ) -> Result<(), SyntaxError> {
3181        self.reset_value();
3182        // The discriminant is evaluated outside the switch's block scope, before
3183        // any `case` clause exists.
3184        self.expr(discriminant)?;
3185
3186        let switch_key = stmt.span.start.offset as u64;
3187        let switch_parent = self.cur().current_block;
3188        self.push_block(switch_key, switch_parent);
3189        self.emit_scope_enter(switch_key);
3190
3191        let break_label = self.new_label();
3192        self.push_jump_target(JumpTarget {
3193            names: Vec::new(),
3194            break_label: Some(break_label),
3195            // `switch` is a valid `break` target but not a `continue` target.
3196            continue_label: None,
3197            // The discriminant stays on the value stack for the whole statement, so
3198            // a `break` aimed further out has to discard it.
3199            drop_count: 1,
3200            finally_label: None,
3201            is_regular_stmt: false,
3202            has_iterator: false,
3203            is_async_iterator: false,
3204        });
3205
3206        // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3207        // its label to the clause after it, so both tests reach the same body.
3208        let mut runs: Vec<(usize, usize)> = Vec::new();
3209        let mut scan = 0;
3210        while scan < cases.len() {
3211            if cases[scan].test.is_some() {
3212                let mut last = scan;
3213                while last + 1 < cases.len()
3214                    && cases[last].test.is_some()
3215                    && cases[last].body.is_empty()
3216                    && cases[last + 1].test.is_some()
3217                {
3218                    last += 1;
3219                }
3220                runs.push((scan, last));
3221                scan = last + 1;
3222            } else {
3223                scan += 1;
3224            }
3225        }
3226
3227        let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3228        let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3229        let default_at = cases.iter().position(|case| case.test.is_none());
3230        // Where the last run sends control when nothing matched.
3231        let miss_target = match default_at {
3232            Some(index) => body_labels[index],
3233            None => break_label,
3234        };
3235
3236        // When `default` comes first, control has to jump over it to reach the
3237        // tests. It only needs to when some clause actually has a test; otherwise
3238        // the default body is the entry point.
3239        let mut entry = None;
3240        if default_at == Some(0) && !runs.is_empty() {
3241            self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3242            entry = Some(run_labels[0]);
3243        }
3244
3245        let mut index = 0;
3246        let mut run = 0;
3247        let result = (|| -> Result<(), SyntaxError> {
3248            while index < cases.len() {
3249                if cases[index].test.is_some() {
3250                    let (first, last) = runs[run];
3251                    // Reaching these tests from the preceding body is a
3252                    // fallthrough, which continues inside the body and skips them.
3253                    if index > 0 {
3254                        self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3255                    }
3256                    if let Some(label) = entry.take() {
3257                        self.place_label(label);
3258                    }
3259                    self.place_label(run_labels[run]);
3260
3261                    for (offset, case) in cases[first..=last].iter().enumerate() {
3262                        let test = case.test.as_ref().unwrap();
3263                        self.emit(Opcode::Dup, &[]);
3264                        self.expr(test)?;
3265                        self.emit(Opcode::StrictEq, &[]);
3266                        if first + offset < last {
3267                            self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3268                        } else {
3269                            // Hand over to the next run's tests, or give up.
3270                            let next = match runs.get(run + 1) {
3271                                Some(_) => run_labels[run + 1],
3272                                None => miss_target,
3273                            };
3274                            self.emit_jump(Opcode::IfFalse, next, &[]);
3275                        }
3276                    }
3277
3278                    self.place_label(body_labels[index]);
3279                    for case in &cases[first..=last] {
3280                        self.stmts(&case.body)?;
3281                    }
3282                    index = last + 1;
3283                    run += 1;
3284                } else {
3285                    // `default`: control arrives here either by falling through or
3286                    // because every test missed.
3287                    self.place_label(body_labels[index]);
3288                    self.stmts(&cases[index].body)?;
3289                    index += 1;
3290                }
3291            }
3292            Ok(())
3293        })();
3294
3295        if result.is_ok() {
3296            self.place_label(break_label);
3297            // Discard the discriminant now that no test needs it.
3298            self.emit(Opcode::Drop, &[]);
3299        }
3300
3301        self.pop_jump_target();
3302        self.emit_scope_leave(switch_key);
3303        self.state().current_block = switch_parent;
3304        result
3305    }
3306
3307    /// Compile `try`/`catch`/`finally`.
3308    ///
3309    /// The shape is an exception table built out of `catch` instructions, each of
3310    /// which records where control goes if the instructions that follow raise:
3311    ///
3312    /// ```text
3313    /// catch HANDLER            <- if the guarded block throws, jump to HANDLER
3314    ///   <guarded block>
3315    ///   drop                   <- discard the catch offset
3316    ///   undefined; gosub FINALLY; drop
3317    ///   goto END
3318    /// HANDLER:
3319    ///   <bind the catch parameter>
3320    ///   catch CATCH2           <- if the handler itself throws, go to CATCH2
3321    ///   <handler body>
3322    ///   drop; undefined; gosub FINALLY; drop; goto END
3323    /// CATCH2:
3324    ///   gosub FINALLY; throw   <- run the finalizer, then let the error out
3325    /// FINALLY:
3326    ///   <finalizer>
3327    ///   ret                    <- return to the `gosub`
3328    /// END:
3329    /// ```
3330    ///
3331    /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
3332    /// of the finalizer serves the normal path, the handler path and the
3333    /// propagating-exception path.
3334    ///
3335    /// The `undefined` before each `gosub` is a dummy return value: the finalizer
3336    /// runs with `ret_value` on the stack, and the normal path has no value to
3337    /// keep, so it pushes one to keep the stack depth identical on every path.
3338    fn try_stmt(
3339        &mut self,
3340        stmt: &Stmt,
3341        block: &[Stmt],
3342        handler: &Option<CatchClause>,
3343        finalizer: Option<&[Stmt]>,
3344    ) -> Result<(), SyntaxError> {
3345        self.reset_value();
3346
3347        let catch_label = self.new_label();
3348        let catch2_label = self.new_label();
3349        let finally_label = self.new_label();
3350        let end_label = self.new_label();
3351
3352        self.emit_jump(Opcode::Catch, catch_label, &[]);
3353
3354        // The guarded block. `break` may not target it, so its entry exists purely
3355        // to unwind: a jump out has to discard the catch offset and run the
3356        // finalizer.
3357        self.push_jump_target(JumpTarget {
3358            names: Vec::new(),
3359            break_label: None,
3360            continue_label: None,
3361            drop_count: 1,
3362            finally_label: Some(finally_label),
3363            is_regular_stmt: false,
3364            has_iterator: false,
3365            is_async_iterator: false,
3366        });
3367
3368        let block_key = Self::try_block_key(stmt, TryPart::Block);
3369        let block_parent = self.cur().current_block;
3370        self.push_block(block_key, block_parent);
3371        self.emit_scope_enter(block_key);
3372        self.stmts(block)?;
3373        self.emit_scope_leave(block_key);
3374        self.state().current_block = block_parent;
3375        // A guarded block that ends in a `return`/`throw` never reaches the
3376        // epilogue, so the reference does not emit one.
3377        self.pop_jump_target();
3378        let block_live = !block.last().is_some_and(Self::terminates);
3379
3380        if block_live {
3381            self.emit(Opcode::Drop, &[]);
3382            self.emit(Opcode::Undefined, &[]);
3383            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3384            self.emit(Opcode::Drop, &[]);
3385            self.emit_jump(Opcode::Goto, end_label, &[]);
3386        }
3387
3388        if let Some(handler) = handler {
3389            self.place_label(catch_label);
3390            // The thrown value is on top of the stack: bind it, or discard it for
3391            // `catch { }`.
3392            match &handler.param {
3393                Some(pattern) => {
3394                    // The stores resolve the names, so they have to run inside the
3395                    // parameter's own scope; otherwise a same-named `catch` further out
3396                    // could win. A `catch` binding is never in the dead zone, so the store
3397                    // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
3398                    let param_key = Self::try_block_key(stmt, TryPart::Param);
3399                    let param_parent = self.cur().current_block;
3400                    self.push_block(param_key, param_parent);
3401                    self.destructure(pattern, Some(VarDeclKind::Var))?;
3402                    self.state().current_block = param_parent;
3403                }
3404                None => self.emit(Opcode::Drop, &[]),
3405            }
3406            self.emit_jump(Opcode::Catch, catch2_label, &[]);
3407
3408            self.push_jump_target(JumpTarget {
3409                names: Vec::new(),
3410                break_label: None,
3411                continue_label: None,
3412                drop_count: 1,
3413                finally_label: Some(finally_label),
3414                is_regular_stmt: false,
3415                has_iterator: false,
3416                is_async_iterator: false,
3417            });
3418            let catch_key = Self::try_block_key(stmt, TryPart::Catch);
3419            let catch_parent = self.cur().current_block;
3420            self.push_block(catch_key, catch_parent);
3421            self.emit_scope_enter(catch_key);
3422            self.stmts(&handler.body)?;
3423            self.emit_scope_leave(catch_key);
3424            self.state().current_block = catch_parent;
3425            self.pop_jump_target();
3426            let handler_live = !handler.body.last().is_some_and(Self::terminates);
3427
3428            if handler_live {
3429                self.emit(Opcode::Drop, &[]);
3430                self.emit(Opcode::Undefined, &[]);
3431                self.emit_jump(Opcode::Gosub, finally_label, &[]);
3432                self.emit(Opcode::Drop, &[]);
3433                self.emit_jump(Opcode::Goto, end_label, &[]);
3434            }
3435
3436            // An error raised inside the handler still has to run the finalizer.
3437            self.place_label(catch2_label);
3438            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3439            self.emit(Opcode::Throw, &[]);
3440        } else {
3441            // `try`/`finally` with no handler: the finalizer runs, then the error
3442            // keeps propagating.
3443            self.place_label(catch_label);
3444            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3445            self.emit(Opcode::Throw, &[]);
3446        }
3447
3448        self.place_label(finally_label);
3449        // Inside the finalizer, leaving has a different cost: the return value and
3450        // the `gosub` return address are both on the stack, and neither finalizer nor
3451        // any outer one may run before the block has finished.
3452        self.push_jump_target(JumpTarget {
3453            names: Vec::new(),
3454            break_label: None,
3455            continue_label: None,
3456            drop_count: 2,
3457            finally_label: None,
3458            is_regular_stmt: false,
3459            has_iterator: false,
3460            is_async_iterator: false,
3461        });
3462        if let Some(finalizer) = finalizer {
3463            let finally_key = Self::try_block_key(stmt, TryPart::Finally);
3464            let finally_parent = self.cur().current_block;
3465            self.push_block(finally_key, finally_parent);
3466            self.emit_scope_enter(finally_key);
3467            self.stmts(finalizer)?;
3468            self.emit_scope_leave(finally_key);
3469            self.state().current_block = finally_parent;
3470        }
3471        self.pop_jump_target();
3472        self.emit(Opcode::Ret, &[]);
3473        self.place_label(end_label);
3474        Ok(())
3475    }
3476
3477    /// Compile `for`/`in` and `for`/`of`.
3478    ///
3479    /// Both keep an enumeration record on the value stack for the whole loop, which
3480    /// is what makes leaving early expensive: the record has to be dropped, or the
3481    /// iterator closed. The layout is
3482    ///
3483    /// ```text
3484    ///   <iterated expression>
3485    ///   for_in_start | for_of_start      <- pushes the record
3486    ///   goto TEST
3487    /// NEXT:
3488    ///   <bind the loop variable>
3489    ///   <body>
3490    /// TEST:
3491    ///   for_in_next | for_of_next 0
3492    ///   if_false NEXT                    <- not finished: next iteration
3493    ///   drop                             <- finished: discard the leftover value
3494    /// BREAK:
3495    ///   drop | iterator_close            <- the one cleanup `break` also uses
3496    /// ```
3497    ///
3498    /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
3499    /// normal exit share one copy — which is why `break` inside the loop emits nothing
3500    /// of its own, and only a jump that passes *through* the loop pays for its record.
3501    fn for_in_of(
3502        &mut self,
3503        stmt: &Stmt,
3504        left: &ForHead,
3505        right: &Expr,
3506        body: &Stmt,
3507        kind: ForLoopKind,
3508        labels: &[String],
3509    ) -> Result<(), SyntaxError> {
3510        self.reset_value();
3511
3512        let loop_key = stmt.span.start.offset as u64;
3513        let loop_parent = self.cur().current_block;
3514        self.push_block(loop_key, loop_parent);
3515        self.emit_scope_enter(loop_key);
3516
3517        // The iterated expression is evaluated inside the loop's scope, after the
3518        // bindings exist in the temporal dead zone.
3519        self.expr(right)?;
3520
3521        let next = self.new_label();
3522        let test = self.new_label();
3523        let break_target = self.new_label();
3524
3525        let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
3526        match kind {
3527            ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
3528            ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
3529            ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
3530        }
3531        self.emit_jump(Opcode::Goto, test, &[]);
3532
3533        self.push_jump_target(JumpTarget {
3534            // `outer: for (x of xs) … break outer` needs the name here. Without it the
3535            // loop had no label to break to, and the compiler reported "break has no
3536            // enclosing loop" for a loop that was plainly enclosing it.
3537            names: labels.to_vec(),
3538            break_label: Some(break_target),
3539            continue_label: Some(test),
3540            // Passing through the loop has to dispose of its record. A `for`/`of`
3541            // record is three slots, and closing the iterator consumes all of them.
3542            drop_count: if has_iterator { 3 } else { 1 },
3543            finally_label: None,
3544            is_regular_stmt: false,
3545            has_iterator,
3546            is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
3547        });
3548
3549        self.place_label(next);
3550        self.bind_loop_variable(left)?;
3551
3552        // The reference marks the body with its own label here. Nothing jumps to it
3553        // once the loop is laid out, but it is not decoration: a label between the
3554        // store and the body is why `put_loc v; get_loc v` does *not* fold into
3555        // `set_loc v` when the body starts by reading the loop variable.
3556        let body_label = self.new_label();
3557        self.place_label(body_label);
3558        // `for (using x of …)` disposes once per iteration, so the body is a disposal
3559        // region rather than the whole loop: the resource is the element that this
3560        // iteration produced.
3561        let using_slot = match left {
3562            ForHead::VarDecl(decl) if decl.kind.is_using() => {
3563                decl.declarators
3564                    .first()
3565                    .and_then(|declarator| match &declarator.target.kind {
3566                        PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
3567                        _ => None,
3568                    })
3569            }
3570            _ => None,
3571        };
3572        match using_slot {
3573            Some(slot) => {
3574                let live = !Self::terminates(body);
3575                self.using_region_around(slot, live, |compiler| compiler.stmt(body))?;
3576            }
3577            None => self.stmt(body)?,
3578        }
3579
3580        // §14.7.5.6 `ForIn/OfBodyEvaluation` step 6: a `let`/`const` head gets a **fresh
3581        // binding each iteration**, so a closure the body creates keeps that iteration's
3582        // value. `CloseCaptured` is the same instruction the C-style `for` uses: it swaps in
3583        // a new reference cell holding the current value.
3584        //
3585        // The position is the *end* of the body, not the start: closing before the body
3586        // would leave the closures pointing at the cell the next `put_loc` overwrites, and
3587        // `for (const x of [1,2,3]) fs.push(() => x)` answered `2,3,3` instead of `1,2,3`.
3588        for name in Self::loop_binding_names(left) {
3589            let pos = self.cur().cur_pos;
3590            self.state().insns.push(Insn::CloseCaptured {
3591                name,
3592                block: loop_key,
3593            });
3594            self.state().insn_pos.push(pos);
3595        }
3596        self.place_label(test);
3597        match kind {
3598            ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
3599            ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
3600            ForLoopKind::AwaitOf => {
3601                // The reference's shape: step, `await` the result, then unpack it.
3602                self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
3603                self.emit(Opcode::Await, &[]);
3604                self.state().has_await = true;
3605                self.emit(Opcode::IteratorGetValueDone, &[]);
3606            }
3607        }
3608        self.emit_jump(Opcode::IfFalse, next, &[]);
3609        // The loop is finished; `for_xx_next` left an `undefined` behind.
3610        self.emit(Opcode::Drop, &[]);
3611
3612        self.pop_jump_target();
3613        self.place_label(break_target);
3614        if has_iterator {
3615            // A loop that ran to completion finds its iterator slot already cleared (see
3616            // `iterator_get_value_done`), so this closes only an iterator abandoned by a
3617            // `break` that jumped here.
3618            self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
3619        } else {
3620            self.emit(Opcode::Drop, &[]);
3621        }
3622
3623        self.emit_scope_leave(loop_key);
3624        self.state().current_block = loop_parent;
3625        Ok(())
3626    }
3627
3628    /// The names a `for (let … of/in …)` head declares, which need a fresh cell per
3629    /// iteration. An assignment head (`for (x of …)`) declares nothing, so it is empty.
3630    fn loop_binding_names(left: &ForHead) -> Vec<String> {
3631        let ForHead::VarDecl(decl) = left else {
3632            return Vec::new();
3633        };
3634        if decl.kind == VarDeclKind::Var {
3635            return Vec::new();
3636        }
3637        let mut names = Vec::new();
3638        for declarator in &decl.declarators {
3639            let mut idents = Vec::new();
3640            declarator.target.bound_names(&mut idents);
3641            names.extend(idents.into_iter().map(|ident| ident.name));
3642        }
3643        names
3644    }
3645
3646    /// Store the value `for_xx_next` left on the stack into the loop variable.
3647    fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
3648        // A declaration *initialises* the binding, which is what takes a `let` out of
3649        // the temporal dead zone, so the store is the unchecked form. Assigning to a
3650        // binding declared elsewhere is an ordinary write and keeps its check.
3651        let (pattern, action) = match left {
3652            ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
3653            ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
3654        };
3655        match &pattern.kind {
3656            PatternKind::Ident(name) => {
3657                // `for (using x of …)` validates and snapshots each iteration's value
3658                // before the body runs, which is what makes a non-disposable element fail
3659                // on the iteration that produced it rather than at the end of the loop.
3660                if let ForHead::VarDecl(decl) = left
3661                    && decl.kind.is_using()
3662                {
3663                    let method_slot = self
3664                        .using_method_slot(&name.name)
3665                        .expect("a using binding was declared during hoisting");
3666                    self.emit(
3667                        Opcode::UsingCheck,
3668                        &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3669                    );
3670                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3671                }
3672                self.emit_var(action, &name.name);
3673                Ok(())
3674            }
3675            // Every other target stores through the same path an assignment pattern
3676            // uses, which is what makes `for (a[0] in obj)` write each key into the
3677            // property instead of refusing the loop outright.
3678            _ => self.destructure(
3679                pattern,
3680                match left {
3681                    ForHead::VarDecl(decl) => Some(decl.kind),
3682                    ForHead::Assign(_) => None,
3683                },
3684            ),
3685        }
3686    }
3687
3688    fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
3689        for declarator in &decl.declarators {
3690            let Some(init) = &declarator.init else {
3691                // `var x;` stays `undefined`. A lexical binding is different: it
3692                // has to be *initialised* to leave the temporal dead zone, so the
3693                // compiler supplies an explicit `undefined`.
3694                if decl.kind.is_lexical() {
3695                    // A lexical binding has to be *initialised* to leave the temporal
3696                    // dead zone, and a destructuring one is no different — `let {a}`
3697                    // with no initialiser is a syntax error, but `let [a] = []` still
3698                    // needs `a` to be initialised from an empty source, which the
3699                    // pattern does on its own.
3700                    self.emit(Opcode::Undefined, &[]);
3701                    self.destructure(&declarator.target, Some(decl.kind))?;
3702                }
3703                continue;
3704            };
3705            match &declarator.target.kind {
3706                PatternKind::Ident(name) => {
3707                    self.expr(init)?;
3708                    self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
3709                    if decl.kind.is_using() {
3710                        // `using_check` validates the value and snapshots its dispose
3711                        // method: `value -> value, method`. The snapshot is what makes a
3712                        // later change to `Symbol.dispose` irrelevant, and validating here
3713                        // is what keeps the body from running at all when the value is not
3714                        // disposable.
3715                        let method_slot = self
3716                            .using_method_slot(&name.name)
3717                            .expect("a using binding was declared during hoisting");
3718                        self.emit(
3719                            Opcode::UsingCheck,
3720                            &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
3721                        );
3722                        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
3723                        self.emit_var(VarAction::PutInit, &name.name);
3724                        continue;
3725                    }
3726                    // A declaration statement produces no value, so nothing is
3727                    // duplicated onto the stack.
3728                    match decl.kind {
3729                        VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
3730                        _ => self.emit_var(VarAction::PutInit, &name.name),
3731                    }
3732                }
3733                _ => {
3734                    // A destructuring declaration keeps nothing on the stack: the
3735                    // pattern consumes the initialiser.
3736                    self.expr(init)?;
3737                    self.destructure(&declarator.target, Some(decl.kind))?;
3738                }
3739            }
3740        }
3741        Ok(())
3742    }
3743
3744    /// Bind a destructuring pattern from the value on top of the stack.
3745    ///
3746    /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
3747    /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
3748    /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
3749    /// *assignment*, where a member expression is a legal target and the store is an
3750    /// ordinary property write.
3751    ///
3752    /// The value is consumed. An assignment expression's own result is the right-hand
3753    /// side, which the caller keeps separately — the spec does not make the pattern's
3754    /// last store produce it.
3755    fn destructure(
3756        &mut self,
3757        pattern: &Pattern,
3758        decl: Option<VarDeclKind>,
3759    ) -> Result<(), SyntaxError> {
3760        match &pattern.kind {
3761            PatternKind::Ident(name) => {
3762                match decl {
3763                    Some(VarDeclKind::Var) | None => {
3764                        self.emit_var(VarAction::Put, &name.name);
3765                    }
3766                    Some(_) => self.emit_var(VarAction::PutInit, &name.name),
3767                }
3768                Ok(())
3769            }
3770            PatternKind::Assign { target, default } => {
3771                // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
3772                // keeps `null`.
3773                //
3774                // The shape is the reference's: test for `undefined`, and when the value is
3775                // present fall **through** to a single store both paths share. The
3776                // alternatives — branching to the store on each side — need a second store
3777                // and a jump between them, which is what the dump used to show.
3778                let has_value = self.new_label();
3779                self.emit(Opcode::Dup, &[]);
3780                self.emit(Opcode::IsUndefined, &[]);
3781                self.emit_jump(Opcode::IfFalse, has_value, &[]);
3782                self.emit(Opcode::Drop, &[]);
3783                self.expr(default)?;
3784                // `var {f = function(){}} = {}` names the function `f`, like a plain
3785                // `var f = function(){}` does. Both pattern forms do it:
3786                // `BindingInitialization` names the value for a *binding* target, and since
3787                // ES2018 `DestructuringAssignmentEvaluation` does the same, so
3788                // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
3789                // no name to give, which is why only an identifier qualifies.
3790                if let PatternKind::Ident(name) = &target.kind {
3791                    self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
3792                }
3793                self.place_label(has_value);
3794                self.destructure(target, decl)
3795            }
3796            PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
3797            PatternKind::Object { properties, rest } => {
3798                self.destructure_object(properties, rest, decl, pattern)
3799            }
3800            PatternKind::Member(member) if decl.is_none() => {
3801                // An assignment pattern may store into a property. The value is on the
3802                // stack, so the receiver and the key go above it and `rot3l`/`swap2`
3803                // put the three in the order `put_array_el`/`put_field` expect.
3804                self.expr(&member.object)?;
3805                match &member.property {
3806                    MemberProp::Ident(name) => {
3807                        // `value obj` -> `obj value`, the order `put_field` takes.
3808                        // Nothing needs to be left behind: a pattern element's value is
3809                        // consumed by its own store.
3810                        self.emit(Opcode::Swap, &[]);
3811                        self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
3812                    }
3813                    MemberProp::Computed(index) => {
3814                        self.expr(index)?;
3815                        // `value obj key` -> `obj key value`.
3816                        self.emit(Opcode::Rot3l, &[]);
3817                        self.emit(Opcode::PutArrayEl, &[]);
3818                    }
3819                    MemberProp::Private(name) => {
3820                        // `value obj` -> `obj value`, and the store half of the assignment is
3821                        // the same one `obj.#x = value` uses — only without `insert2`,
3822                        // because a pattern element's value is not wanted back.
3823                        let binding = format!("#{}", name.name);
3824                        let (kind, setter) = self.private_use(&binding, member.span)?;
3825                        self.emit(Opcode::Swap, &[]);
3826                        self.private_store(&binding, kind, setter.as_deref())?;
3827                    }
3828                }
3829                Ok(())
3830            }
3831            PatternKind::Rest(inner) => self.destructure(inner, decl),
3832            PatternKind::Invalid(expr) => {
3833                Err(SyntaxError::new("invalid assignment target", expr.span))
3834            }
3835            _ => Err(SyntaxError::new(
3836                "this destructuring target is not supported by the compiler yet",
3837                pattern.span,
3838            )),
3839        }
3840    }
3841
3842    /// `[…]` on the left: drain an iterator, binding one target per element.
3843    fn destructure_array(
3844        &mut self,
3845        elements: &[Option<PatternElement>],
3846        rest: &Option<Box<RestElement>>,
3847        decl: Option<VarDeclKind>,
3848    ) -> Result<(), SyntaxError> {
3849        // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
3850        // pattern accepts any iterable and closes the iterator when the pattern ends
3851        // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
3852        // first because it is on top.
3853        self.emit(Opcode::ForOfStart, &[]);
3854        for element in elements {
3855            self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
3856            self.emit(Opcode::Drop, &[]);
3857            match element {
3858                Some(PatternElement::Pattern(pattern)) => self.destructure(pattern, decl)?,
3859                Some(PatternElement::Property { span, .. }) => {
3860                    return Err(SyntaxError::new(
3861                        "a property pattern is not a valid array element",
3862                        *span,
3863                    ));
3864                }
3865                // An elision skips the value, which is already on the stack.
3866                None => self.emit(Opcode::Drop, &[]),
3867            }
3868        }
3869        if let Some(rest) = rest {
3870            // The remaining values go into a fresh array. The target and its running
3871            // index stay on the stack above the iterator, which is what the operand of
3872            // `for_of_next` accounts for: two values sit above the iterator triple.
3873            self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
3874            self.emit(Opcode::Push0, &[]);
3875            let top = self.new_label();
3876            self.place_label(top);
3877            self.emit(Opcode::ForOfNext, &[Op::Int(2)]);
3878            let done = self.new_label();
3879            self.emit_jump(Opcode::IfTrue, done, &[]);
3880            self.emit(Opcode::DefineArrayEl, &[]);
3881            self.emit(Opcode::Inc, &[]);
3882            self.emit_jump(Opcode::Goto, top, &[]);
3883            self.place_label(done);
3884            self.emit(Opcode::Drop, &[]);
3885            self.emit(Opcode::Drop, &[]);
3886            self.destructure_rest(rest, decl)?;
3887        }
3888        self.emit(Opcode::IteratorClose, &[]);
3889        Ok(())
3890    }
3891
3892    /// `{…}` on the left: read properties off one boxed source object.
3893    fn destructure_object(
3894        &mut self,
3895        properties: &[Option<PatternElement>],
3896        rest: &Option<Box<RestElement>>,
3897        decl: Option<VarDeclKind>,
3898        pattern: &Pattern,
3899    ) -> Result<(), SyntaxError> {
3900        // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
3901        // aside for the rest element below.
3902        self.emit(Opcode::ToObject, &[]);
3903        let mut taken: Vec<Wtf8> = Vec::new();
3904        // Whether any key was computed, which a rest element cannot exclude.
3905        let mut computed = false;
3906        for property in properties {
3907            let Some(PatternElement::Property {
3908                key, value, span, ..
3909            }) = property
3910            else {
3911                return Err(SyntaxError::new(
3912                    "a bare pattern is not a valid object property",
3913                    properties
3914                        .iter()
3915                        .flatten()
3916                        .map(|element| match element {
3917                            PatternElement::Pattern(pattern) => pattern.span,
3918                            PatternElement::Property { span, .. } => *span,
3919                        })
3920                        .next()
3921                        .unwrap_or(pattern.span),
3922                ));
3923            };
3924            // Every read needs the source twice: to read from, and to keep for the next
3925            // property. `get_field2` is that duplicate-and-read in one instruction, but it
3926            // leaves the copy *under* the value, so it is only usable when whatever
3927            // consumes the value tolerates that. See [`reads_with_get_field2`].
3928            let nested = reads_with_get_field2(decl, value);
3929            if !nested {
3930                self.emit(Opcode::Dup, &[]);
3931            }
3932            match key {
3933                PropName::Literal(literal) => {
3934                    let name = self.property_key_text(literal, *span)?;
3935                    taken.push(name.clone());
3936                    self.emit(
3937                        if nested {
3938                            Opcode::GetField2
3939                        } else {
3940                            Opcode::GetField
3941                        },
3942                        &[Op::Atom(Atom::from_wtf8(&name))],
3943                    );
3944                }
3945                PropName::Computed(index) => {
3946                    // A computed key has no name to exclude ahead of time, so a rest
3947                    // element that has to skip it is refused below rather than silently
3948                    // copying the property into the rest object.
3949                    computed = true;
3950                    self.expr(index)?;
3951                    self.emit(Opcode::GetArrayEl, &[]);
3952                }
3953                PropName::Private(_) => {
3954                    return Err(SyntaxError::new(
3955                        "private fields are not supported by the compiler yet",
3956                        value.span,
3957                    ));
3958                }
3959            }
3960            self.destructure(value, decl)?;
3961        }
3962        match rest {
3963            Some(rest) => {
3964                if computed {
3965                    return Err(SyntaxError::new(
3966                        "a computed key with a rest element is not supported by the compiler yet",
3967                        Self::rest_span(rest),
3968                    ));
3969                }
3970                // `target src exclude`: the exclusion list is an array of the keys the
3971                // literal part already took, so the rest object gets only the others.
3972                self.emit(Opcode::Object, &[]);
3973                self.emit(Opcode::Swap, &[]);
3974                for name in &taken {
3975                    self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
3976                }
3977                self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
3978                self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
3979                self.emit(Opcode::Drop, &[]);
3980                self.emit(Opcode::Drop, &[]);
3981                self.destructure_rest(rest, decl)?;
3982            }
3983            // The source was only kept for a rest element.
3984            None => self.emit(Opcode::Drop, &[]),
3985        }
3986        Ok(())
3987    }
3988
3989    /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
3990    fn destructure_rest(
3991        &mut self,
3992        rest: &RestElement,
3993        decl: Option<VarDeclKind>,
3994    ) -> Result<(), SyntaxError> {
3995        match rest {
3996            RestElement::Pattern(pattern) => self.destructure(pattern, decl),
3997            // `[...a.b] = c` stores into a property.
3998            RestElement::Member(member) => {
3999                let pattern = Pattern {
4000                    kind: PatternKind::Member(member.clone()),
4001                    span: member.span,
4002                };
4003                self.destructure(&pattern, decl)
4004            }
4005        }
4006    }
4007
4008    /// The source range of a rest element, for error messages.
4009    fn rest_span(rest: &RestElement) -> Span {
4010        match rest {
4011            RestElement::Pattern(pattern) => pattern.span,
4012            RestElement::Member(member) => member.span,
4013        }
4014    }
4015
4016    /// Compile a function declaration and queue it for instantiation at scope
4017    /// entry.
4018    ///
4019    /// A declaration is visible before the statement that declares it, so the
4020    /// code that creates the function object belongs at the top of the enclosing
4021    /// scope, not at the declaration.
4022    fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
4023        let name = func.name.as_ref().expect("a declaration has a name");
4024        let function = self.compile_function(func)?;
4025        let pool_index = self.push_constant(Constant::Function(Box::new(function)));
4026        let target = self.hoist_target(&name.name);
4027        let block = self.cur().current_block;
4028        self.state().hoisted.push((block, target, pool_index));
4029        Ok(())
4030    }
4031
4032    /// Where a name lives, for a hoisted declaration.
4033    fn hoist_target(&self, name: &str) -> HoistTarget {
4034        let state = self.cur();
4035        if let Some(index) = state.args.iter().position(|a| a.name == name) {
4036            return HoistTarget::Arg(index as u32);
4037        }
4038        if let Some(index) = state.vars.iter().position(|v| v.name == name) {
4039            return HoistTarget::Loc(index as u32);
4040        }
4041        // A global function declaration is not a slot at all.
4042        HoistTarget::Global(name.to_string())
4043    }
4044
4045    // -- expressions -------------------------------------------------------
4046
4047    /// Compile one expression, recording where its instructions sit.
4048    ///
4049    /// The position is the node's operator when it has one and its first token
4050    /// otherwise, and it is restored on the way out so a parent's own instructions —
4051    /// which are emitted *after* its children — are blamed on the parent. Without the
4052    /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4053    fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4054        let saved = self.cur().cur_pos;
4055        // Only the node kinds the reference calls `emit_source_pos` for record a position:
4056        // the operator a node exists for, and a variable *read*, which the reference
4057        // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4058        // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4059        // start, a parenthesised group, an anonymous function expression — leaves the
4060        // previous position in place, because a table entry the reference never writes is
4061        // one we must not write either: the instruction that inherits a position (the
4062        // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4063        // report a more recent token than the reference does.
4064        let pos = expr.op_pos.or(match &expr.kind {
4065            ExprKind::Ident(ident) => Some(ident.span.start),
4066            _ => None,
4067        });
4068        match pos {
4069            Some(pos) => self.state().cur_pos = Some(pos),
4070            // A node the reference records nothing for: its own instructions stay
4071            // unpositioned, so they inherit whatever was written last — which is what an
4072            // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4073            // enclosing position instead would blame them on a token the reference has not
4074            // reached yet: a spread's `iterator_open` reports the expression it follows, and
4075            // a template's `to_propkey` the interpolation.
4076            None => self.state().cur_pos = None,
4077        }
4078        // Note a direct `eval` call before compiling it, because the *whole* function
4079        // is affected: an eval can name any binding the function declares, so every one
4080        // of them has to live in a cell for a closure it creates to capture it.
4081        if Self::is_direct_eval(expr) {
4082            // Every enclosing function is affected too: the eval sees the whole scope
4083            // chain, and a closure it creates can capture a binding of any of them.
4084            // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a
4085            // cell, because the closure the eval builds outlives the loop iteration.
4086            for state in &mut self.stack {
4087                state.has_direct_eval = true;
4088            }
4089            let block = self.cur().current_block;
4090            let in_params = self.cur().in_params;
4091            self.state()
4092                .pending_eval_sites
4093                .push((expr.span, block, in_params));
4094        }
4095        let result = self.expr_inner(expr);
4096        self.state().cur_pos = saved;
4097        result
4098    }
4099
4100    /// Record which bindings are in scope at a direct `eval` call.
4101    ///
4102    /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
4103    /// resolves names from a string at run time, so the only chance to pin down *which*
4104    /// slot a name means is here. Visibility is the lexical rule: a binding counts when
4105    /// its block is the current block, an enclosing one, or the function scope.
4106    fn materialize_eval_sites(&mut self) {
4107        let pending = std::mem::take(&mut self.state().pending_eval_sites);
4108        for (span, site_block, in_params) in pending {
4109            self.resolve_eval_site(span, site_block, in_params);
4110        }
4111    }
4112
4113    /// Resolve the bindings visible at one `eval` call.
4114    fn resolve_eval_site(&mut self, span: Span, site_block: u64, site_in_params: bool) {
4115        /// How near a binding is: function distance first, then block depth, then the
4116        /// later declaration (which shadows the earlier one in the same block).
4117        type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
4118
4119        // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
4120        // walked, innermost function first: a direct `eval` sees every enclosing
4121        // function's bindings, and none of them can be resolved at run time because the
4122        // runtime only has names to go on.
4123        let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
4124        let deepest = self.stack.len() - 1;
4125        for (level, state) in self.stack.iter().enumerate().rev() {
4126            let owner = (deepest - level) as u32;
4127            // The innermost function's block is the one the call sat in, which is not
4128            // the block the compiler is in now; the enclosing functions are still at
4129            // the point where this one was created.
4130            let here = if level == deepest {
4131                site_block
4132            } else {
4133                state.current_block
4134            };
4135            // The chain of live blocks, innermost first, with a depth for each. The walk
4136            // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
4137            // block can start at source offset zero.
4138            let mut live: Vec<(u64, usize)> = vec![(here, 0)];
4139            let mut block = here;
4140            while let Some(parent) = state
4141                .blocks
4142                .iter()
4143                .find(|candidate| candidate.key == block)
4144                .map(|candidate| candidate.parent)
4145                .filter(|parent| *parent != NO_PARENT)
4146                .filter(|parent| parent != &block)
4147            {
4148                live.push((parent, live.len()));
4149                block = parent;
4150            }
4151            let depth_of = |key: u64| {
4152                live.iter()
4153                    .find(|(candidate, _)| *candidate == key)
4154                    .map(|(_, depth)| *depth)
4155                    // The function scope is the outermost depth there is. A binding of a
4156                    // block this site is not inside lands here too, which pushes it
4157                    // behind every live one — the right answer: it is out of scope.
4158                    .unwrap_or(live.len())
4159            };
4160            for (index, arg) in state.args.iter().enumerate() {
4161                bindings.push((
4162                    (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
4163                    EvalVisible {
4164                        name: arg.name.clone(),
4165                        is_arg: true,
4166                        index: index as u32,
4167                        owner,
4168                    },
4169                ));
4170            }
4171            // A parameter list cannot see the body, so a body `var` is not a binding the
4172            // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
4173            // not let that eval write the body's `c`.
4174            let hides_body = if level == deepest {
4175                site_in_params
4176            } else {
4177                state.created_in_params
4178            };
4179            for (index, var) in state.vars.iter().enumerate() {
4180                let block = state
4181                    .var_block
4182                    .get(index)
4183                    .copied()
4184                    .unwrap_or(FUNCTION_SCOPE);
4185                if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
4186                    continue;
4187                }
4188                bindings.push((
4189                    (
4190                        owner as usize,
4191                        depth_of(block),
4192                        std::cmp::Reverse(index as u32),
4193                    ),
4194                    EvalVisible {
4195                        name: var.name.clone(),
4196                        is_arg: false,
4197                        index: index as u32,
4198                        owner,
4199                    },
4200                ));
4201            }
4202        }
4203        // Innermost function first, then innermost block, then the later declaration
4204        // (which shadows the earlier one within a block).
4205        bindings.sort_by_key(|(priority, _)| *priority);
4206        let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
4207        self.state().eval_sites.push(EvalSite {
4208            line: span.start.line,
4209            column: span.start.column,
4210            bindings,
4211        });
4212    }
4213
4214    /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
4215    ///
4216    /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
4217    /// a bare identifier callee counts.
4218    fn is_direct_eval(expr: &Expr) -> bool {
4219        matches!(
4220            &expr.kind,
4221            ExprKind::Call { callee, .. }
4222                if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
4223        )
4224    }
4225
4226    fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4227        match &expr.kind {
4228            ExprKind::Number(value) => self.push_number(*value),
4229            ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
4230            ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
4231            ExprKind::Null => self.emit(Opcode::Null, &[]),
4232            ExprKind::String(text) => self.push_string(text),
4233            ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
4234            ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
4235            ExprKind::This => self.this_expression(),
4236            ExprKind::NewTarget => self.new_target_expression(),
4237            ExprKind::Paren(inner) => self.expr(inner)?,
4238            ExprKind::Binary { op, left, right } => {
4239                self.expr(left)?;
4240                self.expr(right)?;
4241                self.emit(binary_opcode(*op), &[]);
4242            }
4243            ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
4244            ExprKind::Unary {
4245                op: UnaryOp::Minus,
4246                argument,
4247            } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
4248                let ExprKind::Number(value) = argument.unparen().kind else {
4249                    unreachable!("matched above")
4250                };
4251                // The reference folds a negative literal only when the negation is
4252                // exact in the integer range: `-1` becomes `push_minus1` and
4253                // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
4254                // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
4255                // `-Infinity`, not `Infinity` — and folding a fraction would change
4256                // which instruction the reference emits.
4257                let negated = -value;
4258                // `-2147483648` is deliberately excluded: its magnitude is one past
4259                // `i32::MAX`, so the reference sends it through the constant pool and
4260                // negates at run time instead.
4261                if value > 0.0
4262                    && negated == negated.trunc()
4263                    && negated >= -(i32::MAX as f64)
4264                    && negated < 0.0
4265                {
4266                    self.push_number(negated);
4267                } else {
4268                    self.push_number(value);
4269                    self.emit(Opcode::Neg, &[]);
4270                }
4271            }
4272            ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
4273            ExprKind::Conditional { test, cons, alt } => {
4274                let else_label = self.new_label();
4275                let end_label = self.new_label();
4276                self.expr(test)?;
4277                self.emit_jump(Opcode::IfFalse, else_label, &[]);
4278                self.expr(cons)?;
4279                self.emit_jump(Opcode::Goto, end_label, &[]);
4280                self.place_label(else_label);
4281                self.expr(alt)?;
4282                self.place_label(end_label);
4283            }
4284            ExprKind::Assign { op, target, value } => self.assign(*op, target, value)?,
4285            ExprKind::Update {
4286                op,
4287                argument,
4288                prefix,
4289            } => self.update(*op, argument, *prefix)?,
4290            ExprKind::Sequence(items) => {
4291                for (index, item) in items.iter().enumerate() {
4292                    self.expr(item)?;
4293                    if index + 1 != items.len() {
4294                        self.emit(Opcode::Drop, &[]);
4295                    }
4296                }
4297            }
4298            ExprKind::Call { .. } => self.chain_link_top(expr)?,
4299            ExprKind::Member { .. } => self.chain_link_top(expr)?,
4300            ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
4301            ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
4302            ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
4303            ExprKind::Template(template) => self.template_literal(template)?,
4304            ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
4305            ExprKind::New { callee, arguments } => {
4306                // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
4307                // The `dup` is not redundant: `call_constructor` takes the
4308                // constructor twice, once as the target and once as `new.target`,
4309                // which is what makes `new.target === C` inside the body.
4310                self.expr(callee)?;
4311                self.emit(Opcode::Dup, &[]);
4312                let args = arguments.as_deref().unwrap_or(&[]);
4313                if Self::has_spread(args) {
4314                    // `C C array`: the duplicated callee is already both the target
4315                    // and `new.target`, so no reordering is needed before `apply 1`.
4316                    self.argument_array(args)?;
4317                    self.emit(Opcode::Apply, &[Op::Int(1)]);
4318                    return Ok(());
4319                }
4320                for argument in args {
4321                    self.expr(argument)?;
4322                }
4323                self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
4324            }
4325            ExprKind::Class(class) => self.class_definition(class, true)?,
4326            ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
4327            ExprKind::Yield { argument, delegate } => {
4328                self.yield_expression(argument.as_deref(), *delegate)?
4329            }
4330            ExprKind::Await(argument) => self.await_expression(argument)?,
4331            ExprKind::RegExp { pattern, flags } => {
4332                // A literal is compiled *here*, at parse time, not when the line runs. The
4333                // spec is explicit that an invalid pattern is an early error (§12.9.4:
4334                // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
4335                // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
4336                // also validates `\p{…}` names: 163 conformance cases are patterns that have
4337                // to be rejected before any code runs.
4338                //
4339                // This is the whole reason the engine lives in its own crate rather than
4340                // inside `quickjs-pure`: the compiler could not depend on the interpreter
4341                // (`pure` depends on `compile`), but both need this.
4342                // The lexer already rejected an unknown or repeated flag, so an unparsable
4343                // flag string here would be a bug in the lexer rather than in the script;
4344                // fall back to the default flags instead of inventing a second message.
4345                let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
4346                let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
4347                    SyntaxError::new(
4348                        format!("invalid regular expression: {}", error.message),
4349                        expr.span,
4350                    )
4351                })?;
4352                // The tree is thrown away and rebuilt when the literal first runs: keeping it
4353                // would mean serialising the syntax tree into the function's constant pool,
4354                // and a literal is created once per evaluation of its expression anyway.
4355                let _ = parsed;
4356                // The pattern and its flags travel as two string constants; `regexp` builds
4357                // the object. A dedicated opcode (rather than a call to the constructor) is
4358                // what the reference does too, so that a literal never goes through the
4359                // public `RegExp` function and its string-coercion rules.
4360                self.push_string(&Wtf8::new(pattern));
4361                self.push_string(&Wtf8::new(flags));
4362                self.emit(Opcode::Regexp, &[]);
4363            }
4364            ExprKind::Arrow(func) => {
4365                let function = self.compile_function(func)?;
4366                let index = self.push_constant(Constant::Function(Box::new(function)));
4367                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4368            }
4369            ExprKind::Function(func) => {
4370                let function = self.compile_function_with_name(func, true)?;
4371                let index = self.push_constant(Constant::Function(Box::new(function)));
4372                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
4373            }
4374            // `import.meta`: the host fills a per-module object at link time.
4375            ExprKind::ImportMeta => {
4376                self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
4377            }
4378            // `import("x")` compiles to a two-slot push followed by one opcode: the
4379            // specifier, then the options object (`undefined` here, since this compiler
4380            // does not accept the second argument yet).
4381            ExprKind::ImportCall(specifier) => {
4382                self.expr(specifier)?;
4383                self.emit(Opcode::Undefined, &[]);
4384                self.emit(Opcode::Import, &[]);
4385            }
4386            ExprKind::PrivateIn { name, object } => {
4387                // `#x in o`: the object, then the binding, then one opcode which decides what
4388                // to do with the second operand. A field's binding holds a symbol and the
4389                // answer is an own-property test; a method's holds a function and the answer
4390                // is a brand check — both live in `private_in`, so the compiler emits the
4391                // same instruction for either.
4392                self.expr(object)?;
4393                self.emit_var(VarAction::Get, &format!("#{}", name.name));
4394                self.emit(Opcode::PrivateIn, &[]);
4395            }
4396            _ => {
4397                return Err(SyntaxError::new(
4398                    "this expression form is not supported by the compiler yet",
4399                    expr.span,
4400                ));
4401            }
4402        }
4403        Ok(())
4404    }
4405
4406    /// Build one array holding the evaluated call arguments, which is how a call
4407    /// containing a spread is compiled: the reference does the same, building the
4408    /// list on the stack and handing it to `apply`.
4409    fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
4410        let elements: Vec<Option<ArrayElement>> = arguments
4411            .iter()
4412            .map(|argument| match &argument.unparen().kind {
4413                ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
4414                _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
4415            })
4416            .collect();
4417        self.array_literal(&elements, Span::default())
4418    }
4419
4420    /// Whether any argument is a spread, which is what selects the `apply` form.
4421    fn has_spread(arguments: &[Expr]) -> bool {
4422        arguments
4423            .iter()
4424            .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
4425    }
4426
4427    /// Compile `a${x}b`.
4428    ///
4429    /// A template is a `+` chain built left to right: the leading chunk (or an empty
4430    /// string when the template starts with a substitution), then for each
4431    /// substitution its value, `to_propkey` and `add`, then the following chunk when
4432    /// it is not empty. `to_propkey` is what makes a number or object substitute the
4433    /// way `ToString` would while leaving the result a string for `add` to
4434    /// concatenate.
4435    ///
4436    /// The chunk is an atom rather than a constant-pool string, because a non-empty
4437    /// chunk always lands where a value is pushed and `push_atom_value` is the
4438    /// instruction the reference uses for it; the empty first chunk has its own
4439    /// zero-byte form.
4440    fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
4441        let first = template.quasis.first();
4442        match first.and_then(|quasi| quasi.cooked.clone()) {
4443            Some(text) if !text.is_empty() => {
4444                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4445            }
4446            // Either the template begins with a substitution, or the chunk is
4447            // empty — in both cases the chain needs a string to start from.
4448            _ => self.emit(Opcode::PushEmptyString, &[]),
4449        }
4450        for (index, expression) in template.expressions.iter().enumerate() {
4451            self.expr(expression)?;
4452            self.emit(Opcode::ToPropkey, &[]);
4453            self.emit(Opcode::Add, &[]);
4454            if let Some(text) = template
4455                .quasis
4456                .get(index + 1)
4457                .and_then(|quasi| quasi.cooked.clone())
4458                && !text.is_empty()
4459            {
4460                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
4461                self.emit(Opcode::Add, &[]);
4462            }
4463        }
4464        Ok(())
4465    }
4466
4467    /// Compile an object literal.
4468    ///
4469    /// The object is built in place: `object` pushes it, and each property leaves it
4470    /// on the stack with one field more, so no temporary is needed and later
4471    /// properties can overwrite earlier ones.
4472    ///
4473    /// The instruction depends on *how* the property was written, not on what kind
4474    /// of value it holds:
4475    ///
4476    /// | source | instruction |
4477    /// |---|---|
4478    /// | `{ a: v }` | `define_field a` |
4479    /// | `{ __proto__: v }` | `set_proto` |
4480    /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
4481    /// | `{ m() {} }` | `define_method m,4` |
4482    /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
4483    /// | `{ [k]() {} }` | `define_method_computed 4` |
4484    /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
4485    ///
4486    /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
4487    /// key itself, which is why the trailing `drop` is absent there too.
4488    /// `tag`…``: a call whose first argument is the call site's template object.
4489    ///
4490    /// The template object is a frozen array of the cooked chunks with a frozen `raw`
4491    /// array beside it, so `String.raw` can read the source text back. It is a constant
4492    /// because its contents never change; the reference builds one per call site and
4493    /// reuses it, while this builds one per evaluation, which only `tag` code that
4494    /// compares template objects across calls could tell apart.
4495    fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
4496        let cooked = quasi
4497            .quasis
4498            .iter()
4499            .map(|chunk| chunk.cooked.clone())
4500            .collect();
4501        let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
4502        let index = self.push_constant(Constant::Template { cooked, raw });
4503        let count = quasi.expressions.len() + 1;
4504        // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
4505        if let ExprKind::Member {
4506            object, property, ..
4507        } = &tag.unparen().kind
4508        {
4509            self.expr(object)?;
4510            match property {
4511                MemberProp::Ident(name) => {
4512                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
4513                }
4514                MemberProp::Computed(key) => {
4515                    self.expr(key)?;
4516                    self.emit(Opcode::GetArrayEl2, &[]);
4517                }
4518                MemberProp::Private(name) => {
4519                    let binding = format!("#{}", name.name);
4520                    let (kind, _) = self.private_use(&binding, tag.span)?;
4521                    self.private_callee(&binding, kind)?;
4522                }
4523            }
4524            self.emit(Opcode::PushConst, &[Op::Const(index)]);
4525            for expression in &quasi.expressions {
4526                self.expr(expression)?;
4527            }
4528            self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
4529            return Ok(());
4530        }
4531        self.expr(tag)?;
4532        self.emit(Opcode::PushConst, &[Op::Const(index)]);
4533        for expression in &quasi.expressions {
4534            self.expr(expression)?;
4535        }
4536        self.emit(Opcode::Call, &[Op::Int(count as i32)]);
4537        Ok(())
4538    }
4539
4540    fn object_literal(
4541        &mut self,
4542        properties: &[ObjectProperty],
4543        span: Span,
4544    ) -> Result<(), SyntaxError> {
4545        self.emit(Opcode::Object, &[]);
4546        for property in properties {
4547            match property {
4548                ObjectProperty::Spread(value) => {
4549                    // `copy_data_properties` takes the target, the source and an
4550                    // exclusion list; a literal `null` means "exclude nothing".
4551                    // Flag bit 1 copies symbols, bits 2/5 pick the source and the
4552                    // exclusion list by stack offset.
4553                    self.expr(spread_argument(value))?;
4554                    self.emit(Opcode::Null, &[]);
4555                    self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4556                    self.emit(Opcode::Drop, &[]);
4557                    self.emit(Opcode::Drop, &[]);
4558                }
4559                ObjectProperty::Property {
4560                    key,
4561                    value,
4562                    kind,
4563                    shorthand,
4564                    span: property_span,
4565                } => match key {
4566                    PropName::Computed(key_expr) => {
4567                        self.expr(key_expr)?;
4568                        match kind {
4569                            PropertyKind::Value => {
4570                                self.emit(Opcode::ToPropkey, &[]);
4571                                self.expr(value)?;
4572                                self.set_name_if_anonymous_computed(value);
4573                                self.emit(Opcode::DefineArrayEl, &[]);
4574                                // `define_array_el` leaves the object and the key;
4575                                // the key is no longer needed.
4576                                self.emit(Opcode::Drop, &[]);
4577                            }
4578                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4579                                self.emit_method_function(value)?;
4580                                self.emit(
4581                                    Opcode::DefineMethodComputed,
4582                                    &[Op::Int(define_method_flags(*kind))],
4583                                );
4584                            }
4585                        }
4586                    }
4587                    PropName::Literal(key) => {
4588                        let name = self.property_key_text(key, *property_span)?;
4589                        match kind {
4590                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
4591                                self.emit_method_function(value)?;
4592                                self.emit(
4593                                    Opcode::DefineMethod,
4594                                    &[
4595                                        Op::Atom(Atom::from_wtf8(&name)),
4596                                        Op::Int(define_method_flags(*kind)),
4597                                    ],
4598                                );
4599                            }
4600                            PropertyKind::Value => {
4601                                self.expr(value)?;
4602                                // `{__proto__: x}` sets the prototype instead of
4603                                // creating a property; the shorthand `{__proto__}`
4604                                // is an ordinary property and does not.
4605                                if name == "__proto__" && !shorthand {
4606                                    self.emit(Opcode::SetProto, &[]);
4607                                } else {
4608                                    self.set_name_if_anonymous(value, &name);
4609                                    self.emit(
4610                                        Opcode::DefineField,
4611                                        &[Op::Atom(Atom::from_wtf8(&name))],
4612                                    );
4613                                }
4614                            }
4615                        }
4616                    }
4617                    PropName::Private(_) => {
4618                        return Err(SyntaxError::new(
4619                            "private names are not valid in object literals",
4620                            *property_span,
4621                        ));
4622                    }
4623                },
4624            }
4625        }
4626        let _ = span;
4627        Ok(())
4628    }
4629
4630    /// Emit the function a method/accessor property defines.
4631    fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
4632        self.expr(value)
4633    }
4634
4635    /// The name a literal property key contributes.
4636    ///
4637    /// String keys are used as written. A numeric key is converted the way
4638    /// `ToString` would convert it, because the atom is made from that spelling:
4639    /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
4640    fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
4641        match key {
4642            PropKey::Str(text) => Ok(text.clone()),
4643            PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
4644        }
4645    }
4646
4647    /// Compile an optional chain.
4648    ///
4649    /// `?.` short-circuits the *whole remaining spine*, not just its own link:
4650    /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
4651    /// `undefined`. So the chain is compiled with one end label and every guard
4652    /// jumps to it. The parser hands us the extent of that spine as an
4653    /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
4654    /// exactly the scope the label has to cover.
4655    fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
4656        let end = self.new_label();
4657        self.chain_link(inner, end)?;
4658        self.place_label(end);
4659        Ok(())
4660    }
4661
4662    /// A member access or call reached from outside any optional chain.
4663    ///
4664    /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
4665    /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
4666    /// still created because [`Self::chain_link`] takes it, and placing it at the
4667    /// end is a no-op that keeps a single code path.
4668    fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4669        let end = self.new_label();
4670        self.chain_link(expr, end)?;
4671        self.place_label(end);
4672        Ok(())
4673    }
4674
4675    /// One link of a chain, where `end` is the label a `?.` guard jumps to.
4676    fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
4677        match &expr.kind {
4678            ExprKind::Member {
4679                object,
4680                property,
4681                optional,
4682            } => {
4683                // `super.x` is not a lookup on a value: it starts at the home object's
4684                // prototype and keeps `this` as the receiver, so it cannot go through
4685                // `chain_link` and the ordinary field read.
4686                if matches!(object.unparen().kind, ExprKind::SuperProp) {
4687                    self.super_base();
4688                    match property {
4689                        MemberProp::Ident(name) => self.emit(
4690                            Opcode::PushAtomValue,
4691                            &[Op::Atom(Atom::from_text(&name.name))],
4692                        ),
4693                        MemberProp::Computed(index) => self.expr(index)?,
4694                        MemberProp::Private(_) => {
4695                            return Err(SyntaxError::new(
4696                                "private fields are not supported by the compiler yet",
4697                                expr.span,
4698                            ));
4699                        }
4700                    }
4701                    self.emit(Opcode::GetSuperValue, &[]);
4702                    return Ok(());
4703                }
4704                self.chain_link(object, end)?;
4705                if *optional {
4706                    self.optional_guard(end);
4707                }
4708                match property {
4709                    // `.length` has its own opcode. The reference emits it for every
4710                    // object, not just arrays, so a name-based rule is right and
4711                    // cheaper than the generic field read.
4712                    MemberProp::Ident(name) if name.name == "length" => {
4713                        self.emit(Opcode::GetLength, &[]);
4714                    }
4715                    MemberProp::Ident(name) => {
4716                        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
4717                    }
4718                    MemberProp::Computed(index) => {
4719                        self.expr(index)?;
4720                        self.emit(Opcode::GetArrayEl, &[]);
4721                    }
4722                    MemberProp::Private(name) => {
4723                        // The binding comes from the class scope, so a read from outside the
4724                        // class cannot name it at all. `?.` checks the object, not the field:
4725                        // `o?.#x` guards on `o` being nullish.
4726                        let binding = format!("#{}", name.name);
4727                        let (kind, _) = self.private_use(&binding, expr.span)?;
4728                        self.private_load(&binding, kind, expr.span)?;
4729                    }
4730                }
4731                Ok(())
4732            }
4733            ExprKind::Call {
4734                callee,
4735                arguments,
4736                optional,
4737            } => {
4738                // `o.m(args)` has to pass `o` as `this`, which a plain `call`
4739                // cannot: it reads the function and then calls it with no
4740                // receiver at all. The reference's answer is to keep the object
4741                // under the function value — `get_field2` reads a field and leaves
4742                // its base in place — and to use `call_method`, which takes the
4743                // receiver from the stack. Missing this does not just cost an
4744                // instruction, it loses the `this` binding.
4745                if let ExprKind::Member {
4746                    object,
4747                    property,
4748                    optional: member_optional,
4749                } = &callee.unparen().kind
4750                {
4751                    // `super.m()` reads the method off the home object's prototype but
4752                    // calls it with `this`, so the receiver goes under the read instead of
4753                    // being replaced by it.
4754                    if matches!(object.unparen().kind, ExprKind::SuperProp) {
4755                        self.super_base();
4756                        match property {
4757                            MemberProp::Ident(name) => self.emit(
4758                                Opcode::PushAtomValue,
4759                                &[Op::Atom(Atom::from_text(&name.name))],
4760                            ),
4761                            MemberProp::Computed(index) => self.expr(index)?,
4762                            MemberProp::Private(_) => {
4763                                return Err(SyntaxError::new(
4764                                    "private fields are not supported by the compiler yet",
4765                                    expr.span,
4766                                ));
4767                            }
4768                        }
4769                        // The two-output form would drop the receiver; this one replaces
4770                        // the prototype and the key, leaving `this` underneath.
4771                        self.emit(Opcode::GetArrayEl, &[]);
4772                        if Self::has_spread(arguments) {
4773                            self.argument_array(arguments)?;
4774                            self.emit(Opcode::Perm3, &[]);
4775                            self.emit(Opcode::Apply, &[Op::Int(0)]);
4776                            return Ok(());
4777                        }
4778                        for argument in arguments {
4779                            self.expr(argument)?;
4780                        }
4781                        self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4782                        return Ok(());
4783                    }
4784                    self.chain_link(object, end)?;
4785                    if *member_optional {
4786                        self.optional_guard(end);
4787                    }
4788                    match property {
4789                        MemberProp::Ident(name) => {
4790                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4791                        }
4792                        MemberProp::Computed(index) => {
4793                            self.expr(index)?;
4794                            // The key is not needed after the read, so this is the
4795                            // two-output form: object, value.
4796                            self.emit(Opcode::GetArrayEl2, &[]);
4797                        }
4798                        MemberProp::Private(name) => {
4799                            // The receiver is already under the callee, which is exactly the
4800                            // shape `call_method` and `apply` want — so nothing is dropped.
4801                            let binding = format!("#{}", name.name);
4802                            let (kind, _) = self.private_use(&binding, expr.span)?;
4803                            self.private_callee(&binding, kind)?;
4804                        }
4805                    }
4806                    if Self::has_spread(arguments) {
4807                        // Stack is `obj func`; the array goes on top, then `perm3`
4808                        // reorders to the `func this array` that `apply` wants.
4809                        self.argument_array(arguments)?;
4810                        self.emit(Opcode::Perm3, &[]);
4811                        self.emit(Opcode::Apply, &[Op::Int(0)]);
4812                        return Ok(());
4813                    }
4814                    for argument in arguments {
4815                        self.expr(argument)?;
4816                    }
4817                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4818                    return Ok(());
4819                }
4820                // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
4821                // with `get_field2` so the base stays under it, and on the short-circuit
4822                // path pushes an extra `undefined` as a placeholder receiver — the call
4823                // then throws, which is what calling a missing optional chain should do.
4824                if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
4825                    && let ExprKind::Member {
4826                        object,
4827                        property,
4828                        optional: member_optional,
4829                    } = &inner.unparen().kind
4830                {
4831                    let call = self.new_label();
4832                    // A guard target of its own: the outer `end` skips the whole
4833                    // expression, and a short-circuited receiver still has to reach the
4834                    // call so that calling it throws.
4835                    let short = self.new_label();
4836                    self.chain_link(object, end)?;
4837                    if *member_optional {
4838                        self.optional_guard(short);
4839                    }
4840                    match property {
4841                        MemberProp::Ident(name) => {
4842                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4843                        }
4844                        MemberProp::Computed(index) => {
4845                            self.expr(index)?;
4846                            self.emit(Opcode::GetArrayEl2, &[]);
4847                        }
4848                        MemberProp::Private(name) => {
4849                            let binding = format!("#{}", name.name);
4850                            let (kind, _) = self.private_use(&binding, expr.span)?;
4851                            self.private_callee(&binding, kind)?;
4852                        }
4853                    }
4854                    self.emit_jump(Opcode::Goto, call, &[]);
4855                    self.place_label(short);
4856                    self.emit(Opcode::Undefined, &[]);
4857                    self.place_label(call);
4858                    if Self::has_spread(arguments) {
4859                        self.argument_array(arguments)?;
4860                        self.emit(Opcode::Perm3, &[]);
4861                        self.emit(Opcode::Apply, &[Op::Int(0)]);
4862                        return Ok(());
4863                    }
4864                    for argument in arguments {
4865                        self.expr(argument)?;
4866                    }
4867                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
4868                    return Ok(());
4869                }
4870                self.chain_link(callee, end)?;
4871                if *optional {
4872                    self.optional_guard(end);
4873                }
4874                if Self::has_spread(arguments) {
4875                    // `func array -> func undefined array`, which is the plain-call
4876                    // form of `apply`: the receiver is `undefined`.
4877                    self.argument_array(arguments)?;
4878                    self.emit(Opcode::Undefined, &[]);
4879                    self.emit(Opcode::Swap, &[]);
4880                    self.emit(Opcode::Apply, &[Op::Int(0)]);
4881                    return Ok(());
4882                }
4883                for argument in arguments {
4884                    self.expr(argument)?;
4885                }
4886                self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
4887                Ok(())
4888            }
4889            _ => self.expr(expr),
4890        }
4891    }
4892
4893    /// Compile `expr` as a tail call when it is one, reporting whether it was.
4894    ///
4895    /// `tail_call` reuses the current frame instead of pushing a new one, so a
4896    /// tail-recursive function runs in constant stack space. It also has to be the
4897    /// *last* thing the function does, which is why only a `return` reaches here.
4898    fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
4899        let ExprKind::Call {
4900            callee,
4901            arguments,
4902            optional: false,
4903        } = &expr.unparen().kind
4904        else {
4905            return Ok(false);
4906        };
4907        // A spread call has no tail form: `tail_call` takes its arguments one at a time off
4908        // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
4909        // as an ordinary call costs the one frame the optimisation was saving and keeps the
4910        // semantics — the alternative was reaching the spread expression below and failing
4911        // with "this expression form is not supported", which is how `return super.m(...a)`
4912        // stopped compiling. Checked before anything is emitted, because the decision cannot
4913        // be taken back once `super_base` or a `get_field2` is on the stack.
4914        if Self::has_spread(arguments) {
4915            return Ok(false);
4916        }
4917        let end = self.new_label();
4918        if let ExprKind::Member {
4919            object,
4920            property,
4921            optional: false,
4922        } = &callee.unparen().kind
4923        {
4924            // `super.m()` in tail position is still an ordinary method call with `this`
4925            // as the receiver; only the read of the method differs.
4926            if matches!(object.unparen().kind, ExprKind::SuperProp) {
4927                self.super_base();
4928                match property {
4929                    MemberProp::Ident(name) => self.emit(
4930                        Opcode::PushAtomValue,
4931                        &[Op::Atom(Atom::from_text(&name.name))],
4932                    ),
4933                    MemberProp::Computed(index) => self.expr(index)?,
4934                    MemberProp::Private(_) => return Ok(false),
4935                }
4936                self.emit(Opcode::GetArrayEl, &[]);
4937                for argument in arguments {
4938                    self.expr(argument)?;
4939                }
4940                self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
4941                self.place_label(end);
4942                return Ok(true);
4943            }
4944            self.chain_link(object, end)?;
4945            match property {
4946                MemberProp::Ident(name) => {
4947                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
4948                }
4949                MemberProp::Computed(index) => {
4950                    self.expr(index)?;
4951                    self.emit(Opcode::GetArrayEl2, &[]);
4952                }
4953                MemberProp::Private(_) => return Ok(false),
4954            }
4955            for argument in arguments {
4956                self.expr(argument)?;
4957            }
4958            self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
4959            self.place_label(end);
4960            return Ok(true);
4961        }
4962        self.chain_link(callee, end)?;
4963        for argument in arguments {
4964            self.expr(argument)?;
4965        }
4966        self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
4967        self.place_label(end);
4968        Ok(true)
4969    }
4970
4971    /// The `?.` guard: keep the value if it is neither null nor undefined,
4972    /// otherwise replace it with `undefined` and leave the whole chain.
4973    fn optional_guard(&mut self, end: Label) {
4974        let cont = self.new_label();
4975        self.emit(Opcode::Dup, &[]);
4976        self.emit(Opcode::IsUndefinedOrNull, &[]);
4977        self.emit_jump(Opcode::IfFalse, cont, &[]);
4978        self.emit(Opcode::Drop, &[]);
4979        self.emit(Opcode::Undefined, &[]);
4980        self.emit_jump(Opcode::Goto, end, &[]);
4981        self.place_label(cont);
4982    }
4983
4984    fn push_number(&mut self, value: f64) {
4985        // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
4986        // goes into the constant pool.
4987        if value == value.trunc() && value.abs() <= i32::MAX as f64 {
4988            let int = value as i32;
4989            if (-1..=7).contains(&int) {
4990                self.emit(Opcode::PushI32, &[Op::Int(int)]);
4991                return;
4992            }
4993            if (-128..=127).contains(&int) {
4994                self.emit(Opcode::PushI8, &[Op::Int(int)]);
4995                return;
4996            }
4997            if (-32768..=32767).contains(&int) {
4998                self.emit(Opcode::PushI16, &[Op::Int(int)]);
4999                return;
5000            }
5001            self.emit(Opcode::PushI32, &[Op::Int(int)]);
5002            return;
5003        }
5004        let index = self.push_constant(Constant::Number(value));
5005        self.emit(Opcode::PushConst, &[Op::Const(index)]);
5006    }
5007
5008    /// Push a `BigInt` literal.
5009    ///
5010    /// A value that fits an `i32` uses the immediate form, which is what the reference
5011    /// emits too; anything larger goes into the constant pool, because the operand of
5012    /// `push_bigint` is only four bytes wide.
5013    fn push_bigint(&mut self, digits: &str, radix: u32) {
5014        if radix == 10
5015            && let Ok(value) = digits.parse::<i64>()
5016            && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
5017        {
5018            self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
5019            return;
5020        }
5021        let index = self.push_constant(Constant::BigInt {
5022            digits: digits.to_string(),
5023            radix,
5024        });
5025        self.emit(Opcode::PushConst, &[Op::Const(index)]);
5026    }
5027
5028    fn push_string(&mut self, text: &Wtf8) {
5029        if text.is_empty() {
5030            self.emit(Opcode::PushEmptyString, &[]);
5031            return;
5032        }
5033        self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
5034    }
5035
5036    /// Name an anonymous function from the binding it is assigned to.
5037    ///
5038    /// `var f = function(){}` produces a function whose `name` is `f`, which the
5039    /// runtime cannot know without being told: the function object is created
5040    /// before the store. `set_name` carries the name across.
5041    fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
5042        if value.is_anonymous_function_definition() {
5043            self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
5044        }
5045    }
5046
5047    /// The same, for a computed key: the name comes from the value on the stack
5048    /// rather than from an atom, so a different instruction carries it.
5049    fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
5050        if value.is_anonymous_function_definition() {
5051            self.emit(Opcode::SetNameComputed, &[]);
5052        }
5053    }
5054
5055    /// Compile a function body that exists only in the compiler's head — a class's
5056    /// implicit constructor or its field initialiser.
5057    ///
5058    /// Everything structural is the same as a written function: a fresh `FnState`, its
5059    /// own body block, and resolution while the frame is still on the stack. Only the
5060    /// statements differ.
5061    fn compile_synthetic_function(
5062        &mut self,
5063        name: &str,
5064        strict: bool,
5065        span: Span,
5066        body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
5067    ) -> Result<CompiledFunction, SyntaxError> {
5068        let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
5069        state.strict = strict;
5070        state.created_in_block = self.cur().current_block;
5071        state.with_names = self.cur().with_names.clone();
5072        state.line = span.start.line;
5073        state.column = span.start.column;
5074        let depth = self.stack.len();
5075        self.stack.push(state);
5076        let body_key = span.start.offset as u64;
5077        self.push_block(body_key, NO_PARENT);
5078        self.state().body_block = body_key;
5079        let result = (|| {
5080            self.emit_scope_enter(body_key);
5081            body(self)?;
5082            if self.end_is_reachable() {
5083                self.emit(Opcode::ReturnUndef, &[]);
5084            }
5085            Ok(())
5086        })();
5087        if result.is_err() {
5088            self.stack.truncate(depth);
5089            return result.map(|()| unreachable!());
5090        }
5091        Ok(self.finish_current())
5092    }
5093
5094    /// The implicit return of a class constructor.
5095    ///
5096    /// A constructor that falls off the end initialises its instance fields first, and a
5097    /// derived one returns `this` — which is what makes `new D()` the object `super()`
5098    /// built rather than `undefined`.
5099    fn emit_class_constructor_tail(&mut self) {
5100        match self.cur().ctor_kind {
5101            CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
5102            // Nothing to install: a base constructor did it in its prologue and a derived
5103            // one at each `super()` site, which is where `this` first exists.
5104            CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
5105            CtorKind::Derived => {
5106                // `get_loc_check` rather than `get_loc`: reaching the end without ever
5107                // running `super()` is a ReferenceError, not `undefined`.
5108                self.emit_var(VarAction::Get, "this");
5109                self.emit(Opcode::Return, &[]);
5110            }
5111        }
5112    }
5113
5114    /// `yield expr` / `yield* expr`.
5115    ///
5116    /// The suspension itself is one instruction: the value is on the stack, `yield` hands
5117    /// it to the caller and parks the frame. On resume the stack holds the value the
5118    /// caller passed *and* a "magic" number saying which method resumed it — `next`
5119    /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
5120    /// `if_false <continue>` asks whether this was an ordinary `next`:
5121    ///
5122    /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
5123    /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
5124    ///   and uses the value sitting under the magic number.
5125    ///
5126    /// A `throw` never reaches here: the interpreter unwinds instead (see
5127    /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
5128    fn yield_expression(
5129        &mut self,
5130        argument: Option<&Expr>,
5131        delegate: bool,
5132    ) -> Result<(), SyntaxError> {
5133        if delegate {
5134            return self.yield_star(argument);
5135        }
5136        // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
5137        // does the same for the `return(v)` that can resume it — which is why an async
5138        // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
5139        // generator's is just `yield`.
5140        let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
5141        match argument {
5142            Some(value) => self.expr(value)?,
5143            None => self.emit(Opcode::Undefined, &[]),
5144        }
5145        if is_async {
5146            self.emit(Opcode::Await, &[]);
5147            self.state().has_await = true;
5148        }
5149        self.emit(Opcode::Yield, &[]);
5150        let resume = self.new_label();
5151        self.emit_jump(Opcode::IfFalse, resume, &[]);
5152        // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
5153        // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
5154        // finished the generator and never ran the `finally`.
5155        if is_async {
5156            self.emit(Opcode::Await, &[]);
5157        }
5158        self.emit_unwind_for_return(true);
5159        self.emit(Opcode::ReturnAsync, &[]);
5160        self.place_label(resume);
5161        // Nothing is emitted here: the value the caller passed to `next` *is* the value
5162        // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
5163        // it through the ordinary expression-statement discard.
5164        Ok(())
5165    }
5166
5167    /// `yield* iterable`.
5168    ///
5169    /// The shape is the reference's, and it is a fall-through chain rather than a
5170    /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
5171    /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
5172    /// the inner iterator and finishes, `throw` forwards the exception into it and
5173    /// continues only if it has a `throw` method.
5174    ///
5175    /// The stack is `iter next catch value` throughout, `catch` being the offset
5176    /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
5177    fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
5178        match argument {
5179            Some(value) => self.expr(value)?,
5180            // The parser rejects a bare `yield*`, so this is unreachable in practice.
5181            None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
5182        }
5183        // `for await of` is the same protocol as `for of` with two differences that matter
5184        // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
5185        // every `next()` result is a promise the delegate has to await.
5186        let is_async = self.cur().kind.is_async();
5187        self.emit(
5188            if is_async {
5189                Opcode::ForAwaitOfStart
5190            } else {
5191                Opcode::ForOfStart
5192            },
5193            &[],
5194        );
5195        self.emit(Opcode::Drop, &[]);
5196        self.emit(Opcode::Undefined, &[]);
5197        self.emit(Opcode::Undefined, &[]);
5198        let next = self.new_label();
5199        let resume = self.new_label();
5200        let finished = self.new_label();
5201        let rethrow = self.new_label();
5202        let throw_no_method = self.new_label();
5203        let done = self.new_label();
5204        self.place_label(next);
5205        self.emit(Opcode::IteratorNext, &[]);
5206        if is_async {
5207            self.emit(Opcode::Await, &[]);
5208            self.state().has_await = true;
5209        }
5210        self.emit(Opcode::IteratorCheckObject, &[]);
5211        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5212        self.emit_jump(Opcode::IfTrue, done, &[]);
5213        // The suspension. `resume` is both the label the return path jumps back to in order
5214        // to yield one more value and where the caller's answer arrives, as the value
5215        // followed by the magic number.
5216        //
5217        // The two forms differ in what they hand the suspension: `yield_star` takes the
5218        // result object itself, `async_yield_star` takes `.value`, because an async
5219        // generator awaits and re-wraps whatever it yields.
5220        self.place_label(resume);
5221        if is_async {
5222            self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5223            self.emit(Opcode::AsyncYieldStar, &[]);
5224        } else {
5225            self.emit(Opcode::YieldStar, &[]);
5226        }
5227        self.emit(Opcode::Dup, &[]);
5228        self.emit_jump(Opcode::IfTrue, rethrow, &[]);
5229        self.emit(Opcode::Drop, &[]);
5230        self.emit_jump(Opcode::Goto, next, &[]);
5231
5232        // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
5233        self.place_label(rethrow);
5234        self.emit(Opcode::PushI32, &[Op::Int(2)]);
5235        self.emit(Opcode::StrictEq, &[]);
5236        self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
5237        // A `return` closes the inner iterator; if it had none, the delegate simply
5238        // finishes with the requested value. In an async generator both the call and its
5239        // result are awaited, because the inner `return` may itself be async.
5240        if is_async {
5241            self.emit(Opcode::Await, &[]);
5242        }
5243        self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
5244        self.emit_jump(Opcode::IfTrue, finished, &[]);
5245        if is_async {
5246            self.emit(Opcode::Await, &[]);
5247        }
5248        self.emit(Opcode::IteratorCheckObject, &[]);
5249        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5250        self.emit_jump(Opcode::IfFalse, resume, &[]);
5251        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5252        self.place_label(finished);
5253        self.emit(Opcode::Nip, &[]);
5254        self.emit(Opcode::Nip, &[]);
5255        self.emit(Opcode::Nip, &[]);
5256        // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
5257        // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
5258        // awaits the value in an async generator and then runs the same `finally`/iterator
5259        // unwinding a written `return` would. Skipping the unwinding made
5260        // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
5261        if is_async {
5262            self.emit(Opcode::Await, &[]);
5263        }
5264        self.emit_unwind_for_return(true);
5265        self.emit(Opcode::ReturnAsync, &[]);
5266
5267        // `throw(e)`: forward it into the inner iterator.
5268        self.place_label(throw_no_method);
5269        self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
5270        let no_throw = self.new_label();
5271        self.emit_jump(Opcode::IfTrue, no_throw, &[]);
5272        if is_async {
5273            self.emit(Opcode::Await, &[]);
5274        }
5275        self.emit(Opcode::IteratorCheckObject, &[]);
5276        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5277        self.emit_jump(Opcode::IfFalse, resume, &[]);
5278        self.emit_jump(Opcode::Goto, done, &[]);
5279        // No `throw` method: close the iterator, then report the spec's TypeError. The
5280        // `if_true` before the `await` is the reference's shape — the flag it consumes is
5281        // what `iterator_call` leaves behind, and a close that *did* find no `return`
5282        // method has nothing to await.
5283        self.place_label(no_throw);
5284        self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
5285        let no_close = self.new_label();
5286        self.emit_jump(Opcode::IfTrue, no_close, &[]);
5287        if is_async {
5288            self.emit(Opcode::Await, &[]);
5289        }
5290        self.place_label(no_close);
5291        self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
5292
5293        // The inner iterator finished: the delegate's value is the `yield*` expression's
5294        // value, so it is left on the stack for whatever consumes it.
5295        self.place_label(done);
5296        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5297        self.emit(Opcode::Nip, &[]);
5298        self.emit(Opcode::Nip, &[]);
5299        self.emit(Opcode::Nip, &[]);
5300        Ok(())
5301    }
5302
5303    /// `await expr`: exactly one instruction.
5304    ///
5305    /// No resume-magic branch follows it. The reference's `await` leaves a single value
5306    /// on the stack and completion is signalled by the `return_async` at the end of the
5307    /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
5308    /// reference never emits, and a `for await` loop — which reaches `await` through the
5309    /// same opcode — would then spill a value the loop's unpacking does not expect.
5310    fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
5311        self.expr(argument)?;
5312        self.emit(Opcode::Await, &[]);
5313        self.state().has_await = true;
5314        Ok(())
5315    }
5316
5317    /// The `super` base: the receiver followed by the home object's prototype.
5318    ///
5319    /// Everything `super` does needs both. A *read* starts at the prototype but reports
5320    /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
5321    /// prototype but calls it with the receiver.
5322    fn super_base(&mut self) {
5323        self.this_expression();
5324        self.home_object();
5325        self.emit(Opcode::GetSuper, &[]);
5326    }
5327
5328    /// `[[HomeObject]]` as `super` sees it.
5329    ///
5330    /// A method, a constructor and a field initialiser each carry one — `set_home_object`
5331    /// put it there — so for them the special object *is* the answer. An arrow and a
5332    /// static block have none: they read the enclosing function's, which has to be
5333    /// materialised into a local, exactly as `this` is for an arrow.
5334    ///
5335    /// The name matches what the reference stores, so the disassembly agrees; it is not a
5336    /// name any program can write.
5337    fn home_object(&mut self) {
5338        if !self.cur().is_arrow {
5339            self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
5340            return;
5341        }
5342        if let Some(target) = self.enclosing_function() {
5343            self.state_at(target).needs_home_object_local = true;
5344            self.declare_at(target, HOME_OBJECT);
5345        }
5346        self.emit_var(VarAction::Get, HOME_OBJECT);
5347    }
5348
5349    /// `super(args)`: construct the parent class and adopt the result as `this`.
5350    ///
5351    /// The parent is the prototype of the constructor that is running, which is exactly
5352    /// what `extends` set up. `new.target` is passed through unchanged so that
5353    /// `new.target` inside the parent is the class actually being constructed.
5354    fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5355        self.active_func_expression();
5356        self.emit(Opcode::GetSuper, &[]);
5357        self.new_target_expression();
5358        if Self::has_spread(arguments) {
5359            self.argument_array(arguments)?;
5360            self.emit(Opcode::Apply, &[Op::Int(1)]);
5361        } else {
5362            for argument in arguments {
5363                self.expr(argument)?;
5364            }
5365            self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
5366        }
5367        // The value stays on the stack: `super()` is an expression, and a derived
5368        // constructor's `this` may only be initialised once.
5369        self.emit(Opcode::Dup, &[]);
5370        self.emit_var(VarAction::PutInitChecked, "this");
5371        // Instance fields are installed here, not at the top of the body: a derived
5372        // constructor has no `this` to install them on until `super()` returns. The
5373        // reference emits the same call at every `super()` site.
5374        self.call_field_initialiser();
5375        Ok(())
5376    }
5377
5378    /// `this` as a local, which every class constructor and field initialiser needs.
5379    ///
5380    /// The reference materialises the receiver into a local rather than reading
5381    /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
5382    /// and a field initialiser has to see the final value.
5383    fn begin_this_local(&mut self) {
5384        self.declare_hidden_local("this", VarKind::Normal);
5385        self.emit(Opcode::PushThis, &[]);
5386        self.emit_var(VarAction::Put, "this");
5387        // The store is already at the top of the body, so `provide_this_local` has
5388        // nothing left to prepend. Without this the initialiser ended up with
5389        // `push_this; put_loc0 this` twice whenever the class also held a field
5390        // initialiser whose body read `this` through an arrow.
5391        self.state().has_this_prologue = true;
5392    }
5393
5394    /// Compile a constructor the class wrote.
5395    ///
5396    /// The flags have to be in place before the body is compiled, but
5397    /// `compile_function_with_name` creates its own state — so the caller's state is
5398    /// marked instead and the new one inherits it. That is the same trick the parameter
5399    /// prologue uses, and it keeps one code path for both.
5400    fn compile_class_constructor(
5401        &mut self,
5402        func: &ast::Function,
5403        has_heritage: bool,
5404    ) -> Result<CompiledFunction, SyntaxError> {
5405        let saved = self.cur().ctor_kind;
5406        self.state().class_ctor_pending = Some(if has_heritage {
5407            CtorKind::Derived
5408        } else {
5409            CtorKind::Base
5410        });
5411        let result = self.compile_function_with_name(func, false);
5412        self.state().ctor_kind = saved;
5413        self.state().class_ctor_pending = None;
5414        result
5415    }
5416
5417    /// The constructor a class gets when it does not declare one.
5418    ///
5419    /// A base class's is empty; a derived class's forwards every argument to the parent
5420    /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
5421    /// instance field initialiser afterwards when the class has fields, which is why the
5422    /// initialiser is captured rather than inlined.
5423    fn compile_implicit_constructor(
5424        &mut self,
5425        class: &Class,
5426        has_heritage: bool,
5427    ) -> Result<CompiledFunction, SyntaxError> {
5428        self.compile_synthetic_function(
5429            "",
5430            true,
5431            Span::new(class.body_end, class.body_end),
5432            |compiler| {
5433                if has_heritage {
5434                    // A derived constructor's `this` does not exist until `super()` returns,
5435                    // so it starts in the dead zone and `init_ctor` fills it.
5436                    compiler.declare("this", VarDef::lexical("this"));
5437                    compiler.emit(
5438                        Opcode::SetLocUninitialized,
5439                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5440                    );
5441                    compiler.emit(Opcode::InitCtor, &[]);
5442                    compiler.emit(
5443                        Opcode::PutLocCheckInit,
5444                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
5445                    );
5446                } else {
5447                    compiler.begin_this_local();
5448                    compiler.emit(Opcode::CheckCtor, &[]);
5449                }
5450                compiler.call_field_initialiser();
5451                // A derived constructor returns `this`, the object `super()` built. Without
5452                // this the implicit constructor fell through to `return_undef`, and `new B()`
5453                // handed back the empty object `construct` had made instead of the one the
5454                // parent constructor initialised.
5455                if has_heritage {
5456                    compiler.emit_var(VarAction::Get, "this");
5457                    compiler.emit(Opcode::Return, &[]);
5458                }
5459                Ok(())
5460            },
5461        )
5462    }
5463
5464    /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
5465    ///
5466    /// A class with no instance fields leaves the binding `undefined`, and calling it
5467    /// would throw; the reference emits the same guard rather than branching at compile
5468    /// time because a class can be extended by a subclass whose fields still have to run.
5469    fn call_field_initialiser(&mut self) {
5470        let skip = self.new_label();
5471        self.emit_var(VarAction::Get, "<class_fields_init>");
5472        self.emit(Opcode::Dup, &[]);
5473        self.emit_jump(Opcode::IfFalse, skip, &[]);
5474        self.emit_var(VarAction::Get, "this");
5475        self.emit(Opcode::Swap, &[]);
5476        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
5477        self.place_label(skip);
5478        self.emit(Opcode::Drop, &[]);
5479    }
5480
5481    /// The function that defines one class's fields on `this`, and runs its static blocks.
5482    ///
5483    /// `define_field` rather than `put_field`: a field is an own property created
5484    /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
5485    /// `x = 1` field must not call the setter.
5486    ///
5487    /// One function serves the whole class: it is called once per instance (or once, for
5488    /// the static half) and walks the members in source order. Static blocks are compiled
5489    /// into the same function because they *are* part of the same sequence — `static a =
5490    /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
5491    /// different values, so the two kinds cannot be split apart.
5492    fn compile_field_initialiser(
5493        &mut self,
5494        items: &[StaticInitItem<'_>],
5495        span: Span,
5496        instance: bool,
5497        add_brand: bool,
5498    ) -> Result<CompiledFunction, SyntaxError> {
5499        self.compile_synthetic_function("", true, span, |compiler| {
5500            if instance {
5501                // An instance initialiser always carries a `<home_object>` local, because the
5502                // brand block below reads it — even when that block turns out to be dead. The
5503                // reference has the same artefact, and the store is visible in its dump.
5504                let current = compiler.stack.len() - 1;
5505                compiler.stack[current].needs_home_object_local = true;
5506            }
5507            compiler.begin_this_local();
5508            if instance {
5509                // `this` gets the brand the prototype created, before any field is defined —
5510                // which is what makes `#m()` usable from inside a field initialiser.
5511                //
5512                // The reference always emits `push_false; if_false L; this; home; add_brand;
5513                // L:` and patches the `push_false` to `push_true` from the class parse when
5514                // the class has private methods; either way the branch folds, but the *mark*
5515                // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
5516                // `this` local from being fused into a `set_loc`.
5517                let skip = compiler.new_label();
5518                if add_brand {
5519                    compiler.emit(Opcode::PushTrue, &[]);
5520                } else {
5521                    compiler.emit(Opcode::PushFalse, &[]);
5522                }
5523                compiler.emit_jump(Opcode::IfFalse, skip, &[]);
5524                compiler.emit_var(VarAction::Get, "this");
5525                compiler.emit_var(VarAction::Get, HOME_OBJECT);
5526                compiler.emit(Opcode::AddBrand, &[]);
5527                compiler.place_label(skip);
5528            }
5529            for item in items {
5530                match item {
5531                    StaticInitItem::Field(key, value) => {
5532                        // A private field is *defined*, not assigned: `define_private_field`
5533                        // reads `obj symbol value`, and its point is that it fails on a
5534                        // receiver that is not this class's — which `put_field` would not.
5535                        //
5536                        // The three shapes are the reference's: `define_field <atom>` for a
5537                        // static name, `define_array_el` for a key that is only known at run
5538                        // time (`obj key value`), `define_private_field` for `#x`, and a
5539                        // computed key is read from its binding rather than recomputed.
5540                        compiler.emit_var(VarAction::Get, "this");
5541                        match key {
5542                            FieldKey::Private(binding) | FieldKey::Computed(binding) => {
5543                                compiler.emit_var(VarAction::Get, binding);
5544                            }
5545                            FieldKey::Literal(_) => {}
5546                        }
5547                        match value {
5548                            Some(value) => compiler.expr(value)?,
5549                            None => compiler.emit(Opcode::Undefined, &[]),
5550                        }
5551                        match key {
5552                            FieldKey::Literal(literal) => {
5553                                let text = compiler.property_key_text(literal, span)?;
5554                                compiler
5555                                    .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
5556                            }
5557                            FieldKey::Computed(_) => {
5558                                compiler.emit(Opcode::DefineArrayEl, &[]);
5559                                // `define_array_el` leaves `obj key`; the key is consumed by
5560                                // the copy the pattern machinery wants, so both go.
5561                                compiler.emit(Opcode::Drop, &[]);
5562                            }
5563                            FieldKey::Private(_) => {
5564                                compiler.emit(Opcode::DefinePrivateField, &[]);
5565                            }
5566                        }
5567                        compiler.emit(Opcode::Drop, &[]);
5568                    }
5569                    StaticInitItem::Block { body, body_start } => {
5570                        let block = compiler.compile_static_block(body, *body_start)?;
5571                        let index = compiler.push_constant(Constant::Function(Box::new(block)));
5572                        // `this fclosure`, so `call_method` finds the receiver below the
5573                        // callee: the block runs with `this` bound to the class.
5574                        compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
5575                        compiler.emit_var(VarAction::Get, "this");
5576                        compiler.emit(Opcode::Swap, &[]);
5577                        compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
5578                        // Nothing the block evaluates is wanted; its effects are the point.
5579                        compiler.emit(Opcode::Drop, &[]);
5580                    }
5581                }
5582            }
5583            Ok(())
5584        })
5585    }
5586
5587    /// Compile a `static { … }` body into the function the class calls for it.
5588    ///
5589    /// Shaped like an arrow, because that is the one function form with no `this`,
5590    /// `new.target` or `arguments` of its own: all three reach the enclosing static
5591    /// initialiser, and through it the class. `arguments` never gets that far — the parser
5592    /// rejects the reference — but `this` and `super` both depend on it.
5593    ///
5594    /// The body is hoisted like a function body's, because the reference parses it as one:
5595    /// `var` inside a block is a local of the block's function, not of whatever encloses
5596    /// the class.
5597    fn compile_static_block(
5598        &mut self,
5599        body: &[Stmt],
5600        body_start: Position,
5601    ) -> Result<CompiledFunction, SyntaxError> {
5602        let mut state = FnState::new(String::new(), FunctionKind::Normal);
5603        // Class bodies are strict, so a static block is too.
5604        state.strict = true;
5605        // The one property that makes this an arrow: nothing of its own to bind `this` to,
5606        // so `this` and `super` come from the initialiser that calls it.
5607        state.is_arrow = true;
5608        state.created_in_block = self.cur().current_block;
5609        state.with_names = self.cur().with_names.clone();
5610        state.line = body_start.line;
5611        state.column = body_start.column;
5612        let depth = self.stack.len();
5613        self.stack.push(state);
5614        let body_key = body_start.offset as u64;
5615        self.push_block(body_key, NO_PARENT);
5616        self.state().body_block = body_key;
5617        let result = (|| {
5618            self.hoist(body, body_key)?;
5619            self.emit_scope_enter(body_key);
5620            for statement in body {
5621                self.stmt(statement)?;
5622            }
5623            if self.end_is_reachable() {
5624                self.emit(Opcode::ReturnUndef, &[]);
5625            }
5626            Ok(())
5627        })();
5628        if result.is_err() {
5629            self.stack.truncate(depth);
5630            return result.map(|()| unreachable!());
5631        }
5632        Ok(self.finish_current())
5633    }
5634
5635    /// Compile a class, leaving the constructor on the stack when `keep`.
5636    ///
5637    /// The shape follows the reference: the class body is its own scope holding the
5638    /// class's *inner* name as a `const` — which is what lets a method refer to the
5639    /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
5640    /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
5641    /// on the top of the stack: the prototype for instance members, the constructor
5642    /// itself for `static` ones, which is why a static member costs an extra `swap`.
5643    fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
5644        let parent_block = self.cur().current_block;
5645        let key = class.span.start.offset as u64;
5646        self.push_block(key, parent_block);
5647        let name = class.name.as_ref().map(|ident| ident.name.clone());
5648        // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
5649        // resolves `E` without a global lookup. An *unnamed* class expression has no such
5650        // binding, and `define_class` is handed the empty name.
5651        if let Some(name) = &name {
5652            self.declare(name, VarDef::constant(name.clone()));
5653        }
5654        self.emit_scope_enter(key);
5655
5656        // The heritage clause is evaluated outside the class's own scope: it cannot see
5657        // the class binding it is about to initialise.
5658        let saved_block = self.cur().current_block;
5659        self.state().current_block = parent_block;
5660        match &class.super_class {
5661            Some(parent) => self.expr(parent)?,
5662            None => self.emit(Opcode::Undefined, &[]),
5663        }
5664        self.state().current_block = saved_block;
5665        let has_heritage = class.super_class.is_some();
5666
5667        // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
5668        // lands after the heritage's code — which is where the reference puts it, because it
5669        // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
5670        // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
5671        // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
5672        // came out in the opposite order from the reference's.
5673        //
5674        // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
5675        // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
5676        // a const accepts — so the old comment's worry ("a const would refuse the second
5677        // store") did not apply: there is no second store.
5678        // Every `#name` the class declares gets a `const` binding in the class scope, and so
5679        // does every computed field key. That is how the reference does it
5680        // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
5681        // what makes a private name resolve like any other class-scope variable — including
5682        // through a nested function's closure — while remaining invisible outside.
5683        //
5684        // All of them are declared *before* `<class_fields_init>`, in member order, because
5685        // that is when the reference's parser creates them.
5686        let plan = ClassPlan::build(class);
5687        // The body's private names are visible from here to the end of the class, and shadow
5688        // any outer class's of the same spelling. Pushed *before* the constructor is compiled
5689        // — it is compiled first because `define_class` consumes it, but its body can name
5690        // `#x` like any other member's.
5691        self.private_scopes.push(plan.uses.clone());
5692        let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
5693        for binding in &plan.bindings {
5694            class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
5695        }
5696        let fci = self.declare(
5697            "<class_fields_init>",
5698            VarDef::constant("<class_fields_init>"),
5699        );
5700        // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
5701        // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
5702        // members' bindings follow in reverse.
5703        self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
5704        for slot in class_slots.iter().rev() {
5705            self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
5706        }
5707
5708        // The constructor is compiled before `define_class` because that instruction
5709        // consumes it; a class without one gets the implicit version.
5710        let constructor = class.elements.iter().find_map(|element| match element {
5711            ClassElement::Method {
5712                kind: MethodKind::Constructor,
5713                func,
5714                ..
5715            } => Some(&**func),
5716            _ => None,
5717        });
5718        // A constructor is compiled differently from a method: it owns `this`. The flags
5719        // go on the *enclosing* state because a constructor is a nested function and
5720        // `compile_function_with_name` starts a fresh one.
5721        let ctor = match constructor {
5722            Some(func) => self.compile_class_constructor(func, has_heritage)?,
5723            None => self.compile_implicit_constructor(class, has_heritage)?,
5724        };
5725        // A closure, not the bare constant: the constructor captures
5726        // `<class_fields_init>`, which is only filled after `define_class` has run, so it
5727        // has to hold the cell rather than a copy of its value.
5728        //
5729        // The pool slot is left unassigned for now, because the reference gives the
5730        // constructor the *last* index of the members' range: `js_parse_class` emits a
5731        // `push_const` whose operand is patched at the end of the class parse, after every
5732        // method has taken a slot. Emitting the members first and the constant second is how
5733        // the numbering comes out the same; the instruction itself stays where it is.
5734        let ctor_insn = self.cur().insns.len();
5735        self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
5736        let flags = if has_heritage { 1 } else { 0 };
5737        self.emit(
5738            Opcode::DefineClass,
5739            &[
5740                Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
5741                Op::Int(flags),
5742            ],
5743        );
5744
5745        // Instance fields and static fields are two different functions: the first runs
5746        // per instance from the constructor, the second runs once, here.
5747        let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
5748        let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
5749        for (index, element) in class.elements.iter().enumerate() {
5750            match element {
5751                ClassElement::Method {
5752                    key: member_key,
5753                    is_static,
5754                    kind,
5755                    func,
5756                    span,
5757                } => {
5758                    if *kind == MethodKind::Constructor {
5759                        continue;
5760                    }
5761                    // `static(x)` is a *method* named `static`, not a static method; the
5762                    // parser already decided which by putting it in `kind`.
5763                    if *is_static {
5764                        self.emit(Opcode::Swap, &[]);
5765                    }
5766                    // A computed key is evaluated *here*, before the method's closure
5767                    // exists, and stays under it: `define_method_computed` pops
5768                    // `function, key, object`, so the stack has to read
5769                    // `[class, prototype, key, function]`. Evaluating the key after the
5770                    // `fclosure` and swapping the two put the prototype *below* the
5771                    // closure, which defined the method on the function and lost the
5772                    // prototype: `class C { [k]() {} }` left `C` undefined. The order is
5773                    // also the spec's — a class body evaluates every element's name before
5774                    // that element's function.
5775                    if let PropName::Computed(key) = member_key {
5776                        self.expr(key)?;
5777                    }
5778                    let function = self.compile_function_with_name(func, true)?;
5779                    let index = self.push_constant(Constant::Function(Box::new(function)));
5780                    self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5781                    match member_key {
5782                        // A private method is not a property of the prototype: it is a
5783                        // closure in the class scope, which is why nothing outside can reach
5784                        // it and why a use site has to brand-check. `set_name` gives the
5785                        // function its `name` (`#m`), which an accessor does not get — the
5786                        // reference leaves that commented out.
5787                        PropName::Private(ident) => {
5788                            let name = format!("#{}", ident.name);
5789                            // `set_home_object` first: the brand check reads the function's
5790                            // home object, and for a method that is the prototype.
5791                            self.emit(Opcode::SetHomeObject, &[]);
5792                            let binding = if *kind == MethodKind::Set {
5793                                format!("{name}<set>")
5794                            } else {
5795                                name.clone()
5796                            };
5797                            if *kind == MethodKind::Method {
5798                                self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
5799                            }
5800                            self.emit_var(VarAction::PutInit, &binding);
5801                        }
5802                        PropName::Computed(_) => {
5803                            self.emit(
5804                                Opcode::DefineMethodComputed,
5805                                &[Op::Int(class_method_flags(*kind))],
5806                            );
5807                        }
5808                        PropName::Literal(literal) => {
5809                            let text = self.property_key_text(literal, *span)?;
5810                            self.emit(
5811                                Opcode::DefineMethod,
5812                                &[
5813                                    Op::Atom(Atom::from_wtf8(&text)),
5814                                    Op::Int(class_method_flags(*kind)),
5815                                ],
5816                            );
5817                        }
5818                    }
5819                    if *is_static {
5820                        self.emit(Opcode::Swap, &[]);
5821                    }
5822                }
5823                ClassElement::Field {
5824                    key: field_key,
5825                    is_static,
5826                    value,
5827                    ..
5828                } => {
5829                    // A private field's *symbol* is created here, at the member, and stored
5830                    // in its binding: the field's property is keyed by it, so it has to exist
5831                    // before any initialiser runs, and a fresh one per class body is what
5832                    // makes two classes that both write `#x` independent.
5833                    //
5834                    // A computed key is evaluated once, here, and `to_propkey`'d once — a key
5835                    // whose `toString` has a side effect must not run again per instance.
5836                    let key = match field_key {
5837                        PropName::Private(ident) => {
5838                            let binding = format!("#{}", ident.name);
5839                            if *is_static {
5840                                self.emit(Opcode::Swap, &[]);
5841                            }
5842                            self.emit(
5843                                Opcode::PrivateSymbol,
5844                                &[Op::Atom(Atom::from_text(&binding))],
5845                            );
5846                            self.emit_var(VarAction::PutInit, &binding);
5847                            if *is_static {
5848                                self.emit(Opcode::Swap, &[]);
5849                            }
5850                            FieldKey::Private(binding)
5851                        }
5852                        PropName::Computed(expression) => {
5853                            let binding = plan
5854                                .computed
5855                                .get(&index)
5856                                .cloned()
5857                                .expect("every computed key got a binding");
5858                            if *is_static {
5859                                self.emit(Opcode::Swap, &[]);
5860                            }
5861                            self.expr(expression)?;
5862                            self.emit(Opcode::ToPropkey, &[]);
5863                            self.emit_var(VarAction::PutInit, &binding);
5864                            if *is_static {
5865                                self.emit(Opcode::Swap, &[]);
5866                            }
5867                            FieldKey::Computed(binding)
5868                        }
5869                        PropName::Literal(literal) => FieldKey::Literal(literal),
5870                    };
5871                    if *is_static {
5872                        static_items.push(StaticInitItem::Field(key, value.as_deref()));
5873                    } else {
5874                        instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
5875                    }
5876                }
5877                ClassElement::StaticBlock {
5878                    body, body_start, ..
5879                } => static_items.push(StaticInitItem::Block {
5880                    body,
5881                    body_start: *body_start,
5882                }),
5883            }
5884        }
5885
5886        // Now that every member has its slot, the constructor can have the next one and the
5887        // `fclosure` above can name it.
5888        let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
5889        match self.state().insns.get_mut(ctor_insn) {
5890            Some(Insn::Fixed { operands, .. }) => {
5891                operands[0] = Op::Const(ctor_index);
5892            }
5893            // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
5894            // loudly beats emitting a `fclosure` of slot 4294967295.
5895            _ => {
5896                return Err(SyntaxError::new(
5897                    "the class constructor's fclosure went missing",
5898                    class.span,
5899                ));
5900            }
5901        }
5902
5903        // The instance brand: a symbol created once on the prototype, which every instance
5904        // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
5905        // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
5906        // copy is created. The prototype is on top of the stack at this point.
5907        if plan.instance_brand {
5908            self.emit(Opcode::Dup, &[]);
5909            self.emit(Opcode::Null, &[]);
5910            self.emit(Opcode::Swap, &[]);
5911            self.emit(Opcode::AddBrand, &[]);
5912        }
5913
5914        // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
5915        // class has no instance fields. The constructor calls it only when it is defined.
5916        //
5917        // A class with private *methods* but no fields still needs one, because adding the
5918        // brand to each new instance is the initialiser's job.
5919        if instance_fields.is_empty() && !plan.instance_brand {
5920            self.emit(Opcode::Undefined, &[]);
5921        } else {
5922            let initialiser = self.compile_field_initialiser(
5923                &instance_fields,
5924                class.span,
5925                true,
5926                plan.instance_brand,
5927            )?;
5928            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
5929            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5930            // `set_home_object` reads `obj func`, so the prototype stays where it is.
5931            self.emit(Opcode::SetHomeObject, &[]);
5932        }
5933        self.emit_var(VarAction::PutInit, "<class_fields_init>");
5934        // The prototype has done its job: every instance member is defined on it. What
5935        // is left under it is the constructor.
5936        self.emit(Opcode::Drop, &[]);
5937
5938        // The static brand, for `static #m() {}`: same opcode, but the home object is the
5939        // constructor itself, so the symbol lands on the class and the class carries it.
5940        if plan.static_brand {
5941            self.emit(Opcode::Dup, &[]);
5942            self.emit(Opcode::Dup, &[]);
5943            self.emit(Opcode::AddBrand, &[]);
5944        }
5945
5946        // The class binding is initialised *before* static fields run, so a static field
5947        // can refer to the class by name (`static y = S.x`).
5948        // `set_loc` leaves the constructor on the stack, which is what the static field
5949        // call and the outer store both consume.
5950        //
5951        // Only when there *is* such a binding: an anonymous class expression declares no
5952        // class-scope name, and asking for one by the empty string resolved to nothing —
5953        // which made `var x = class {}` assign `undefined` and put a bogus global store in
5954        // the instruction stream.
5955        if let Some(name) = &name {
5956            self.emit_var(VarAction::SetInit, name);
5957        }
5958        if !static_items.is_empty() {
5959            // The static half has no brand prologue of its own: the constructor got its
5960            // brand above, before this runs.
5961            let initialiser =
5962                self.compile_field_initialiser(&static_items, class.span, false, false)?;
5963            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
5964            self.emit(Opcode::Dup, &[]);
5965            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5966            self.emit(Opcode::SetHomeObject, &[]);
5967            self.emit(Opcode::CallMethod, &[Op::Int(0)]);
5968            self.emit(Opcode::Drop, &[]);
5969        }
5970        // The body is over, and with it this class's private names.
5971        let _ = self.private_scopes.pop();
5972        self.emit_scope_leave(key);
5973        self.state().current_block = parent_block;
5974        if keep {
5975            // A class *expression* is its own value; the class-scope binding was only
5976            // ever an alias for it.
5977            return Ok(());
5978        }
5979        // A declaration stores into the binding the enclosing statement declared.
5980        self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
5981        Ok(())
5982    }
5983
5984    fn push_this(&mut self) {
5985        self.emit(Opcode::PushThis, &[]);
5986    }
5987
5988    /// `this`, which an arrow does not have of its own.
5989    ///
5990    /// The reference gives the enclosing function a local named `this`, initialised from
5991    /// `push_this` at the top of its body, and the arrow then reads it as a captured
5992    /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
5993    /// the arrow is called with none.
5994    fn this_expression(&mut self) {
5995        // In a class constructor `this` is a local: a derived constructor only gets one
5996        // when `super()` returns, and reading the raw receiver would give the *outer*
5997        // one instead.
5998        if self.cur().ctor_kind != CtorKind::None {
5999            self.emit_var(VarAction::Get, "this");
6000            return;
6001        }
6002        if !self.cur().is_arrow {
6003            self.push_this();
6004            return;
6005        }
6006        if let Some(target) = self.enclosing_function() {
6007            self.state_at(target).needs_this_local = true;
6008            self.declare_at(target, "this");
6009        }
6010        self.emit_var(VarAction::Get, "this");
6011    }
6012
6013    /// `new.target`, which an arrow likewise does not own.
6014    fn new_target_expression(&mut self) {
6015        if !self.cur().is_arrow {
6016            self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
6017            return;
6018        }
6019        if let Some(target) = self.enclosing_function() {
6020            self.state_at(target).needs_new_target_local = true;
6021            self.declare_at(target, NEW_TARGET);
6022        }
6023        self.emit_var(VarAction::Get, NEW_TARGET);
6024    }
6025
6026    /// `this.active_func`: the function `super()` resolves against.
6027    ///
6028    /// In a constructor or a method that is the function being run, so the special object
6029    /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
6030    /// a closure variable — see [`FnState::needs_active_func_local`].
6031    fn active_func_expression(&mut self) {
6032        if !self.cur().is_arrow {
6033            self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
6034            return;
6035        }
6036        if let Some(target) = self.enclosing_function() {
6037            self.state_at(target).needs_active_func_local = true;
6038            self.declare_at(target, ACTIVE_FUNC);
6039        }
6040        self.emit_var(VarAction::Get, ACTIVE_FUNC);
6041    }
6042
6043    /// Give the function a local `<active_func>`, for an arrow inside it to capture.
6044    fn provide_active_func_local(&mut self) {
6045        let current = self.stack.len() - 1;
6046        if !self.stack[current].needs_active_func_local {
6047            return;
6048        }
6049        if !self.stack[current]
6050            .vars
6051            .iter()
6052            .any(|var| var.name == ACTIVE_FUNC)
6053        {
6054            self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
6055        }
6056        self.prepend_initialiser(
6057            ACTIVE_FUNC,
6058            Insn::Fixed {
6059                op: Opcode::SpecialObject,
6060                operands: vec![Op::Int(2)],
6061            },
6062        );
6063    }
6064
6065    /// Give the function a local `new.target`, for an arrow inside it to capture.
6066    fn provide_new_target_local(&mut self) {
6067        let current = self.stack.len() - 1;
6068        if !self.stack[current].needs_new_target_local {
6069            return;
6070        }
6071        if !self.stack[current]
6072            .vars
6073            .iter()
6074            .any(|var| var.name == NEW_TARGET)
6075        {
6076            self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
6077        }
6078        self.prepend_initialiser(
6079            NEW_TARGET,
6080            Insn::Fixed {
6081                op: Opcode::SpecialObject,
6082                operands: vec![Op::Int(3)],
6083            },
6084        );
6085    }
6086
6087    /// `arguments` reached from an arrow, which likewise belongs to the enclosing
6088    /// function.
6089    fn ensure_enclosing_arguments(&mut self) {
6090        // An arrow created in a parameter list needs the *parameter* scope's
6091        // `arguments`, not the body's: the two are separate bindings and the arrow was
6092        // born before the body existed.
6093        let from_params = self.cur().created_in_params;
6094        if let Some(target) = self.enclosing_function() {
6095            self.state_at(target).needs_arguments_local = true;
6096            if from_params {
6097                self.state_at(target).needs_param_arguments = true;
6098                // Declare it now, not at the enclosing function's `finish_current`: the
6099                // arrow resolves its own `arguments` before that runs, and a binding that
6100                // does not exist yet resolves as a global.
6101                declare_param_var_at(&mut self.stack[target], "arguments");
6102            }
6103            self.declare_at(target, "arguments");
6104        }
6105    }
6106
6107    /// The innermost enclosing frame that is a real function — an arrow inherits from it
6108    /// rather than starting a scope of its own.
6109    fn enclosing_function(&self) -> Option<usize> {
6110        (0..self.stack.len())
6111            .rev()
6112            .find(|index| !self.stack[*index].is_arrow && !self.stack[*index].is_script)
6113    }
6114
6115    fn state_at(&mut self, index: usize) -> &mut FnState {
6116        &mut self.stack[index]
6117    }
6118
6119    /// Declare a `var` binding directly in a specific frame.
6120    fn declare_at(&mut self, index: usize, name: &str) {
6121        let state = &mut self.stack[index];
6122        if state.vars.iter().any(|var| var.name == name) {
6123            return;
6124        }
6125        state.var_block.push(FUNCTION_SCOPE);
6126        state.vars.push(VarDef::var(name));
6127    }
6128
6129    /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
6130    /// the reference calls a `special_object` gets initialised on entry.
6131    fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
6132        let current = self.stack.len() - 1;
6133        let init = [
6134            producer,
6135            Insn::Var {
6136                action: VarAction::Put,
6137                name: name.to_string(),
6138                block: 0,
6139                // A prologue initialiser runs before the body proper, but it is body
6140                // code: `this` and `arguments` are provided for it, not by it.
6141                in_params: false,
6142            },
6143        ];
6144        let inserted = init.len();
6145        for (index, instruction) in init.into_iter().enumerate() {
6146            self.stack[current].insns.insert(index, instruction);
6147        }
6148        for placed in self.stack[current].labels.iter_mut().flatten() {
6149            *placed += inserted;
6150        }
6151        self.stack[current].label_since_insn = true;
6152    }
6153
6154    fn push_constant(&mut self, constant: Constant) -> u32 {
6155        let state = self.state();
6156        let index = state.cpool.len() as u32;
6157        state.cpool.push(constant);
6158        index
6159    }
6160
6161    /// Compile `a && b`, `a || b`, `a ?? b`.
6162    ///
6163    /// A run of the *same* operator shares one end label, so `a || b || c` tests
6164    /// `a` once and jumps past everything when it is truthy, instead of falling
6165    /// into `b`'s test. The parser builds such a run left-associated —
6166    /// `((a || b) || c)` — so the operands are collected off the left spine.
6167    ///
6168    /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
6169    /// `||`'s label, because the inner chain really does end before `&&` begins.
6170    fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
6171        let mut operands = Vec::new();
6172        collect_same_operator(op, left, &mut operands);
6173        operands.push(right);
6174
6175        let end = self.new_label();
6176        // Every operand but the last decides whether the chain stops here.
6177        let last = operands.pop().expect("the right operand is always present");
6178        for operand in operands {
6179            self.expr(operand)?;
6180            self.emit(Opcode::Dup, &[]);
6181            match op {
6182                LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
6183                LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
6184                // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
6185                // `0 || b` is `b`. The dedicated test keeps the value unless it is
6186                // null-ish, so the jump is taken on `false`.
6187                LogicalOp::Coalesce => {
6188                    self.emit(Opcode::IsUndefinedOrNull, &[]);
6189                    self.emit_jump(Opcode::IfFalse, end, &[]);
6190                }
6191            }
6192            self.emit(Opcode::Drop, &[]);
6193        }
6194        self.expr(last)?;
6195        self.place_label(end);
6196        Ok(())
6197    }
6198
6199    fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
6200        match op {
6201            UnaryOp::Typeof => {
6202                // `typeof x` must not throw on an undeclared name.
6203                if let ExprKind::Ident(name) = &argument.kind {
6204                    self.emit_var(VarAction::GetUndef, &name.name);
6205                } else {
6206                    self.expr(argument)?;
6207                }
6208                self.emit(Opcode::Typeof, &[]);
6209            }
6210            UnaryOp::Delete => {
6211                // `delete obj.prop` really deletes, and answers whether it could.
6212                // Deleting a *binding* is always `false`: a local, an argument and a
6213                // declared global are all non-configurable, which the reference encodes
6214                // as a constant `push_false` rather than a runtime check. Only a
6215                // property access has anything to do at run time.
6216                // `delete super.x` is not a delete at all: the spec refuses it, and the
6217                // reference encodes the refusal as a `throw_error`. The receiver and the
6218                // key are still evaluated first, which is what keeps the evaluation order
6219                // of the operand intact.
6220                // `delete z?.b.c` answers `true` when the chain short-circuits: there is
6221                // nothing to delete, and a failed delete is not the same as a skipped
6222                // one. The reference emits the guards so they land on a `drop; push_true`
6223                // tail, which is what this reproduces.
6224                if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
6225                    && let ExprKind::Member {
6226                        object, property, ..
6227                    } = &inner.unparen().kind
6228                {
6229                    let end = self.new_label();
6230                    let done = self.new_label();
6231                    self.chain_link(object, end)?;
6232                    match property {
6233                        MemberProp::Ident(name) => self.emit(
6234                            Opcode::PushAtomValue,
6235                            &[Op::Atom(Atom::from_text(&name.name))],
6236                        ),
6237                        MemberProp::Computed(index) => self.expr(index)?,
6238                        MemberProp::Private(_) => {
6239                            return Err(SyntaxError::new(
6240                                "deleting a private field is not allowed",
6241                                argument.span,
6242                            ));
6243                        }
6244                    }
6245                    self.emit(Opcode::Delete, &[]);
6246                    self.emit_jump(Opcode::Goto, done, &[]);
6247                    self.place_label(end);
6248                    self.emit(Opcode::Drop, &[]);
6249                    self.emit(Opcode::PushTrue, &[]);
6250                    self.place_label(done);
6251                    return Ok(());
6252                }
6253                if let ExprKind::Member { object, .. } = &argument.unparen().kind
6254                    && matches!(object.unparen().kind, ExprKind::SuperProp)
6255                {
6256                    self.super_base();
6257                    self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
6258                    return Ok(());
6259                }
6260                match &argument.kind {
6261                    ExprKind::Member {
6262                        object, property, ..
6263                    } => {
6264                        self.expr(object)?;
6265                        match property {
6266                            MemberProp::Ident(name) => {
6267                                self.emit(
6268                                    Opcode::PushAtomValue,
6269                                    &[Op::Atom(Atom::from_text(&name.name))],
6270                                );
6271                            }
6272                            MemberProp::Computed(index) => self.expr(index)?,
6273                            MemberProp::Private(_) => {
6274                                return Err(SyntaxError::new(
6275                                    "deleting a private field is not allowed",
6276                                    argument.span,
6277                                ));
6278                            }
6279                        }
6280                        self.emit(Opcode::Delete, &[]);
6281                    }
6282                    ExprKind::Ident(name) => {
6283                        // `delete name`: a declared global, a local and an argument all
6284                        // answer `false`, but an *implicit* global (`x = 1` with no
6285                        // declaration) is a configurable property of the global object
6286                        // and really goes away. Which of those a name is only the
6287                        // resolver knows, so the decision waits for it.
6288                        let pos = self.cur().cur_pos;
6289                        self.state().insns.push(Insn::DeleteVar {
6290                            name: name.name.clone(),
6291                        });
6292                        self.state().insn_pos.push(pos);
6293                    }
6294                    _ => self.emit(Opcode::PushFalse, &[]),
6295                }
6296            }
6297            UnaryOp::Void => {
6298                self.expr(argument)?;
6299                self.emit(Opcode::Drop, &[]);
6300                self.emit(Opcode::Undefined, &[]);
6301            }
6302            UnaryOp::Minus => {
6303                self.expr(argument)?;
6304                self.emit(Opcode::Neg, &[]);
6305            }
6306            UnaryOp::Plus => {
6307                self.expr(argument)?;
6308                self.emit(Opcode::Plus, &[]);
6309            }
6310            UnaryOp::Not => {
6311                self.expr(argument)?;
6312                self.emit(Opcode::Lnot, &[]);
6313            }
6314            UnaryOp::BitNot => {
6315                self.expr(argument)?;
6316                self.emit(Opcode::Not, &[]);
6317            }
6318        }
6319        Ok(())
6320    }
6321
6322    /// Compile an assignment.
6323    ///
6324    /// Three operator families, three shapes:
6325    ///
6326    /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
6327    ///   the value is kept, because `put_field`/`put_array_el` consume both the
6328    ///   object and the value: `insert2` is `obj a -> a obj a`, so the store sees
6329    ///   the pair it wants and leaves a copy on top.
6330    /// * **compound** `+=` … — read the place, apply the operator, store. A member
6331    ///   reads through `get_field2`/`get_array_el3`, which leave the object (and
6332    ///   index) underneath the value precisely so the store can follow.
6333    /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
6334    ///   right-hand side. The test *keeps* the current value and skips the store
6335    ///   entirely, which is the whole point: `a ||= b` must not evaluate `b` when
6336    ///   `a` is already truthy.
6337    fn assign(&mut self, op: AssignOp, target: &Pattern, value: &Expr) -> Result<(), SyntaxError> {
6338        // Reading the flag clears it: only the outermost assignment of an
6339        // expression statement may drop its value.
6340        let keep = !std::mem::take(&mut self.state().discard_value);
6341        match &target.kind {
6342            PatternKind::Ident(name) => {
6343                // A *simple* store is blamed on the identifier, not on the `=`: a
6344                // strict-mode `not_def = 1` raises when the name is written, which the
6345                // reference reports at the name's column. A compound store is blamed on
6346                // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
6347                // which the reference reports at the `+=`), so only the simple case
6348                // moves the position.
6349                let saved = self.cur().cur_pos;
6350                let name_pos = Some(name.span.start);
6351                if matches!(op, AssignOp::Assign) {
6352                    self.state().cur_pos = name_pos;
6353                }
6354                // A *compound* store reads the binding before it combines, and that read
6355                // is blamed on the identifier: `not_def += 2` fails while reading
6356                // `not_def`, so the position is the name's, not the `+=`'s. The
6357                // combination that follows is blamed on the operator, which is why
6358                // `cur_pos` is put back to the operator position before it is emitted.
6359                self.state().cur_pos = name_pos;
6360                match op {
6361                    AssignOp::Assign => {
6362                        self.expr(value)?;
6363                        self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
6364                        // A discarded store to a *slot* consumes its value, so no copy
6365                        // is needed. A global store goes through `put_var`, which the
6366                        // reference always pairs with a `dup` — matching it keeps the
6367                        // bytecode identical. Getting this wrong is not only an extra
6368                        // instruction: a stray copy gives the peephole a chance to fold
6369                        // the store into an unrelated later read.
6370                        let slot = self.is_slot(&name.name);
6371                        if keep || !slot {
6372                            self.emit(Opcode::Dup, &[]);
6373                        }
6374                        self.state().no_value = !keep && slot;
6375                        self.emit_var(VarAction::Put, &name.name);
6376                    }
6377                    AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6378                        let end = self.new_label();
6379                        self.emit_var(VarAction::Get, &name.name);
6380                        self.state().cur_pos = saved;
6381                        self.emit(Opcode::Dup, &[]);
6382                        self.emit_logical_test(op);
6383                        self.emit_jump(logical_jump(op), end, &[]);
6384                        self.emit(Opcode::Drop, &[]);
6385                        self.expr(value)?;
6386                        self.emit(Opcode::Dup, &[]);
6387                        self.emit_var(VarAction::Put, &name.name);
6388                        self.place_label(end);
6389                    }
6390                    _ => {
6391                        self.emit_var(VarAction::Get, &name.name);
6392                        self.expr(value)?;
6393                        self.state().cur_pos = saved;
6394                        self.emit(compound_opcode(op), &[]);
6395                        self.emit(Opcode::Dup, &[]);
6396                        self.emit_var(VarAction::Put, &name.name);
6397                    }
6398                }
6399                self.state().cur_pos = saved;
6400                Ok(())
6401            }
6402            PatternKind::Member(member) => {
6403                // `super.x = v` is not a store through a value: it starts at the home
6404                // object's prototype but writes to `this`, so it goes through
6405                // `put_super_value` rather than `put_field`. The receiver, prototype, key
6406                // and value are handed over together.
6407                if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
6408                    return self.assign_super(member, op, value);
6409                }
6410                // A store is blamed on the selector punctuator (`.` or `[`), the same
6411                // token a load is blamed on — the reference records `put_field obj.a`
6412                // at the `.`, so a setter that throws reports that column and not the
6413                // `=` of the assignment it sits in. The inner expressions restore their
6414                // own positions, so the selector's sticks for the store instructions.
6415                let saved = self.cur().cur_pos;
6416                self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6417                self.expr(&member.object)?;
6418                match &member.property {
6419                    MemberProp::Ident(property) => {
6420                        let atom = Atom::from_text(&property.name);
6421                        match op {
6422                            AssignOp::Assign => {
6423                                self.expr(value)?;
6424                                // `put_field` consumes the object and the value, so
6425                                // without `insert2` nothing is left over for the
6426                                // statement to drop.
6427                                self.state().no_value = !keep;
6428                                if keep {
6429                                    self.emit(Opcode::Insert2, &[]);
6430                                }
6431                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6432                            }
6433                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6434                                // `get_field2` leaves the object under the value, so
6435                                // the keep path has an object to dispose of. The store
6436                                // path must jump *over* that cleanup: falling into it
6437                                // would `nip` a stack that only holds the value.
6438                                let (keep_label, end) = (self.new_label(), self.new_label());
6439                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6440                                self.emit(Opcode::Dup, &[]);
6441                                self.emit_logical_test(op);
6442                                self.emit_jump(logical_jump(op), keep_label, &[]);
6443                                self.emit(Opcode::Drop, &[]);
6444                                self.expr(value)?;
6445                                self.emit(Opcode::Insert2, &[]);
6446                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6447                                self.emit_jump(Opcode::Goto, end, &[]);
6448                                self.place_label(keep_label);
6449                                self.emit(Opcode::Nip, &[]);
6450                                self.place_label(end);
6451                            }
6452                            _ => {
6453                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
6454                                self.expr(value)?;
6455                                self.emit(compound_opcode(op), &[]);
6456                                self.state().no_value = !keep;
6457                                if keep {
6458                                    self.emit(Opcode::Insert2, &[]);
6459                                }
6460                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
6461                            }
6462                        }
6463                    }
6464                    MemberProp::Computed(index) => {
6465                        self.expr(index)?;
6466                        match op {
6467                            AssignOp::Assign => {
6468                                self.expr(value)?;
6469                                self.state().no_value = !keep;
6470                                if keep {
6471                                    self.emit(Opcode::Insert3, &[]);
6472                                }
6473                                self.emit(Opcode::PutArrayEl, &[]);
6474                            }
6475                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6476                                let (keep_label, end) = (self.new_label(), self.new_label());
6477                                self.emit(Opcode::GetArrayEl3, &[]);
6478                                self.emit(Opcode::Dup, &[]);
6479                                self.emit_logical_test(op);
6480                                self.emit_jump(logical_jump(op), keep_label, &[]);
6481                                self.emit(Opcode::Drop, &[]);
6482                                self.expr(value)?;
6483                                self.emit(Opcode::Insert3, &[]);
6484                                self.emit(Opcode::PutArrayEl, &[]);
6485                                self.emit_jump(Opcode::Goto, end, &[]);
6486                                self.place_label(keep_label);
6487                                // Both the object and the index are left over.
6488                                self.emit(Opcode::Nip, &[]);
6489                                self.emit(Opcode::Nip, &[]);
6490                                self.place_label(end);
6491                            }
6492                            _ => {
6493                                self.emit(Opcode::GetArrayEl3, &[]);
6494                                self.expr(value)?;
6495                                self.emit(compound_opcode(op), &[]);
6496                                self.state().no_value = !keep;
6497                                if keep {
6498                                    self.emit(Opcode::Insert3, &[]);
6499                                }
6500                                self.emit(Opcode::PutArrayEl, &[]);
6501                            }
6502                        }
6503                    }
6504                    MemberProp::Private(name) => {
6505                        // `obj value` is on the stack, and every private store wants exactly
6506                        // that. A top-level private name cannot be assigned (the parser rejects
6507                        // `#x = 1`), so the only way here is `this.#x = …` inside the class.
6508                        //
6509                        // The reference emits `insert2` whether or not the value is wanted,
6510                        // so this does too: the copy left behind is the assignment expression's
6511                        // value, and a discarded one is simply never read.
6512                        let binding = format!("#{}", name.name);
6513                        let (kind, setter) = self.private_use(&binding, member.span)?;
6514                        match op {
6515                            AssignOp::Assign => {
6516                                self.expr(value)?;
6517                                if keep {
6518                                    self.emit(Opcode::Insert2, &[]);
6519                                }
6520                                self.private_store(&binding, kind, setter.as_deref())?;
6521                                self.state().no_value = !keep;
6522                            }
6523                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6524                                let (keep_label, end) = (self.new_label(), self.new_label());
6525                                self.emit(Opcode::Dup, &[]);
6526                                self.private_load(&binding, kind, member.span)?;
6527                                self.emit(Opcode::Dup, &[]);
6528                                self.emit_logical_test(op);
6529                                self.emit_jump(logical_jump(op), keep_label, &[]);
6530                                self.emit(Opcode::Drop, &[]);
6531                                self.expr(value)?;
6532                                self.emit(Opcode::Insert2, &[]);
6533                                self.private_store(&binding, kind, setter.as_deref())?;
6534                                self.emit_jump(Opcode::Goto, end, &[]);
6535                                self.place_label(keep_label);
6536                                self.emit(Opcode::Nip, &[]);
6537                                self.place_label(end);
6538                            }
6539                            _ => {
6540                                self.emit(Opcode::Dup, &[]);
6541                                self.private_load(&binding, kind, member.span)?;
6542                                self.expr(value)?;
6543                                self.emit(compound_opcode(op), &[]);
6544                                self.emit(Opcode::Insert2, &[]);
6545                                self.private_store(&binding, kind, setter.as_deref())?;
6546                            }
6547                        }
6548                    }
6549                }
6550                self.state().cur_pos = saved;
6551                Ok(())
6552            }
6553            // A destructuring assignment: the right-hand side is the expression's own
6554            // value, so it is evaluated once and kept under the pattern's stores.
6555            PatternKind::Array { .. } | PatternKind::Object { .. } => {
6556                self.expr(value)?;
6557                if keep {
6558                    self.emit(Opcode::Dup, &[]);
6559                }
6560                self.destructure(target, None)?;
6561                self.state().no_value = !keep;
6562                Ok(())
6563            }
6564            _ => Err(SyntaxError::new(
6565                "this assignment target is not supported by the compiler yet",
6566                target.span,
6567            )),
6568        }
6569    }
6570
6571    /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
6572    ///
6573    /// The stack has to carry four values — receiver, prototype, key, value — because
6574    /// `put_super_value` takes them together; the receiver is what makes a setter found on
6575    /// the prototype run with `this`, and the key has to survive until the store, which is
6576    /// why a compound form converts it to a property key once and `dup3`s rather than
6577    /// evaluating it twice.
6578    fn assign_super(
6579        &mut self,
6580        member: &MemberPattern,
6581        op: AssignOp,
6582        value: &Expr,
6583    ) -> Result<(), SyntaxError> {
6584        let saved = self.cur().cur_pos;
6585        self.state().cur_pos = member.op_pos.or(Some(member.span.start));
6586        self.super_base();
6587        match &member.property {
6588            MemberProp::Ident(property) => self.emit(
6589                Opcode::PushAtomValue,
6590                &[Op::Atom(Atom::from_text(&property.name))],
6591            ),
6592            MemberProp::Computed(index) => self.expr(index)?,
6593            MemberProp::Private(_) => {
6594                return Err(SyntaxError::new(
6595                    "private fields are not supported by the compiler yet",
6596                    member.span,
6597                ));
6598            }
6599        }
6600        match op {
6601            AssignOp::Assign => {
6602                // The key is only converted once, by `put_super_value` itself, so a
6603                // computed key's `toString` runs exactly once.
6604                self.expr(value)?;
6605                self.emit(Opcode::Insert4, &[]);
6606                self.emit(Opcode::PutSuperValue, &[]);
6607            }
6608            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
6609                let (keep_label, end) = (self.new_label(), self.new_label());
6610                self.emit(Opcode::ToPropkey, &[]);
6611                self.emit(Opcode::Dup3, &[]);
6612                self.emit(Opcode::GetSuperValue, &[]);
6613                self.emit(Opcode::Dup, &[]);
6614                self.emit_logical_test(op);
6615                self.emit_jump(logical_jump(op), keep_label, &[]);
6616                self.emit(Opcode::Drop, &[]);
6617                self.expr(value)?;
6618                self.emit(Opcode::Insert4, &[]);
6619                self.emit(Opcode::PutSuperValue, &[]);
6620                self.emit_jump(Opcode::Goto, end, &[]);
6621                self.place_label(keep_label);
6622                // The prototype and the key are still under the value that was read.
6623                self.emit(Opcode::Nip, &[]);
6624                self.emit(Opcode::Nip, &[]);
6625                self.emit(Opcode::Nip, &[]);
6626                self.place_label(end);
6627            }
6628            _ => {
6629                self.emit(Opcode::ToPropkey, &[]);
6630                self.emit(Opcode::Dup3, &[]);
6631                self.emit(Opcode::GetSuperValue, &[]);
6632                self.expr(value)?;
6633                self.emit(compound_opcode(op), &[]);
6634                self.emit(Opcode::Insert4, &[]);
6635                self.emit(Opcode::PutSuperValue, &[]);
6636            }
6637        }
6638        // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
6639        // is still on the stack when the store finishes, and the expression statement is
6640        // what disposes of it — the same arrangement as `put_field`, reached from the other
6641        // side: there the store consumes the value (`no_value`), here it leaves it
6642        // (`keep` already false, so nothing tells the statement otherwise).
6643        self.state().cur_pos = saved;
6644        Ok(())
6645    }
6646
6647    /// The test a logical assignment applies to the current value.
6648    ///
6649    /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
6650    /// assign, while `0 ||= b` must not.
6651    fn emit_logical_test(&mut self, op: AssignOp) {
6652        if op == AssignOp::Coalesce {
6653            self.emit(Opcode::IsUndefinedOrNull, &[]);
6654        }
6655    }
6656
6657    /// The private name `#name` this use site resolves against.
6658    ///
6659    /// The parser has already rejected a name no enclosing class declares, so a miss here
6660    /// means the compiler lost track of a class scope — which is worth a real error rather
6661    /// than an `unwrap`.
6662    fn private_use(
6663        &self,
6664        binding: &str,
6665        span: Span,
6666    ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
6667        ClassPlan::find(self, binding)
6668            .map(|use_| (use_.kind, use_.setter.clone()))
6669            .ok_or_else(|| {
6670                SyntaxError::new(
6671                    format!("the private name '{binding}' is out of scope here"),
6672                    span,
6673                )
6674            })
6675    }
6676
6677    /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
6678    ///
6679    /// The three readable kinds take three different instructions, because a private name
6680    /// holds three different things — a symbol, a method function, a getter function — and
6681    /// only the first one is a property read at all.
6682    fn private_load(
6683        &mut self,
6684        binding: &str,
6685        kind: PrivateKind,
6686        span: Span,
6687    ) -> Result<(), SyntaxError> {
6688        match kind {
6689            PrivateKind::Field => {
6690                self.emit_var(VarAction::Get, binding);
6691                self.emit(Opcode::GetPrivateField, &[]);
6692            }
6693            PrivateKind::Method => {
6694                self.emit_var(VarAction::Get, binding);
6695                self.emit(Opcode::CheckBrand, &[]);
6696                // `check_brand` reads `obj func` and leaves both; the method itself is what
6697                // `this.#m` evaluates to.
6698                self.emit(Opcode::Nip, &[]);
6699            }
6700            PrivateKind::Getter => {
6701                self.emit_var(VarAction::Get, binding);
6702                self.emit(Opcode::CheckBrand, &[]);
6703                self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6704            }
6705            // `#a` is declared but never filled when only a setter exists, so reading it is
6706            // the same refusal as assigning to a `const`. The reference reports it with the
6707            // generic read-only wording and leaves the better message as a `XXX`.
6708            PrivateKind::Setter => self.emit(
6709                Opcode::ThrowError,
6710                &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
6711            ),
6712        }
6713        let _ = span;
6714        Ok(())
6715    }
6716
6717    /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
6718    fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
6719        match kind {
6720            // A method *is* the callee, so only the check goes in between.
6721            PrivateKind::Method => {
6722                self.emit_var(VarAction::Get, binding);
6723                self.emit(Opcode::CheckBrand, &[]);
6724            }
6725            _ => self.private_load(binding, kind, Span::default())?,
6726        }
6727        Ok(())
6728    }
6729
6730    /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
6731    /// wanted back.
6732    ///
6733    /// A getter/setter pair is a *method call*, not a property store: the reference reads
6734    /// the setter out of its own binding and calls it with the receiver, which is why the
6735    /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
6736    /// keeps the assignment's value for an expression context.
6737    fn private_store(
6738        &mut self,
6739        binding: &str,
6740        kind: PrivateKind,
6741        setter: Option<&str>,
6742    ) -> Result<(), SyntaxError> {
6743        match kind {
6744            PrivateKind::Field => {
6745                self.emit_var(VarAction::Get, binding);
6746                self.emit(Opcode::PutPrivateField, &[]);
6747            }
6748            PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
6749                Some(setter) => {
6750                    self.emit_var(VarAction::Get, setter);
6751                    // `obj func value` -> `value obj func` for the check, and back again for
6752                    // the call, which wants `obj func arg`.
6753                    self.emit(Opcode::Swap, &[]);
6754                    self.emit(Opcode::Rot3r, &[]);
6755                    self.emit(Opcode::CheckBrand, &[]);
6756                    self.emit(Opcode::Rot3l, &[]);
6757                    self.emit(Opcode::CallMethod, &[Op::Int(1)]);
6758                    // The setter's return value is discarded; the assignment's own value is
6759                    // whatever the caller left underneath.
6760                    self.emit(Opcode::Drop, &[]);
6761                }
6762                None => self.emit(
6763                    Opcode::ThrowError,
6764                    &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
6765                ),
6766            },
6767        }
6768        Ok(())
6769    }
6770
6771    fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
6772        let instruction = match (op, prefix) {
6773            (UpdateOp::Increment, true) => Opcode::Inc,
6774            (UpdateOp::Increment, false) => Opcode::PostInc,
6775            (UpdateOp::Decrement, true) => Opcode::Dec,
6776            (UpdateOp::Decrement, false) => Opcode::PostDec,
6777        };
6778        if let ExprKind::Member {
6779            object,
6780            property,
6781            optional: _,
6782        } = &argument.kind
6783        {
6784            // `o.x++` needs the receiver twice, so the last link is read with the
6785            // `get_*2`/`get_*3` form that keeps it, and the update is written back
6786            // with `put_field`/`put_array_el`. The reordering in between is what puts
6787            // the old value below the receiver for a postfix update and the new one
6788            // above it for a prefix one:
6789            //
6790            //   `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
6791            //   `obj val` → `inc`      → `obj new new` → `insert2` → `new obj new`
6792            //
6793            // This mirrors the reference instruction for instruction.
6794            self.expr(object)?;
6795            match property {
6796                MemberProp::Ident(name) => {
6797                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
6798                    self.emit(instruction, &[]);
6799                    self.emit(
6800                        if prefix {
6801                            Opcode::Insert2
6802                        } else {
6803                            Opcode::Perm3
6804                        },
6805                        &[],
6806                    );
6807                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
6808                }
6809                MemberProp::Computed(index) => {
6810                    self.expr(index)?;
6811                    self.emit(Opcode::GetArrayEl3, &[]);
6812                    self.emit(instruction, &[]);
6813                    self.emit(
6814                        if prefix {
6815                            Opcode::Insert3
6816                        } else {
6817                            Opcode::Perm4
6818                        },
6819                        &[],
6820                    );
6821                    self.emit(Opcode::PutArrayEl, &[]);
6822                }
6823                MemberProp::Private(name) => {
6824                    // The receiver is duplicated and the read keeps it, exactly as `get_field2`
6825                    // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
6826                    // `perm3` -> `old obj new` -> store.
6827                    let binding = format!("#{}", name.name);
6828                    let (kind, setter) = self.private_use(&binding, argument.span)?;
6829                    self.emit(Opcode::Dup, &[]);
6830                    self.private_load(&binding, kind, argument.span)?;
6831                    self.emit(instruction, &[]);
6832                    self.emit(
6833                        if prefix {
6834                            Opcode::Insert2
6835                        } else {
6836                            Opcode::Perm3
6837                        },
6838                        &[],
6839                    );
6840                    self.private_store(&binding, kind, setter.as_deref())?;
6841                }
6842            }
6843            return Ok(());
6844        }
6845        let ExprKind::Ident(name) = &argument.kind else {
6846            return Err(SyntaxError::new(
6847                "increment of a non-variable is not supported by the compiler yet",
6848                argument.span,
6849            ));
6850        };
6851        // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
6852        // reference's `inc_loc` folds those three into one, but it does so only in some
6853        // positions (a `for` update and not a bare statement, and never for a lexical
6854        // binding), so emitting it unconditionally would move *away* from its output.
6855        // The instruction is equivalent either way; matching the reference matters more
6856        // than saving two instructions.
6857        let _ = !std::mem::take(&mut self.state().discard_value);
6858        self.emit_var(VarAction::Get, &name.name);
6859        self.emit(instruction, &[]);
6860        if prefix {
6861            self.emit(Opcode::Dup, &[]);
6862        }
6863        self.emit_var(VarAction::Put, &name.name);
6864        Ok(())
6865    }
6866
6867    /// Compile an array literal.
6868    ///
6869    /// The reference splits this into three phases, and the split is load-bearing
6870    /// rather than an optimisation detail:
6871    ///
6872    /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
6873    ///    the array in one instruction.
6874    /// 2. **Everything up to the first spread** is appended with explicit indices
6875    ///    (`define_field <index>`), because a hole has no element to pass to
6876    ///    `array_from`. A hole here is what makes `length` need fixing up: an
6877    ///    explicit index does not extend the array the way a pushed element does.
6878    /// 3. **From the first spread on** the index lives on the stack, so `append` and
6879    ///    `define_array_el` can consume it and `inc` advances it.
6880    ///
6881    /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
6882    /// forces phase 2, and `[...a]` forces phase 3.
6883    fn array_literal(
6884        &mut self,
6885        elements: &[Option<ArrayElement>],
6886        span: Span,
6887    ) -> Result<(), SyntaxError> {
6888        let _ = span;
6889        let mut index: u32 = 0;
6890        let mut cursor = 0usize;
6891
6892        // Phase 1: a leading run of plain elements, at most 32 of them.
6893        while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
6894            if index >= 32 {
6895                break;
6896            }
6897            self.expr(element)?;
6898            index += 1;
6899            cursor += 1;
6900        }
6901        self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
6902
6903        // Phase 2: explicit indices, up to the first spread.
6904        let mut need_length = false;
6905        while let Some(element) = elements.get(cursor) {
6906            if matches!(element, Some(ArrayElement::Spread(_))) {
6907                break;
6908            }
6909            need_length = true;
6910            if let Some(ArrayElement::Expr(expression)) = element {
6911                self.expr(expression)?;
6912                self.emit_define_index(index);
6913                need_length = false;
6914            }
6915            index += 1;
6916            cursor += 1;
6917        }
6918
6919        if cursor >= elements.len() {
6920            if need_length {
6921                // `define_field` cannot set `length`, which is not configurable.
6922                self.emit(Opcode::Dup, &[]);
6923                self.push_number(index as f64);
6924                self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
6925            }
6926            return Ok(());
6927        }
6928
6929        // Phase 3: the index moves onto the stack for the spreading tail.
6930        //
6931        // `need_length` deliberately carries over from phase 2: a hole before the
6932        // first spread still has to be reflected in `length`, and only the final
6933        // check can do it because the array is not finished until the tail is
6934        // appended.
6935        self.push_number(index as f64);
6936        while let Some(element) = elements.get(cursor) {
6937            match element {
6938                Some(ArrayElement::Spread(expression)) => {
6939                    // `append` copies an iterable and leaves the next index behind,
6940                    // so no `inc` is needed here.
6941                    self.expr(spread_argument(expression))?;
6942                    self.emit(Opcode::Append, &[]);
6943                }
6944                None | Some(ArrayElement::Expr(_)) => {
6945                    need_length = true;
6946                    if let Some(ArrayElement::Expr(expression)) = element {
6947                        self.expr(expression)?;
6948                        self.emit(Opcode::DefineArrayEl, &[]);
6949                        need_length = false;
6950                    }
6951                    self.emit(Opcode::Inc, &[]);
6952                }
6953            }
6954            cursor += 1;
6955        }
6956        if need_length {
6957            self.emit(Opcode::Dup1, &[]);
6958            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
6959        } else {
6960            self.emit(Opcode::Drop, &[]);
6961        }
6962        Ok(())
6963    }
6964
6965    /// `define_field` with an array-index atom, which is how phase 2 stores elements.
6966    fn emit_define_index(&mut self, index: u32) {
6967        self.emit(
6968            Opcode::DefineField,
6969            &[Op::Atom(Atom::from_text(&index.to_string()))],
6970        );
6971    }
6972
6973    // -- functions ---------------------------------------------------------
6974
6975    fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
6976        self.compile_function_with_name(func, false)
6977    }
6978
6979    /// Compile a function, recording whether it is a *named function expression*.
6980    ///
6981    /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
6982    /// must not leak outside. The reference does that by declaring `g` as a local of
6983    /// the function itself and initialising it with `special_object 2` (the current
6984    /// function), which is why this has to be known at compile time.
6985    fn compile_function_with_name(
6986        &mut self,
6987        func: &ast::Function,
6988        is_expression: bool,
6989    ) -> Result<CompiledFunction, SyntaxError> {
6990        let kind = match (func.is_generator, func.is_async) {
6991            (false, false) => FunctionKind::Normal,
6992            (true, false) => FunctionKind::Generator,
6993            (false, true) => FunctionKind::Async,
6994            (true, true) => FunctionKind::AsyncGenerator,
6995        };
6996        let mut state = FnState::new(
6997            func.name
6998                .as_ref()
6999                .map(|n| n.name.clone())
7000                .unwrap_or_default(),
7001            kind,
7002        );
7003        // The function's own mode, recorded by the parser. Inheriting the enclosing
7004        // function's instead let a nested `"use strict"` directive be ignored, so the
7005        // body ran with sloppy `this`, sloppy `arguments` and no const checks.
7006        state.strict = func.strict;
7007        // A function defined inside a `with` block keeps seeing that object: the guard
7008        // chain names the enclosing `<with>` locals, which resolve outward into closure
7009        // variables exactly like any other captured binding.
7010        state.with_names = self.cur().with_names.clone();
7011        state.is_arrow = func.is_arrow;
7012        state.created_in_block = self.cur().current_block;
7013        // A default anywhere in the parameter list is what gives the function two
7014        // variable environments. The reference decides this the same way: it scans the
7015        // parenthesis for a top-level `=`, so a destructured name without a default
7016        // stays a plain function-scope binding.
7017        state.in_params = false;
7018        // The reference scans the parenthesis for *any* `=`, including one nested inside
7019        // a pattern, so `function f({a = 1})` has parameter expressions even though the
7020        // parameter itself carries no initialiser.
7021        state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
7022        // A function born inside a parameter list inherits the prohibition: it must not
7023        // see the body bindings of the function it was created in.
7024        state.created_in_params = self.cur().in_params || self.cur().created_in_params;
7025        // A class constructor knows what it is only because the class told it.
7026        if let Some(kind) = self.cur().class_ctor_pending {
7027            state.ctor_kind = kind;
7028        }
7029        // A named *expression* binds its own name; a declaration's name is already
7030        // bound in the enclosing scope.
7031        state.self_name = if is_expression && !func.is_arrow {
7032            func.name.as_ref().map(|n| n.name.clone())
7033        } else {
7034            None
7035        };
7036        state.line = func.span.start.line;
7037        state.column = func.span.start.column;
7038        // A function body has no hidden `<ret>` local; the value comes back on
7039        // the stack. Only a script keeps one.
7040        // Parameters are positional, so even a pattern occupies one argument slot. A
7041        // simple name is that slot itself; anything else (a pattern, a default, a rest
7042        // parameter) takes an anonymous slot and is unpicked into locals at the top of
7043        // the body, which is the only way one argument can bind several names.
7044        let mut prologue: Vec<(usize, Pattern)> = Vec::new();
7045        // `.length` stops at the first parameter that can be substituted: a default
7046        // fills a missing argument in, and a rest parameter absorbs the rest.
7047        let mut defined_args = func.params.len() as u32;
7048        for (index, param) in func.params.iter().enumerate() {
7049            match simple_parameter(param) {
7050                Some(name) => state.args.push(VarDef::var(name.name.clone())),
7051                None => {
7052                    state.args.push(VarDef::var(ANONYMOUS_BINDING));
7053                    prologue.push((index, param.clone()));
7054                }
7055            }
7056        }
7057        // A default anywhere before the end also ends the count, which the loop above
7058        // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
7059        for (position, param) in func.params.iter().enumerate() {
7060            if matches!(
7061                param.kind,
7062                PatternKind::Assign { .. } | PatternKind::Rest(_)
7063            ) {
7064                defined_args = position as u32;
7065                break;
7066            }
7067        }
7068        state.defined_args = defined_args;
7069        state.param_prologue = prologue;
7070        let depth = self.stack.len();
7071        self.stack.push(state);
7072        let result = self.compile_function_body(func);
7073        if result.is_err() {
7074            // A failed compile must not leave its `FnState` behind. Every caller
7075            // reads `self.state()` as "the function being compiled", so a leftover
7076            // frame silently retargets all later bookkeeping at a dead function.
7077            self.stack.truncate(depth);
7078        }
7079        result
7080    }
7081
7082    /// The body of a function, with its frame already pushed.
7083    fn compile_function_body(
7084        &mut self,
7085        func: &ast::Function,
7086    ) -> Result<CompiledFunction, SyntaxError> {
7087        let body_key = func.params_span.end.offset as u64;
7088        // Where the body begins, in source order. The runtime needs this to tell a
7089        // closure created by a default expression from one the body creates — the two see
7090        // different variable environments — and a bytecode offset would not survive the
7091        // instruction shuffling that building the frame does. Positions are in source
7092        // order, so a comparison answers it.
7093        self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
7094        self.push_block(body_key, NO_PARENT);
7095        self.state().body_block = body_key;
7096        // An arrow with an expression body has no statements; the expression is
7097        // its `return`. Building the statement here keeps one code path below, and
7098        // matters for correctness beyond convenience: returning early with the new
7099        // `FnState` still on the stack would leave the compiler looking at the
7100        // wrong function, which surfaces as an unrelated underflow later.
7101        let concise = match &func.body {
7102            js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
7103                StmtKind::Return(Some(Box::new((**value).clone()))),
7104                value.span,
7105            )),
7106            js_parse::ast::FunctionBody::Block(_) => None,
7107        };
7108        let body: &[Stmt] = match &concise {
7109            Some(stmt) => std::slice::from_ref(stmt),
7110            None => func
7111                .body
7112                .statements()
7113                .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
7114        };
7115        let prologue = std::mem::take(&mut self.state().param_prologue);
7116        let has_param_scope = self.cur().has_parameter_expressions;
7117        // The parameter scope's own bindings, declared in source order.
7118        //
7119        // With parameter expressions the list gets a variable environment of its own, and
7120        // every name it binds is a `let` there. That is what puts the *list* in the
7121        // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
7122        // and `function f(x = y, y){}` does the same, where a single shared environment
7123        // would answer `undefined` to both.
7124        if has_param_scope {
7125            let mut declared: Vec<String> = Vec::new();
7126            for param in &func.params {
7127                let mut names = Vec::new();
7128                param.bound_names(&mut names);
7129                for name in names {
7130                    if declared.contains(&name.name) {
7131                        continue;
7132                    }
7133                    declared.push(name.name.clone());
7134                    self.declare_param_binding(&name.name);
7135                }
7136            }
7137        }
7138        // A pattern parameter binds its names as function-scope locals, so they have to
7139        // exist — and be unpicked from the argument — before the body runs. With a
7140        // parameter scope these are the *second* environment: the pattern fills the
7141        // parameter's copy, and the body's binding is filled from it afterwards.
7142        for (_, pattern) in &prologue {
7143            let mut names = Vec::new();
7144            pattern.bound_names(&mut names);
7145            for name in names {
7146                self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
7147            }
7148        }
7149        self.hoist(body, body_key)?;
7150        // A constructor's prologue is not a parameter unpacking but the `this` binding:
7151        // a base constructor takes the receiver, a derived one starts in the dead zone
7152        // because only `super()` may produce it.
7153        match self.cur().ctor_kind {
7154            CtorKind::None => {}
7155            CtorKind::Base => {
7156                self.begin_this_local();
7157                self.emit(Opcode::CheckCtor, &[]);
7158                // Instance fields are installed at the top of a base constructor's body,
7159                // before any statement — `class C { x = 1; constructor() { this.x } }` sees
7160                // `1`. This used to be emitted at the *tail*, which made every field read
7161                // `undefined` inside the constructor that declared it.
7162                self.call_field_initialiser();
7163            }
7164            CtorKind::Derived => {
7165                self.declare("this", VarDef::lexical("this"));
7166                let slot = self.cur().vars.len() as u32 - 1;
7167                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7168                self.emit(Opcode::CheckCtor, &[]);
7169            }
7170        }
7171        // Entering the parameter list: everything it binds starts in the dead zone.
7172        // The order is the reference's — it walks the scope chain, which is prepended, so
7173        // the bindings come out newest first.
7174        for name in self.param_binding_names().into_iter().rev() {
7175            if let Some(slot) = self.param_binding_slot(&name) {
7176                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
7177            }
7178        }
7179        // The whole parameter list is one scope, and nothing in the body exists yet, so
7180        // every name it mentions resolves against the parameter bindings and outward.
7181        self.state().in_params = has_param_scope;
7182        for (index, param) in func.params.iter().enumerate() {
7183            if let Some(pattern) = prologue_pattern(&prologue, index) {
7184                // A destructuring parameter *initialises* its bindings: with a parameter
7185                // scope they are the list's own `let`s, which is why the stores skip the
7186                // dead-zone check, and why the reference reads their properties with
7187                // `get_field2` — a `let` needs no reference.
7188                let kind = if has_param_scope {
7189                    VarDeclKind::Let
7190                } else {
7191                    VarDeclKind::Var
7192                };
7193                match &pattern.kind {
7194                    // `...rest` collects what is left rather than reading one slot.
7195                    PatternKind::Rest(inner) => {
7196                        self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7197                        self.destructure(inner, Some(kind))?;
7198                    }
7199                    _ => {
7200                        self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7201                        self.destructure(pattern, Some(kind))?;
7202                    }
7203                }
7204                continue;
7205            }
7206            // A plain name binds straight from its argument slot. With a parameter scope
7207            // the slot is also copied into the parameter binding, which is what a later
7208            // default (or a closure made among the defaults) reads.
7209            let Some(name) = simple_parameter(param) else {
7210                continue;
7211            };
7212            let target = self.param_binding_slot(&name.name);
7213            if matches!(param.kind, PatternKind::Rest(_)) {
7214                self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
7215                if let Some(slot) = target {
7216                    self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
7217                }
7218                // `put_arg` rather than `set_arg`: the array is the last thing on the
7219                // stack and nothing keeps it. Named by hand because a name in the
7220                // parameter list resolves to the parameter binding, and this store has to
7221                // reach the *argument* — that is what the body reads.
7222                self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
7223                continue;
7224            }
7225            if let PatternKind::Assign { default, .. } = &param.kind {
7226                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7227                let has_value = self.new_label();
7228                self.emit(Opcode::Dup, &[]);
7229                self.emit(Opcode::IsUndefined, &[]);
7230                self.emit_jump(Opcode::IfFalse, has_value, &[]);
7231                self.emit(Opcode::Drop, &[]);
7232                self.expr(default)?;
7233                self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
7234                // The argument slot keeps the substituted value, because the *body* reads
7235                // the slot rather than the parameter binding — so this store is named
7236                // explicitly, like the rest parameter's.
7237                self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7238                self.place_label(has_value);
7239                if let Some(slot) = target {
7240                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7241                }
7242                continue;
7243            }
7244            if let Some(slot) = target {
7245                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
7246                self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
7247            }
7248        }
7249        // Copy the parameter scope into the body. A plain parameter needs nothing: the
7250        // body reads its argument slot, and the list kept the two in step. A name a
7251        // pattern bound has no argument slot of its own, so the body gets a `var` filled
7252        // from the parameter's copy — and *that* is why an assignment inside a default
7253        // does not reach the body.
7254        if has_param_scope {
7255            for (_, pattern) in &prologue {
7256                let mut names = Vec::new();
7257                pattern.bound_names(&mut names);
7258                for name in names {
7259                    let Some(slot) = self.param_binding_slot(&name.name) else {
7260                        continue;
7261                    };
7262                    let Some(body) = self.body_var_slot(&name.name) else {
7263                        continue;
7264                    };
7265                    self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
7266                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
7267                }
7268            }
7269        }
7270        // The parameter list is over; from here on a direct `eval` belongs to the body.
7271        self.state().in_params = false;
7272        // Entering the body's own scope comes *after* the parameter list: the body's
7273        // `let`s are not in existence while the defaults run, and the reference emits
7274        // their `set_loc_uninitialized` only once the parameters are bound.
7275        self.emit_scope_enter(body_key);
7276        // A generator starts suspended: `initial_yield` parks the body so that creating one
7277        // runs no body code until the first `next()`.
7278        //
7279        // It comes *after* the parameter unpacking, not before, because a parameter
7280        // initialiser is not body code — `function* g(a = sideEffect())` must run
7281        // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
7282        // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
7283        // until the first `next()` and 29 test262 cases that check for a synchronous throw
7284        // saw none at all.
7285        //
7286        // An async function does **not** get one. Its body runs synchronously up to the
7287        // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
7288        // before its caller's next statement — so an `initial_yield` here would park the
7289        // body before it started, which is not fixable at run time: the suspension looks
7290        // exactly like a real `await`.
7291        if self.cur().kind.is_generator() {
7292            self.emit(Opcode::InitialYield, &[]);
7293        }
7294        // Through `stmts`: the body is a block, and a `using` declaration in it is a
7295        // disposal region.
7296        self.stmts(body)?;
7297        // The implicit return only exists if control can actually get here: an
7298        // infinite loop never falls off the end.
7299        if self.end_is_reachable() {
7300            if self.cur().is_suspending() {
7301                // Falling off the end finishes the generator with `undefined`, and the
7302                // value is what tells the resume machinery "completed" rather than
7303                // "suspended".
7304                self.emit(Opcode::Undefined, &[]);
7305                self.emit(Opcode::ReturnAsync, &[]);
7306            } else {
7307                self.emit_class_constructor_tail();
7308            }
7309        }
7310        // Resolution runs while this function is still on the stack: capturing a
7311        // variable from an enclosing function means reaching into that
7312        // function's state, which requires the whole chain to be present.
7313        Ok(self.finish_current())
7314    }
7315
7316    /// Put every binding of a function that contains a direct `eval` into a cell.
7317    ///
7318    /// A direct eval can name any binding in scope, and any closure it creates has to
7319    /// keep sharing that binding after the function returns — `for (let i …)
7320    /// eval("push(() => i)")` collects one closure per iteration and each must read its
7321    /// own `i`. A copy in a side table would freeze the value, so the binding has to be
7322    /// a cell. Doing this unconditionally for such functions is the cheap, honest
7323    /// answer: the alternative is knowing at compile time which names a string will
7324    /// mention.
7325    fn capture_everything_for_eval(&mut self) {
7326        let current = self.stack.len() - 1;
7327        if !self.stack[current].has_direct_eval {
7328            return;
7329        }
7330        for arg in &mut self.stack[current].args {
7331            arg.is_captured = true;
7332        }
7333        for var in &mut self.stack[current].vars {
7334            var.is_captured = true;
7335        }
7336    }
7337
7338    /// Whether the current position in the instruction stream can be reached.
7339    ///
7340    /// A walk over the control-flow graph, using labels as instruction indices.
7341    /// The reference does the same thing to decide whether an implicit
7342    /// `return_undef` is needed.
7343    fn end_is_reachable(&self) -> bool {
7344        let state = self.cur();
7345        reachable_instructions(state, state.insns.len())[state.insns.len()]
7346    }
7347
7348    /// Resolve and assemble the function on top of the compiler stack, then pop
7349    /// it.
7350    fn finish_current(&mut self) -> CompiledFunction {
7351        self.provide_param_arguments();
7352        self.provide_arguments();
7353        self.provide_this_local();
7354        self.provide_new_target_local();
7355        self.provide_home_object_local();
7356        self.provide_active_func_local();
7357        self.provide_self_name();
7358        self.materialize_eval_sites();
7359        self.capture_everything_for_eval();
7360        let (mut resolved, resolved_pos) = resolve(&mut self.stack);
7361        // Captured bindings need a reference cell; the count goes in the header so
7362        // the runtime knows how many cells to allocate on entry.
7363        let current = self.stack.len() - 1;
7364        let captured = self.stack[current]
7365            .args
7366            .iter()
7367            .filter(|a| a.is_captured)
7368            .count()
7369            + self.stack[current]
7370                .vars
7371                .iter()
7372                .filter(|v| v.is_captured)
7373                .count();
7374        self.stack[current].var_ref_count = captured as u32;
7375        // The scope chain is only final now that every binding is known.
7376        rebuild_scope_chain(&mut self.stack[current]);
7377        let (code, stack_size, positions) =
7378            assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
7379        let _ = &mut resolved;
7380        let mut state = self.stack.pop().expect("a function is being compiled");
7381        CompiledFunction {
7382            name: state.name,
7383            kind: state.kind,
7384            strict: state.strict,
7385            is_arrow: state.is_arrow,
7386            has_parameter_expressions: state.has_parameter_expressions,
7387            body_start: state.body_start,
7388            args: state.args,
7389            defined_args: state.defined_args,
7390            vars: state.vars,
7391            closure_vars: state.closure_vars,
7392            cpool: state.cpool,
7393            atoms: state.atoms,
7394            code,
7395            stack_size,
7396            var_ref_count: state.var_ref_count,
7397            positions,
7398            source: None,
7399            line: state.line,
7400            column: state.column,
7401            filename: None,
7402            eval_sites: state.eval_sites,
7403            module: state.module.take().map(Box::new),
7404        }
7405    }
7406}
7407
7408/// Assign each binding a scope level and rebuild the scope chains.
7409///
7410/// Levels are numbered in the order the blocks appear, with 0 reserved for the
7411/// function scope where `var` and hoisted functions live. Every binding outside
7412/// level 0 gets a `scope_next` link to the next binding visible from the same
7413/// point, so walking a block's chain enumerates exactly the bindings live there.
7414///
7415/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
7416/// point at `b`, which is declared later in the source but earlier in the chain.
7417fn rebuild_scope_chain(state: &mut FnState) {
7418    // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
7419    // real block that happens to start at offset zero keeps its own level instead of
7420    // being merged into the function scope.
7421    let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
7422    for block in &state.blocks {
7423        if !levels.contains(&block.key) {
7424            levels.push(block.key);
7425        }
7426    }
7427    let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
7428    let parent_level = |level: usize| -> usize {
7429        if level == 0 {
7430            return 0;
7431        }
7432        let key = levels[level];
7433        let parent = state
7434            .blocks
7435            .iter()
7436            .find(|b| b.key == key)
7437            .map(|b| b.parent)
7438            .unwrap_or(FUNCTION_SCOPE);
7439        level_of(parent)
7440    };
7441
7442    // Own bindings per level, in declaration order.
7443    let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
7444    let keys: Vec<u64> = (0..state.vars.len())
7445        .map(|index| {
7446            state
7447                .var_block
7448                .get(index)
7449                .copied()
7450                .unwrap_or(FUNCTION_SCOPE)
7451        })
7452        .collect();
7453    for (index, key) in keys.into_iter().enumerate() {
7454        // The parameter scope is not a block: it is a level of its own with no parent,
7455        // assigned below. Letting it land in level 0 would chain the body's bindings onto
7456        // it, which the reference does not do — the two environments are siblings.
7457        if key == PARAM_SCOPE {
7458            continue;
7459        }
7460        let level = level_of(key);
7461        state.vars[index].scope_level = level as u32;
7462        // A `catch` parameter is part of the runtime scope chain even though it is
7463        // not lexical: the handler's own bindings chain on to it, which is why the
7464        // reference prints `let y [next:1]` with `e` at 1.
7465        if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
7466        {
7467            own[level].push(index);
7468        }
7469    }
7470
7471    // A scope's chain is its own bindings in reverse declaration order followed
7472    // by the enclosing scope's chain.
7473    let mut head = vec![-1i32; levels.len()];
7474    for level in 0..levels.len() {
7475        let inherited = if level == 0 {
7476            -1
7477        } else {
7478            head[parent_level(level)]
7479        };
7480        let chain: Vec<usize> = own[level].iter().rev().copied().collect();
7481        head[level] = chain.first().map_or(inherited, |first| *first as i32);
7482        for (position, &index) in chain.iter().enumerate() {
7483            let next = chain
7484                .get(position + 1)
7485                .map_or(inherited, |next| *next as i32);
7486            state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
7487        }
7488    }
7489    state.block_heads = head;
7490
7491    // The parameter list is a scope of its own, and it has no parent: the reference pops
7492    // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
7493    // the `-1` a block uses. A level past every real block keeps it out of the walk above
7494    // — nothing but the dump reads it — and the links run newest-to-oldest through the
7495    // bindings themselves, which is the order `set_loc_uninitialized` walks.
7496    let param_level = levels.len() as u32;
7497    let mut previous: Option<usize> = None;
7498    for index in 0..state.vars.len() {
7499        if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
7500        {
7501            continue;
7502        }
7503        state.vars[index].scope_level = param_level;
7504        state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
7505        previous = Some(index);
7506    }
7507}
7508
7509/// This is where names become slots and where the temporal dead zone shows up in
7510/// the instruction stream: a read of a `let`/`const` binding compiles to
7511/// `get_loc_check`, which throws if the binding is still uninitialised.
7512///
7513/// The peephole pass from the reference implementation is applied at the end,
7514/// for the same reason it is applied to resolved bytecode there: the patterns are
7515/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
7516/// resolution. Deleted instructions stay in the list as `None` so that label
7517/// indices remain valid; [`Assembler`] maps them to byte offsets.
7518/// A resolved instruction and the source position it came from.
7519type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
7520
7521/// A resolved instruction paired with its position, which is what `assemble` consumes.
7522type PositionedInsn = (Opcode, Vec<Op>);
7523
7524fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
7525    let current = stack.len() - 1;
7526    // Dead-code elimination, on the symbolic form where labels are still
7527    // instruction indices. A `break` inside a loop leaves the trailing `goto`
7528    // unreachable, and a `return` leaves everything after it unreachable; the
7529    // reference drops both. Doing it here means the emitter never has to think
7530    // about reachability.
7531    strip_empty_gosubs(stack, current);
7532    eliminate_dead_code(stack, current);
7533    let insns = std::mem::take(&mut stack[current].insns);
7534    // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
7535    // `insns`, and every arm below pushes exactly one instruction, so the positions
7536    // stay aligned with `out`.
7537    let positions = std::mem::take(&mut stack[current].insn_pos);
7538    let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
7539    let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
7540    for (index, insn) in insns.iter().enumerate() {
7541        let pos = positions.get(index).copied().flatten();
7542        out_pos.push(pos);
7543        match insn {
7544            Insn::Fixed { op, operands } => {
7545                let operands = operands
7546                    .iter()
7547                    .map(|operand| match operand {
7548                        Op::Atom(atom) => {
7549                            Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
7550                        }
7551                        other => other.clone(),
7552                    })
7553                    .collect();
7554                out.push(Some((*op, operands)));
7555            }
7556            Insn::Var {
7557                action,
7558                name,
7559                block,
7560                in_params,
7561            } => {
7562                // Both reads and writes in the parameter list address the parameter
7563                // scope. That is what puts the list in the temporal dead zone — a read of
7564                // a later parameter is `get_loc_check` on an uninitialised slot — and it
7565                // is also what keeps an assignment made inside a default away from the
7566                // body, which sees a separate environment.
7567                let slot = resolve_slot(stack, current, name, *block, *in_params);
7568                // A store to the name of a named function expression is special: the
7569                // reference drops it in sloppy mode and throws in strict mode, because
7570                // the binding is immutable but only *checked* when the body is strict.
7571                // The same rule applies when the name is reached through a closure:
7572                // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
7573                // the store in the arrow too, not just in the function that owns the
7574                // binding. Reaching the owner means walking the chain of closure
7575                // entries, which is what `self_name_binding` does.
7576                let self_name = matches!(action, VarAction::Put | VarAction::Set)
7577                    .then(|| {
7578                        // A local of this function is the common case and needs no
7579                        // chain walk; only an access that resolves elsewhere can be
7580                        // pointing at an enclosing function's name binding.
7581                        if let Slot::Loc(index) = slot {
7582                            stack[current]
7583                                .vars
7584                                .get(index as usize)
7585                                .filter(|var| var.kind == VarKind::FunctionName)
7586                                .map(|var| var.is_const)
7587                        } else {
7588                            self_name_binding(stack, current, name, *block)
7589                        }
7590                    })
7591                    .flatten();
7592                if let Some(is_const) = self_name {
7593                    out.push(Some(if is_const {
7594                        (
7595                            Opcode::ThrowError,
7596                            vec![
7597                                Op::AtomId(intern_atom(&mut stack[current], name)),
7598                                Op::Int(0),
7599                            ],
7600                        )
7601                    } else {
7602                        (Opcode::Drop, Vec::new())
7603                    }));
7604                    continue;
7605                }
7606                out.push(Some(variable_instruction(stack, current, *action, slot)));
7607            }
7608            Insn::CloseCaptured { name, block } => {
7609                // The block matters: a loop variable is scoped to the `for` head's own
7610                // block, so resolving it against block 0 would miss it entirely and
7611                // silently emit nothing.
7612                let slot = resolve_slot(stack, current, name, *block, false);
7613                // Only a local with a reference cell has anything to close. A global
7614                // or a never-captured local resolves to no instruction at all, which
7615                // keeps the bytecode identical to the reference's.
7616                if let Slot::Loc(index) = slot
7617                    && stack[current]
7618                        .vars
7619                        .get(index as usize)
7620                        .is_some_and(|v| v.is_captured)
7621                {
7622                    out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
7623                } else {
7624                    out.push(None);
7625                }
7626            }
7627            Insn::DeleteVar { name } => {
7628                // A binding — a local, an argument, or a declared global — cannot be
7629                // deleted, and the reference encodes that as a constant `push_false`.
7630                // Only an implicit global needs the runtime lookup.
7631                if matches!(
7632                    resolve_slot(stack, current, name, 0, false),
7633                    Slot::Global(_)
7634                ) {
7635                    let atom = intern_atom(&mut stack[current], name);
7636                    out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
7637                } else {
7638                    out.push(Some((Opcode::PushFalse, Vec::new())));
7639                }
7640            }
7641            Insn::Dead => out.push(None),
7642        }
7643    }
7644    // Which label (if any) sits on each instruction, so the jump patterns can
7645    // tell whether they would cross a jump target.
7646    let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
7647    for (id, placed) in stack[current].labels.iter().enumerate() {
7648        if let Some(index) = *placed
7649            && index < label_at.len()
7650            && label_at[index].is_none()
7651        {
7652            label_at[index] = Some(id as u32);
7653        }
7654    }
7655    if std::env::var_os("QJS_DEBUG").is_some() {
7656        eprintln!("--- peephole entry ---");
7657        for (i, e) in out.iter().enumerate() {
7658            eprintln!("{i}: {e:?}");
7659        }
7660        eprintln!("label_at: {label_at:?}");
7661    }
7662    peephole(&mut out, &label_at, &stack[current].labels);
7663    (out, out_pos)
7664}
7665
7666/// Find where `name` lives, capturing it in an enclosing function when needed.
7667///
7668/// The search runs outward through the enclosing functions' states, which are
7669/// still on the compiler stack while a nested function is resolved. Finding the
7670/// name in an enclosing function is what creates a closure reference, and every
7671/// function in between has to forward it — a function can only reach its own
7672/// parent's frame.
7673///
7674/// A name declared nowhere is a global. The reference does *not* look it up by
7675/// name from the inner function: the top-level function gets one `[global]`
7676/// entry and every nested function gets a `[global_ref<n>]` pointing at its
7677/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
7678/// rather than `[global]`.
7679/// The lexical blocks enclosing `block`, innermost first.
7680fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
7681    let mut chain = Vec::new();
7682    let mut current = Some(block);
7683    while let Some(key) = current {
7684        // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
7685        // explicitly (rather than on "no block with this key") is what keeps a block
7686        // that happens to sit at offset zero from being mistaken for the terminator.
7687        if key == NO_PARENT || chain.contains(&key) {
7688            break;
7689        }
7690        chain.push(key);
7691        current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
7692    }
7693    chain
7694}
7695
7696/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
7697///
7698/// The binding may be several functions away: an arrow nested in `function myfunc`
7699/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
7700/// means following `Ref` entries down and then reading the owning function's var table.
7701fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
7702    let state = stack.get(current)?;
7703    // A parameter shadows everything and is never a function-expression name.
7704    if state.args.iter().any(|arg| arg.name == name) {
7705        return None;
7706    }
7707    // A local of this very function: the answer is in its var table.
7708    if let Some(index) = local_slot_index(state, name, block) {
7709        let var = state.vars.get(index)?;
7710        return (var.kind == VarKind::FunctionName).then_some(var.is_const);
7711    }
7712    // Otherwise the name lives further out, and the closure entry says how to get
7713    // there. `Local` names the owner's slot directly; `Ref` names the next level's
7714    // closure entry, so the walk continues downwards.
7715    let mut level = current;
7716    let mut index = state
7717        .closure_vars
7718        .iter()
7719        .position(|closure| closure.name == name)?;
7720    loop {
7721        let state = stack.get(level)?;
7722        let closure = state.closure_vars.get(index)?;
7723        match closure.closure_type {
7724            ClosureType::Local => {
7725                let owner = stack.get(level.checked_sub(1)?)?;
7726                let var = owner.vars.get(closure.var_idx as usize)?;
7727                return (var.kind == VarKind::FunctionName).then_some(var.is_const);
7728            }
7729            ClosureType::Arg => return None,
7730            ClosureType::Ref => {
7731                level -= 1;
7732                index = closure.var_idx as usize;
7733            }
7734            // A global is never a function-expression name.
7735            ClosureType::Global
7736            | ClosureType::GlobalDecl
7737            | ClosureType::GlobalRef
7738            | ClosureType::ModuleDecl
7739            | ClosureType::ModuleImport => return None,
7740        }
7741    }
7742}
7743
7744/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
7745fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
7746    block_chain(state, block).into_iter().find_map(|scope| {
7747        state.vars.iter().enumerate().find_map(|(index, var)| {
7748            (var.name == name && state.var_block.get(index).copied() == Some(scope))
7749                .then_some(index)
7750        })
7751    })
7752}
7753
7754/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
7755fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
7756    if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
7757        var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
7758    }) {
7759        return index as u32;
7760    }
7761    state.var_block.push(PARAM_SCOPE);
7762    state.vars.push(VarDef::var(name));
7763    state.vars.len() as u32 - 1
7764}
7765
7766/// The name a parameter binds straight from its argument slot, if it has one.
7767///
7768/// A plain name does — with or without a default, and with or without `...`. Everything
7769/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
7770/// reference names the argument in the first case and leaves it `<null>` in the second,
7771/// so both the dump and the closures that capture the argument depend on this.
7772fn simple_parameter(param: &Pattern) -> Option<&Ident> {
7773    match &param.kind {
7774        PatternKind::Ident(name) => Some(name),
7775        PatternKind::Assign { target, .. } => match &target.kind {
7776            PatternKind::Ident(name) => Some(name),
7777            _ => None,
7778        },
7779        PatternKind::Rest(inner) => match &inner.kind {
7780            PatternKind::Ident(name) => Some(name),
7781            _ => None,
7782        },
7783        _ => None,
7784    }
7785}
7786
7787/// The pattern a parameter list has to unpick, if `index` is one of them.
7788fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
7789    prologue
7790        .iter()
7791        .find(|(at, _)| *at == index)
7792        .map(|(_, pattern)| pattern)
7793}
7794
7795/// Whether a parameter pattern contains a default anywhere, at any depth.
7796///
7797/// The reference decides "this function has parameter expressions" by scanning the
7798/// parenthesis for a top-level `=`, which a default buried in a pattern still counts as —
7799/// `function f({a = 1})` has a parameter scope just like `function f(a = 1)`.
7800fn pattern_has_default(pattern: &Pattern) -> bool {
7801    match &pattern.kind {
7802        PatternKind::Assign { .. } => true,
7803        PatternKind::Rest(inner) => pattern_has_default(inner),
7804        PatternKind::Array { elements, rest } => {
7805            elements.iter().flatten().any(element_has_default)
7806                || rest.as_deref().is_some_and(rest_has_default)
7807        }
7808        PatternKind::Object { properties, rest } => {
7809            properties.iter().flatten().any(element_has_default)
7810                || rest.as_deref().is_some_and(rest_has_default)
7811        }
7812        _ => false,
7813    }
7814}
7815
7816fn element_has_default(element: &PatternElement) -> bool {
7817    match element {
7818        PatternElement::Pattern(pattern) => pattern_has_default(pattern),
7819        PatternElement::Property { value, .. } => pattern_has_default(value),
7820    }
7821}
7822
7823fn rest_has_default(rest: &RestElement) -> bool {
7824    match rest {
7825        RestElement::Pattern(pattern) => pattern_has_default(pattern),
7826        RestElement::Member(_) => false,
7827    }
7828}
7829
7830/// Whether a function-scope binding is visible to the parameter list.
7831///
7832/// The parameter list runs before the body, so the body's `var`s and function
7833/// declarations do not exist yet — a name that only the body declares has to resolve
7834/// outward instead. What *does* exist by then is the compiler's own prologue: the
7835/// self-name of a named function expression (bound by `special_object 2` before anything
7836/// else), `this` and `new.target`. Those stay visible, which is what makes
7837/// `function f(a = this)` and `var f = function f(a = f)` work.
7838///
7839/// `arguments` is handled separately, as a binding of the parameter scope itself: with
7840/// parameter expressions the reference creates two of them, and the one the parameter
7841/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
7842fn visible_in_params(var: &VarDef) -> bool {
7843    var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
7844}
7845
7846fn resolve_slot(
7847    stack: &mut [FnState],
7848    current: usize,
7849    name: &str,
7850    block: u64,
7851    in_params: bool,
7852) -> Slot {
7853    // The parameter list's own bindings. They are consulted first because they shadow
7854    // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
7855    // `a` in the parameter scope, so a closure made there reads the parameter even after
7856    // the body assigns to its own `a`.
7857    if in_params
7858        && let Some(index) = stack[current]
7859            .vars
7860            .iter()
7861            .enumerate()
7862            .position(|(index, var)| {
7863                var.name == name
7864                    && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
7865            })
7866    {
7867        return Slot::Loc(index as u32);
7868    }
7869    // A name can be bound more than once: two `catch` parameters in nested
7870    // handlers are two slots. The binding that wins is the one whose scope encloses
7871    // the access, and among those the innermost — so the blocks are walked outward
7872    // and the first binding found on the way is the one that counts. A binding in
7873    // no block (`var`) is reachable from anywhere, which is why the function scope
7874    // is the end of the walk.
7875    //
7876    // The block walk comes *before* the argument slots, because a block may shadow a
7877    // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
7878    // slot is only the answer once nothing nearer claims the name.
7879    let chain = block_chain(&stack[current], block);
7880    for scope in &chain {
7881        let found = stack[current]
7882            .vars
7883            .iter()
7884            .enumerate()
7885            .find(|(index, var)| {
7886                var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
7887            })
7888            .map(|(index, _)| index);
7889        if let Some(index) = found {
7890            return Slot::Loc(index as u32);
7891        }
7892    }
7893    // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
7894    // its own slot, and `var` of the same name in the body is the same binding.
7895    if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
7896        return Slot::Arg(index as u32);
7897    }
7898    // Function-scope bindings — `var` and function declarations — are recorded with
7899    // the sentinel block `0`, which no real scope uses, so the walk above cannot see
7900    // them. They are reachable from anywhere in the function, which is exactly what
7901    // the sentinel means.
7902    //
7903    // This pass is *only* for those. A lexical binding has to be found through the
7904    // chain or not at all, and looking a name up without its block is precisely how
7905    // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
7906    // block leaked out of it.
7907    let function_scoped = stack[current]
7908        .vars
7909        .iter()
7910        .enumerate()
7911        .find(|(index, var)| {
7912            var.name == name
7913                && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
7914                && (!in_params || visible_in_params(var))
7915        })
7916        .map(|(index, _)| index);
7917    if let Some(index) = function_scoped {
7918        return Slot::Loc(index as u32);
7919    }
7920    if let Some(index) = stack[current]
7921        .closure_vars
7922        .iter()
7923        .position(|c| c.name == name)
7924    {
7925        return slot_for_closure(&stack[current].closure_vars[index], index as u32);
7926    }
7927
7928    for owner in (0..current).rev() {
7929        // The nested function was created inside one of this frame's blocks, and the
7930        // outermost visible binding is the innermost block on that chain — not whatever
7931        // comes first in the variable table. `function f(){ class S{} }` has two `S`
7932        // bindings: the `let S` inside `f` and the `const S` inside the class body, and
7933        // the class body is the one a method may see.
7934        let entry = stack
7935            .get(owner + 1)
7936            .map(|s| s.created_in_block)
7937            .unwrap_or(0);
7938        let lexical = block_chain(&stack[owner], entry)
7939            .into_iter()
7940            .find_map(|scope| {
7941                stack[owner]
7942                    .vars
7943                    .iter()
7944                    .enumerate()
7945                    .find(|(index, var)| {
7946                        var.name == name
7947                            && stack[owner].var_block.get(*index).copied() == Some(scope)
7948                    })
7949                    .map(|(index, _)| index)
7950            });
7951        // A function born in a parameter list sees that list's bindings, not the body's:
7952        // the parameter scope is the environment it was created in.
7953        let in_param_scope = stack
7954            .get(owner + 1)
7955            .is_some_and(|child| child.created_in_params)
7956            .then(|| {
7957                stack[owner]
7958                    .vars
7959                    .iter()
7960                    .enumerate()
7961                    .position(|(index, var)| {
7962                        var.name == name
7963                            && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
7964                    })
7965            })
7966            .flatten();
7967        let found = if let Some(index) = in_param_scope {
7968            let var = &stack[owner].vars[index];
7969            Some(Found::Local(
7970                ClosureType::Local,
7971                index as u32,
7972                var.is_const,
7973                var.needs_check(),
7974            ))
7975        } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
7976            Some(Found::Local(ClosureType::Arg, index as u32, false, false))
7977        } else if let Some(index) = lexical {
7978            let var = &stack[owner].vars[index];
7979            Some(Found::Local(
7980                ClosureType::Local,
7981                index as u32,
7982                var.is_const,
7983                var.needs_check(),
7984            ))
7985        } else if let Some(index) = stack[owner]
7986            .vars
7987            .iter()
7988            .enumerate()
7989            .find_map(|(index, var)| {
7990                // A function created inside a parameter list must not see the body of the
7991                // function it was born in; see [`FnState::created_in_params`].
7992                let hidden = stack
7993                    .get(owner + 1)
7994                    .is_some_and(|child| child.created_in_params);
7995                (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
7996            })
7997        {
7998            let var = &stack[owner].vars[index];
7999            Some(Found::Local(
8000                ClosureType::Local,
8001                index as u32,
8002                var.is_const,
8003                var.needs_check(),
8004            ))
8005        } else if stack[owner].self_name.as_deref() == Some(name) {
8006            // A named function expression's own name. The reference declares it here,
8007            // on the first lookup that fails, rather than up front — and that is what
8008            // makes it reachable from a *nested* function: the nested lookup is what
8009            // walks out and creates the binding. A direct reference in the body is
8010            // caught the same way, which is why `provide_self_name` only has to add
8011            // the prologue.
8012            let strict = stack[owner].strict;
8013            stack[owner].var_block.push(FUNCTION_SCOPE);
8014            stack[owner].vars.push(VarDef {
8015                kind: VarKind::FunctionName,
8016                // In strict mode the name is immutable, so a store raises; sloppy
8017                // mode drops the store instead (see `variable_instruction`).
8018                is_const: strict,
8019                ..VarDef::var(name)
8020            });
8021            let index = stack[owner].vars.len() as u32 - 1;
8022            Some(Found::Local(ClosureType::Local, index, strict, false))
8023        } else if let Some(index) = stack[owner]
8024            .closure_vars
8025            .iter()
8026            .position(|c| c.name == name)
8027        {
8028            let closure = &stack[owner].closure_vars[index];
8029            Some(match closure.closure_type {
8030                // `GlobalRef` belongs here too: it is a *global* reached through this
8031                // frame's reference table, so treating it as a `Ref` to a local cell makes
8032                // the reader look for a cell no frame ever fills. That is how a second
8033                // function using `eval` in its parameter list read `undefined` after a
8034                // sibling had already made `eval` a closure entry.
8035                ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
8036                    Found::Global(index as u32)
8037                }
8038                // A module variable is a cell in the *module's* environment, which is
8039                // the module body's parent as far as a nested function is concerned — so
8040                // it is captured as a plain reference, not looked up as a global.
8041                ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
8042                    ClosureType::Ref,
8043                    index as u32,
8044                    closure.is_const,
8045                    closure.is_lexical,
8046                ),
8047                _ => Found::Local(
8048                    ClosureType::Ref,
8049                    index as u32,
8050                    closure.is_const,
8051                    closure.is_lexical,
8052                ),
8053            })
8054        } else {
8055            None
8056        };
8057        let Some(found) = found else { continue };
8058
8059        let (is_const, is_lexical) = match found {
8060            Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
8061            Found::Global(_) => (false, false),
8062        };
8063        // Mark the owner's binding as captured so it moves into a reference cell.
8064        if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
8065            let slot = match found {
8066                Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
8067                _ => &mut stack[owner].vars[index as usize],
8068            };
8069            slot.is_captured = true;
8070        }
8071        // Forward the reference through every function in between.
8072        let mut previous = match found {
8073            Found::Local(kind, index, _, _) => (kind, index),
8074            Found::Global(index) => (ClosureType::Global, index),
8075        };
8076        for level in owner + 1..=current {
8077            let kind = match (previous.0, level) {
8078                // A global stays a global at *every* level. Without `GlobalRef` in
8079                // this arm the second nested function over the same global got a
8080                // `Ref` to a cell no frame ever held, so the innermost closure read
8081                // `undefined` — which is how a two-deep getter lost its outer
8082                // variable.
8083                (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
8084                    ClosureType::GlobalRef
8085                }
8086                (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
8087                _ => ClosureType::Ref,
8088            };
8089            let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
8090            previous = (kind, index);
8091        }
8092        let index = previous.1;
8093        return slot_for_closure(&stack[current].closure_vars[index as usize], index);
8094    }
8095
8096    // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
8097    // creating a property. The top-level function holds the entry.
8098    let mut previous = (
8099        ClosureType::Global,
8100        ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
8101    );
8102    for level in 1..=current {
8103        let index = ensure_closure(
8104            stack,
8105            level,
8106            name,
8107            false,
8108            false,
8109            ClosureType::GlobalRef,
8110            previous.1,
8111        );
8112        previous = (ClosureType::GlobalRef, index);
8113    }
8114    Slot::Global(previous.1)
8115}
8116
8117/// What an outward search turned up.
8118#[derive(Debug, Clone, Copy)]
8119enum Found {
8120    /// A binding in an enclosing function, reachable through a closure of this
8121    /// type, with its const/lexical flags.
8122    Local(ClosureType, u32, bool, bool),
8123    /// A global, reached through the enclosing function's closure entry.
8124    Global(u32),
8125}
8126
8127/// Add a closure entry to `level` if it is not there yet.
8128fn ensure_closure(
8129    stack: &mut [FnState],
8130    level: usize,
8131    name: &str,
8132    is_const: bool,
8133    is_lexical: bool,
8134    closure_type: ClosureType,
8135    var_idx: u32,
8136) -> u32 {
8137    if let Some(index) = stack[level]
8138        .closure_vars
8139        .iter()
8140        .position(|c| c.name == name)
8141    {
8142        return index as u32;
8143    }
8144    stack[level].closure_vars.push(ClosureVar {
8145        name: name.to_string(),
8146        is_const,
8147        is_lexical,
8148        closure_type,
8149        var_idx: var_idx as u16,
8150    });
8151    stack[level].closure_vars.len() as u32 - 1
8152}
8153
8154fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
8155    match closure.closure_type {
8156        // A `global_ref` only says *how* the binding is found (through the
8157        // parent's closure table); the access itself is an ordinary global one.
8158        ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
8159        ClosureType::GlobalDecl => Slot::GlobalDecl(index),
8160        // A module variable is a real cell in the module's environment, so it is reached
8161        // exactly like a captured local — the host, not the global object, is what fills
8162        // the slot.
8163        ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
8164        _ => Slot::VarRef(index),
8165    }
8166}
8167
8168/// Pick the opcode for one variable access.
8169///
8170/// The `_check` variants are what enforce the temporal dead zone. They are used
8171/// for every access to a `let`/`const` binding except its own initialisation —
8172/// which is exactly the operation that takes the binding out of the dead zone.
8173fn variable_instruction(
8174    stack: &[FnState],
8175    current: usize,
8176    action: VarAction,
8177    slot: Slot,
8178) -> (Opcode, Vec<Op>) {
8179    let lexical = match slot {
8180        Slot::Loc(index) => stack[current]
8181            .vars
8182            .get(index as usize)
8183            .is_some_and(|v| v.needs_check()),
8184        Slot::VarRef(index) => stack[current]
8185            .closure_vars
8186            .get(index as usize)
8187            .is_some_and(|c| c.is_lexical),
8188        _ => false,
8189    };
8190    let operand = vec![Op::Slot(slot)];
8191    match (action, slot) {
8192        (VarAction::Get, Slot::Loc(index)) => (
8193            if lexical {
8194                Opcode::GetLocCheck
8195            } else {
8196                Opcode::GetLoc
8197            },
8198            vec![Op::Slot(Slot::Loc(index))],
8199        ),
8200        (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
8201        (VarAction::Get, Slot::VarRef(index)) => (
8202            if lexical {
8203                Opcode::GetVarRefCheck
8204            } else {
8205                Opcode::GetVarRef
8206            },
8207            vec![Op::Slot(Slot::VarRef(index))],
8208        ),
8209        (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
8210        (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
8211        (VarAction::GetUndef, Slot::Loc(_)) => (Opcode::GetLoc, operand),
8212        (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
8213        (VarAction::GetUndef, Slot::VarRef(_)) => (Opcode::GetVarRef, operand),
8214        (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8215            (Opcode::GetVarUndef, operand)
8216        }
8217
8218        (VarAction::Put, Slot::Loc(_)) => (
8219            if lexical {
8220                Opcode::PutLocCheck
8221            } else {
8222                Opcode::PutLoc
8223            },
8224            operand,
8225        ),
8226        (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
8227        (VarAction::Put, Slot::VarRef(_)) => (
8228            if lexical {
8229                Opcode::PutVarRefCheck
8230            } else {
8231                Opcode::PutVarRef
8232            },
8233            operand,
8234        ),
8235        (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
8236        (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8237        // Initialisation is what ends the dead zone, so it never checks.
8238        (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8239        (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
8240        // `this` in a derived constructor is always a local, so these cannot happen;
8241        // routing them to the ordinary forms keeps the match total without inventing
8242        // opcodes the reference does not have.
8243        (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
8244        (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8245        (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8246            (Opcode::PutVarInit, operand)
8247        }
8248        (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
8249        (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8250        (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
8251            (Opcode::PutVarInit, operand)
8252        }
8253        (VarAction::Set, Slot::Loc(_)) => (
8254            if lexical {
8255                Opcode::SetLocCheck
8256            } else {
8257                Opcode::SetLoc
8258            },
8259            operand,
8260        ),
8261        (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
8262        (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
8263        (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8264        (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
8265        (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
8266        (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
8267        (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
8268        (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
8269        (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
8270        (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
8271        (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
8272        (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
8273    }
8274}
8275
8276/// The instruction-rewriting pass.
8277///
8278/// These are the reference implementation's patterns, restricted to the ones the
8279/// constructs this compiler supports can produce. Each entry is a comment on the
8280/// bytecode it removes, because the whole point is that the result is one
8281/// instruction shorter than the literal translation of the AST.
8282fn peephole(
8283    insns: &mut [Option<(Opcode, Vec<Op>)>],
8284    label_at: &[Option<u32>],
8285    placed: &[Option<usize>],
8286) {
8287    fold_dup_patterns(insns, label_at);
8288
8289    // `drop` before `return_undef` is dead: the return discards the whole frame
8290    // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
8291    // consumes its own `drop`; removing the drop first would leave the `dup` and
8292    // produce a `set_` where the reference has a `put_`.
8293    for index in 0..insns.len() {
8294        if opcode_at(insns, index) != Some(Opcode::Drop) {
8295            continue;
8296        }
8297        // Skip over a run of drops, but stop at a jump target: removing code on
8298        // one side of a label would silently retarget the jump.
8299        let mut next = index + 1;
8300        while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
8301            next += 1;
8302        }
8303        if is_label_at(label_at, next) {
8304            continue;
8305        }
8306        if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
8307            for entry in &mut insns[index..next] {
8308                *entry = None;
8309            }
8310        }
8311    }
8312
8313    // The rewrites below all decide against one fixed snapshot, which is what the
8314    // reference sees: `code_match` reads the bytecode buffer as it was on entry to
8315    // the pass, so a rule never observes what an earlier rule removed. Gathering
8316    // every deletion first and applying them together reproduces that.
8317    let snapshot: Vec<Option<Opcode>> = insns
8318        .iter()
8319        .map(|entry| entry.as_ref().map(|(op, _)| *op))
8320        .collect();
8321    // The next instruction that is still there. Holes left by dead-code
8322    // elimination are not instructions, so a rule looks past them.
8323    let next_op = |index: usize| -> Option<usize> {
8324        (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
8325    };
8326
8327    let mut doomed = vec![false; insns.len()];
8328    for index in 0..insns.len() {
8329        // A constant pushed only to be dropped does nothing at all. This is what a
8330        // comma expression with a literal left operand compiles to — `(0, f)()` — and
8331        // the reference removes the pair rather than making the reader step over it.
8332        let constant = matches!(
8333            snapshot[index],
8334            Some(
8335                Opcode::Undefined
8336                    | Opcode::Null
8337                    | Opcode::PushMinus1
8338                    | Opcode::Push0
8339                    | Opcode::Push1
8340                    | Opcode::Push2
8341                    | Opcode::Push3
8342                    | Opcode::Push4
8343                    | Opcode::Push5
8344                    | Opcode::Push6
8345                    | Opcode::Push7
8346                    | Opcode::PushTrue
8347                    | Opcode::PushFalse
8348                    | Opcode::PushI32
8349            )
8350        );
8351        if constant
8352            && let Some(next) = next_op(index)
8353            && snapshot[next] == Some(Opcode::Drop)
8354        {
8355            doomed[index] = true;
8356            doomed[next] = true;
8357        }
8358    }
8359    for (index, entry) in insns.iter_mut().enumerate() {
8360        if doomed[index] {
8361            *entry = None;
8362        }
8363    }
8364
8365    // A conditional whose destination is the very next instruction just pops its
8366    // condition, so it becomes a plain `drop`. This is what an empty `case` clause
8367    // compiles to.
8368    //
8369    // Order matters, and it is the reference's order: this runs *before* the
8370    // folding below, on the instruction the conditional originally had. Folding
8371    // moves a conditional's destination, and the reference never re-examines it
8372    // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
8373    // a conditional even though folding leaves it pointing at the next
8374    // instruction.
8375    for (index, entry) in insns.iter_mut().enumerate() {
8376        let Some((op, operands)) = entry.clone() else {
8377            continue;
8378        };
8379        if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
8380            continue;
8381        }
8382        let Some(id) = label_id(&operands) else {
8383            continue;
8384        };
8385        if placed.get(id as usize).copied().flatten() == Some(index + 1) {
8386            *entry = Some((Opcode::Drop, Vec::new()));
8387        }
8388    }
8389
8390    // A constant condition is decided here rather than at run time.
8391    fold_constant_conditions(insns);
8392    // The conditional folding below is about pairs of *real* branches, so it runs
8393    // before a jump to the next instruction is dropped: `do { … if (c) continue }
8394    // while (t)` puts `continue` exactly on the condition, and the reference inverts
8395    // the branch first and only then notices the jump goes nowhere.
8396    fold_conditional_jumps(insns, label_at, placed);
8397
8398    // A jump whose destination is the very next instruction does nothing, which is
8399    // what constant folding leaves behind for `while (1) { … }`.
8400    remove_jump_to_next(insns, placed);
8401
8402    // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
8403    // a use of the same variable boils down to.
8404    for index in 0..insns.len() {
8405        let Some((put_op, _)) = insns[index].clone() else {
8406            continue;
8407        };
8408        if !is_foldable_put(put_op) {
8409            continue;
8410        }
8411        if is_label_at(label_at, index + 1) {
8412            continue;
8413        }
8414        let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
8415            continue;
8416        };
8417        if get_op != get_form_of(put_op) {
8418            continue;
8419        }
8420        let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
8421        if put_slot.is_none() || put_slot != get_operands.first().cloned() {
8422            continue;
8423        }
8424        insns[index] = Some((set_form_of(put_op), get_operands));
8425        insns[index + 1] = None;
8426    }
8427}
8428
8429/// Drop `gosub`s that call an empty subroutine.
8430///
8431/// A `gosub` whose target starts with `ret` returns immediately, so the reference
8432/// drops the call. This is how `try`/`catch` without a `finally` loses its
8433/// finalizer plumbing: the finalizer block is empty, its first instruction is
8434/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
8435/// [`eliminate_dead_code`] then removes.
8436fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
8437    let state = &stack[current];
8438    let mut targets = Vec::new();
8439    for insn in &state.insns {
8440        if let Insn::Fixed { op, operands } = insn
8441            && *op == Opcode::Gosub
8442            && let Some(id) = label_id(operands)
8443            && let Some(target) = state.labels.get(id as usize).copied().flatten()
8444        {
8445            targets.push(target);
8446        }
8447    }
8448    let empty: Vec<usize> = targets
8449        .into_iter()
8450        .filter(|target| {
8451            stack[current]
8452                .insns
8453                .get(*target)
8454                .map(|insn| {
8455                    matches!(
8456                        insn,
8457                        Insn::Fixed {
8458                            op: Opcode::Ret,
8459                            ..
8460                        }
8461                    )
8462                })
8463                .unwrap_or(false)
8464        })
8465        .collect();
8466    if empty.is_empty() {
8467        return;
8468    }
8469    for insn in stack[current].insns.iter_mut() {
8470        if let Insn::Fixed { op, operands } = insn
8471            && *op == Opcode::Gosub
8472            && let Some(id) = label_id(operands)
8473            && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
8474            && empty.contains(&target)
8475        {
8476            *insn = Insn::Dead;
8477        }
8478    }
8479}
8480
8481/// Replace unreachable instructions with [`Insn::Dead`].
8482fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
8483    let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
8484    for (index, insn) in stack[current].insns.iter_mut().enumerate() {
8485        if !reachable[index] {
8486            *insn = Insn::Dead;
8487        }
8488    }
8489}
8490
8491/// Mark every instruction index reachable from the entry, plus the index one past
8492/// the last instruction.
8493///
8494/// `seen[len]` answers "can control reach the end of this function", and the
8495/// entries before it identify dead code. Both DCE and the implicit-return decision
8496/// read the same result, which keeps them from disagreeing.
8497fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
8498    let mut seen = vec![false; count + 1];
8499    let mut worklist = vec![0usize];
8500    while let Some(index) = worklist.pop() {
8501        if index > count || seen[index] {
8502            continue;
8503        }
8504        seen[index] = true;
8505        if index == count {
8506            continue;
8507        }
8508        let (op, operands) = match &state.insns[index] {
8509            Insn::Fixed { op, operands } => (*op, operands.as_slice()),
8510            // A variable access never transfers control, and a removed
8511            // instruction is only reachable if it is already marked.
8512            Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
8513                worklist.push(index + 1);
8514                continue;
8515            }
8516        };
8517        match op {
8518            // A return, a throw and a `ret` all leave this instruction stream: the
8519            // first two give control to the caller or the handler, and `ret`
8520            // returns to a `gosub` elsewhere.
8521            // A tail call leaves the function too: the callee's result becomes this
8522            // function's result, so nothing after it runs.
8523            Opcode::Return
8524            | Opcode::ReturnUndef
8525            | Opcode::ReturnAsync
8526            | Opcode::TailCall
8527            | Opcode::TailCallMethod
8528            | Opcode::Throw
8529            | Opcode::ThrowError
8530            | Opcode::Ret => {}
8531            // A `catch` records where exceptions from the code that follows go.
8532            // That code is not reachable through normal control flow, but it is
8533            // reachable — through the exception edge — so the walk has to follow
8534            // it, or dead-code elimination would delete every handler.
8535            Opcode::Catch => {
8536                if let Some(target) = placed_label(state, operands) {
8537                    worklist.push(target);
8538                }
8539                worklist.push(index + 1);
8540            }
8541            // A `gosub` calls a subroutine and then continues, so both edges count.
8542            Opcode::Gosub => {
8543                if let Some(target) = placed_label(state, operands) {
8544                    worklist.push(target);
8545                }
8546                worklist.push(index + 1);
8547            }
8548            Opcode::Goto => {
8549                if let Some(target) = placed_label(state, operands) {
8550                    worklist.push(target);
8551                }
8552            }
8553            Opcode::IfTrue | Opcode::IfFalse => {
8554                if let Some(target) = placed_label(state, operands) {
8555                    worklist.push(target);
8556                }
8557                worklist.push(index + 1);
8558            }
8559            _ => worklist.push(index + 1),
8560        }
8561    }
8562    seen
8563}
8564
8565/// The instruction index a jump operand points at, resolved through the label
8566/// placement table.
8567fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
8568    let id = label_id(operands)?;
8569    state.labels.get(id as usize).copied().flatten()
8570}
8571
8572/// The label an instruction refers to.
8573fn label_id(operands: &[Op]) -> Option<u32> {
8574    operands.iter().find_map(|operand| match operand {
8575        Op::Label(label) => Some(label.0),
8576        _ => None,
8577    })
8578}
8579
8580/// Turn `if_false L; goto M; L:` into `if_true M`.
8581///
8582/// A conditional whose alternate branch is an unconditional jump needs one jump,
8583/// not two. This is the shape `if (c) break;` produces, so folding it removes an
8584/// instruction and a label from every conditional `break`.
8585/// The boolean a constant-push instruction produces, or `None` if it is not one.
8586///
8587/// Only the operators whose truthiness is decided by the opcode are covered; a
8588/// constant that needs the constant pool (a string) is left alone, because reading it
8589/// would mean threading the pool through the peephole for a case the reference also
8590/// skips.
8591fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
8592    match op {
8593        // `push_0` returns -1 for zero, `push_1` 1, and so on.
8594        Opcode::PushMinus1 => Some(true),
8595        Opcode::Push0 => Some(false),
8596        Opcode::Push1
8597        | Opcode::Push2
8598        | Opcode::Push3
8599        | Opcode::Push4
8600        | Opcode::Push5
8601        | Opcode::Push6
8602        | Opcode::Push7 => Some(true),
8603        Opcode::PushTrue => Some(true),
8604        Opcode::PushFalse => Some(false),
8605        Opcode::Undefined | Opcode::Null => Some(false),
8606        Opcode::PushI32 => match operands.first() {
8607            Some(Op::Int(value)) => Some(*value != 0),
8608            _ => None,
8609        },
8610        _ => None,
8611    }
8612}
8613
8614/// Fold a branch on a constant condition.
8615///
8616/// `if (0) a() else b()` must not test anything at run time, and the reference
8617/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
8618/// which is why the bytecode for a `while (1)` loop has no condition at all.
8619///
8620/// Two instructions become one, so the slot the test occupied is left empty rather
8621/// than shifting everything after it: labels have already been resolved to indices.
8622fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>]) {
8623    for index in 0..insns.len() {
8624        let Some((push_op, push_operands)) = insns[index].clone() else {
8625            continue;
8626        };
8627        let Some(truth) = constant_truth(push_op, &push_operands) else {
8628            continue;
8629        };
8630        let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
8631            continue;
8632        };
8633        let (destination, taken) = match branch_op {
8634            Opcode::IfTrue => (branch_operands.first().cloned(), truth),
8635            Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
8636            _ => continue,
8637        };
8638        let Some(destination) = destination else {
8639            continue;
8640        };
8641        insns[index] = if taken {
8642            // The branch is always taken, so it becomes an unconditional jump.
8643            Some((Opcode::Goto, vec![destination]))
8644        } else {
8645            // The branch never runs: both instructions disappear and control falls
8646            // through to what came after.
8647            None
8648        };
8649        insns[index + 1] = None;
8650    }
8651}
8652
8653/// Remove a jump whose destination is the instruction right after it.
8654///
8655/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
8656/// its test into nothing, and the loop-end jump then points at the following
8657/// instruction. The reference drops them, so `stack_size` and the listing agree.
8658fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
8659    for index in 0..insns.len() {
8660        let Some((op, operands)) = insns[index].clone() else {
8661            continue;
8662        };
8663        if !is_goto(op) {
8664            continue;
8665        }
8666        let Some(id) = label_id(&operands) else {
8667            continue;
8668        };
8669        // The next instruction that still exists, which is what "the instruction
8670        // after this jump" means once earlier folds have punched holes.
8671        let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
8672        if placed.get(id as usize).copied().flatten() == next {
8673            insns[index] = None;
8674        }
8675    }
8676}
8677
8678fn fold_conditional_jumps(
8679    insns: &mut [Option<(Opcode, Vec<Op>)>],
8680    label_at: &[Option<u32>],
8681    placed: &[Option<usize>],
8682) {
8683    for index in 0..insns.len() {
8684        let Some((op, operands)) = insns[index].clone() else {
8685            continue;
8686        };
8687        let inverted = match op {
8688            Opcode::IfFalse => Opcode::IfTrue,
8689            Opcode::IfTrue => Opcode::IfFalse,
8690            _ => continue,
8691        };
8692        // Next must be an unconditional jump that is not itself a target, and the
8693        // instruction after it must be exactly where the conditional goes.
8694        let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
8695            continue;
8696        };
8697        if !is_goto(next_op) || is_label_at(label_at, index + 1) {
8698            continue;
8699        }
8700        // The conditional must land on the instruction *after* the jump. Several
8701        // labels can share a position, so this asks where *this* label was put
8702        // rather than what label happens to sit there.
8703        let Some(taken) = label_id(&operands) else {
8704            continue;
8705        };
8706        if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
8707            continue;
8708        }
8709        let Some(destination) = next_operands.first().cloned() else {
8710            continue;
8711        };
8712        insns[index] = Some((inverted, vec![destination]));
8713        insns[index + 1] = None;
8714    }
8715}
8716
8717/// Whether a jump target is placed at this instruction index.
8718fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
8719    label_at.get(index).copied().flatten().is_some()
8720}
8721
8722fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
8723    // `dup put_x(n)` -> `set_x(n)`
8724    // `dup put_x(n) drop` -> `put_x(n)`
8725    // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
8726    for index in 0..insns.len() {
8727        if opcode_at(insns, index) != Some(Opcode::Dup) {
8728            continue;
8729        }
8730        if is_label_at(label_at, index + 1) {
8731            continue;
8732        }
8733        let Some((put_op, put_operands)) = insns[index + 1].clone() else {
8734            continue;
8735        };
8736        if !is_foldable_put(put_op) {
8737            continue;
8738        }
8739        let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
8740            continue;
8741        };
8742        let mut new_op = set_form_of(put_op);
8743        let mut end = index + 2;
8744        if is_label_at(label_at, end) {
8745            // The `put` has to stay as it is; only the `dup` can be folded.
8746            insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
8747            insns[index + 1] = None;
8748            continue;
8749        }
8750        // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
8751        // Deleting it moves the label's target onto whatever follows, and the code that
8752        // jumps there arrives with a different stack than the fall-through path: that is
8753        // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
8754        // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
8755        // an empty stack. The store had already consumed the value it was supposed to
8756        // leave behind.
8757        if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
8758            new_op = put_op;
8759            end += 1;
8760            if opcode_at(insns, end) == Some(get_form_of(put_op))
8761                && !is_label_at(label_at, end)
8762                && insns[end]
8763                    .as_ref()
8764                    .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
8765            {
8766                new_op = set_form_of(put_op);
8767                end += 1;
8768            }
8769        }
8770        insns[index] = Some((new_op, vec![Op::Slot(slot)]));
8771        for entry in &mut insns[index + 1..end] {
8772            *entry = None;
8773        }
8774    }
8775}
8776
8777fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
8778    insns
8779        .get(index)
8780        .and_then(|entry| entry.as_ref())
8781        .map(|(op, _)| *op)
8782}
8783
8784/// The four `put_` families that have a `set_` twin. Deliberately not including
8785/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
8786/// these, and folding the others would produce instructions that do not exist.
8787fn is_foldable_put(op: Opcode) -> bool {
8788    matches!(
8789        op,
8790        Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
8791    )
8792}
8793
8794fn set_form_of(op: Opcode) -> Opcode {
8795    match op {
8796        Opcode::PutLoc => Opcode::SetLoc,
8797        Opcode::PutLocCheck => Opcode::SetLocCheck,
8798        Opcode::PutArg => Opcode::SetArg,
8799        Opcode::PutVarRef => Opcode::SetVarRef,
8800        other => other,
8801    }
8802}
8803
8804fn get_form_of(op: Opcode) -> Opcode {
8805    match op {
8806        Opcode::PutLoc => Opcode::GetLoc,
8807        Opcode::PutLocCheck => Opcode::GetLocCheck,
8808        Opcode::PutArg => Opcode::GetArg,
8809        Opcode::PutVarRef => Opcode::GetVarRef,
8810        other => other,
8811    }
8812}
8813
8814/// Atom interning, per function.
8815///
8816/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
8817/// identifiers, so the array-index rule applies here rather than at the handful of
8818/// call sites that build property keys.
8819fn intern_atom(state: &mut FnState, name: &str) -> u32 {
8820    intern_atom_value(state, Atom::from_text(name))
8821}
8822
8823/// [`intern_atom`] for an operand that is already an [`Atom`].
8824///
8825/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
8826/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
8827/// would have looked up.
8828fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
8829    if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
8830        return index as u32;
8831    }
8832    state.atoms.push(atom);
8833    state.atoms.len() as u32 - 1
8834}
8835
8836fn binary_opcode(op: BinaryOp) -> Opcode {
8837    match op {
8838        BinaryOp::Add => Opcode::Add,
8839        BinaryOp::Sub => Opcode::Sub,
8840        BinaryOp::Mul => Opcode::Mul,
8841        BinaryOp::Div => Opcode::Div,
8842        BinaryOp::Mod => Opcode::Mod,
8843        BinaryOp::Pow => Opcode::Pow,
8844        BinaryOp::BitOr => Opcode::Or,
8845        BinaryOp::BitXor => Opcode::Xor,
8846        BinaryOp::BitAnd => Opcode::And,
8847        BinaryOp::Shl => Opcode::Shl,
8848        BinaryOp::Shr => Opcode::Sar,
8849        BinaryOp::UShr => Opcode::Shr,
8850        BinaryOp::Lt => Opcode::Lt,
8851        BinaryOp::LtEq => Opcode::Lte,
8852        BinaryOp::Gt => Opcode::Gt,
8853        BinaryOp::GtEq => Opcode::Gte,
8854        BinaryOp::Eq => Opcode::Eq,
8855        BinaryOp::NotEq => Opcode::Neq,
8856        BinaryOp::StrictEq => Opcode::StrictEq,
8857        BinaryOp::StrictNotEq => Opcode::StrictNeq,
8858        BinaryOp::In => Opcode::In,
8859        BinaryOp::Instanceof => Opcode::Instanceof,
8860    }
8861}
8862
8863fn compound_opcode(op: AssignOp) -> Opcode {
8864    match op {
8865        AssignOp::Add => Opcode::Add,
8866        AssignOp::Sub => Opcode::Sub,
8867        AssignOp::Mul => Opcode::Mul,
8868        AssignOp::Div => Opcode::Div,
8869        AssignOp::Mod => Opcode::Mod,
8870        AssignOp::Pow => Opcode::Pow,
8871        AssignOp::Shl => Opcode::Shl,
8872        AssignOp::Shr => Opcode::Sar,
8873        AssignOp::UShr => Opcode::Shr,
8874        AssignOp::BitOr => Opcode::Or,
8875        AssignOp::BitXor => Opcode::Xor,
8876        AssignOp::BitAnd => Opcode::And,
8877        AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
8878    }
8879}
8880
8881/// Encode the resolved instruction stream, choosing short forms where possible.
8882///
8883/// The peephole pass leaves holes in the instruction list so that label indices
8884/// stay valid. A label names an *instruction index*, and an index that was
8885/// deleted has to resolve to the next surviving instruction, which is what
8886/// [`resolve_label`] does before the byte offsets are known.
8887fn assemble(
8888    insns: &mut [Option<(Opcode, Vec<Op>)>],
8889    insn_pos: &[Option<Position>],
8890    state: &mut FnState,
8891) -> (Vec<u8>, u32, Vec<LineCol>) {
8892    // Compaction: surviving instructions in order, plus the index mapping.
8893    //
8894    // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
8895    // point below where instructions are removed — otherwise a stack trace would point
8896    // at the wrong source line as soon as dead-code elimination kicked in.
8897    let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
8898    let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
8899    let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
8900    for (original, entry) in insns.iter_mut().enumerate() {
8901        if let Some((op, operands)) = entry.take() {
8902            original_to_kept[original] = Some(kept.len());
8903            kept.push((op, operands));
8904            spans.push(insn_pos.get(original).copied().flatten());
8905        }
8906    }
8907
8908    if std::env::var_os("QJS_DEBUG").is_some() {
8909        eprintln!("--- assemble entry --- {kept:?}");
8910    }
8911    // How many labels are real, as opposed to the per-instruction ones allocated
8912    // just below. Only a real label marks a spot in the source program.
8913    let real_labels = state.labels.len();
8914
8915    // Give every surviving instruction a label of its own. Jump cleanup below
8916    // redirects jumps to arbitrary instructions, and a jump target has to be a
8917    // label; pre-allocating one per index means a redirect never has to invent
8918    // anything.
8919    let existing = state.labels.len();
8920    let base = kept.len();
8921    let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
8922    for offset in 0..=kept.len() {
8923        state.labels.push(Some(0));
8924        index_label.push(Label((existing + offset) as u32));
8925    }
8926    // Point each pre-allocated label at its instruction, reusing the count from
8927    // `original_to_kept` so the mapping survives compaction.
8928    let place_index_labels = |state: &mut FnState,
8929                              original_to_kept: &[Option<usize>],
8930                              kept_len: usize,
8931                              index_label: &[Label]| {
8932        for (original, mapped) in original_to_kept.iter().enumerate() {
8933            if let Some(kept_index) = mapped {
8934                let label = index_label[*kept_index].0 as usize;
8935                state.labels[label] = Some(original);
8936            }
8937        }
8938        state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
8939    };
8940    place_index_labels(state, &original_to_kept, base, &index_label);
8941
8942    // Resolve every label to a kept index once; the placement table maps labels
8943    // to original indices, so a second hop lands in kept space.
8944    let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
8945    for (id, placed) in state.labels.iter().enumerate() {
8946        let Some(original) = placed else { continue };
8947        label_kept[id] = if *original == usize::MAX {
8948            Some(base)
8949        } else {
8950            (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
8951        };
8952    }
8953
8954    // Code after an unconditional transfer is unreachable, and the reference drops it
8955    // as it walks past the transfer — the `skip_dead_code` in its first pass. It
8956    // scans forward until it finds a label something still jumps to, so a run of
8957    // dead instructions between a `throw` and the next live target disappears.
8958    //
8959    // The scan repeats because dropping a jump lowers the reference count of the
8960    // label it pointed at, which can strand what follows. Only a real label keeps an
8961    // instruction alive here; the per-instruction labels allocated above belong to
8962    // this pass, not to the program.
8963    loop {
8964        let mut references = vec![false; kept.len() + 1];
8965        for (_, operands) in &kept {
8966            if let Some(target) = target_kept_index(operands, &label_kept)
8967                && target < references.len()
8968            {
8969                references[target] = true;
8970            }
8971        }
8972        let mut doomed = vec![false; kept.len()];
8973        let mut any = false;
8974        for (index, (op, _)) in kept.iter().enumerate() {
8975            if !is_transfer(*op) {
8976                continue;
8977            }
8978            for next in index + 1..kept.len() {
8979                if references[next] {
8980                    break;
8981                }
8982                doomed[next] = true;
8983                any = true;
8984            }
8985        }
8986        if !any {
8987            break;
8988        }
8989        (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
8990    }
8991
8992    // A label that lands on an unconditional jump stands for wherever that jump
8993    // goes, so retarget it once and every jump to the label follows for free.
8994    // This is what makes `continue` in a `for` head reach the loop top instead of
8995    // stopping at the update's trailing jump.
8996    let folded: Vec<Option<usize>> = label_kept
8997        .iter()
8998        .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
8999        .collect();
9000    label_kept = folded;
9001
9002    // Jump cleanup, in compacted index space. Two rewrites the reference also
9003    // applies while it resolves labels:
9004    //   * a jump whose destination is the very next instruction does nothing;
9005    //   * a jump to a jump is redirected to its final destination.
9006    // The second can expose the first, so this repeats until it settles.
9007    loop {
9008        let mut delete = vec![false; kept.len()];
9009        let mut changed = false;
9010        for index in 0..kept.len() {
9011            let (op, operands) = &kept[index];
9012            if !is_goto(*op) {
9013                continue;
9014            }
9015            let Some(immediate) = target_kept_index(operands, &label_kept) else {
9016                continue;
9017            };
9018            let target = follow_jump_chain(&kept, &label_kept, immediate);
9019            if target == index + 1 {
9020                delete[index] = true;
9021                changed = true;
9022            } else if matches!(
9023                kept.get(target).map(|(op, _)| *op),
9024                Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
9025            ) {
9026                // Jumping straight to a return or throw is the same as doing it
9027                // here, so the jump becomes that instruction.
9028                kept[index] = (kept[target].0, Vec::new());
9029                changed = true;
9030            } else if target != immediate {
9031                // Redirect to the end of the chain.
9032                let label = index_label[target];
9033                kept[index].1 = vec![Op::Label(label)];
9034                changed = true;
9035            }
9036        }
9037        if !changed {
9038            break;
9039        }
9040        if !delete.iter().any(|deleted| *deleted) {
9041            break;
9042        }
9043        // Drop the deleted instructions and renumber everything.
9044        let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9045        let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9046        let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9047        for (old, entry) in kept.into_iter().enumerate() {
9048            if delete[old] {
9049                continue;
9050            }
9051            moved[old] = Some(next.len());
9052            next.push(entry);
9053            next_spans.push(spans[old]);
9054        }
9055        for (id, slot) in label_kept.iter_mut().enumerate() {
9056            let Some(old) = *slot else { continue };
9057            *slot = match moved.get(old).copied().flatten() {
9058                Some(new) => Some(new),
9059                // The target was deleted: the jump now lands on whatever follows.
9060                None => (old..moved.len())
9061                    .find_map(|i| moved[i])
9062                    .or(Some(next.len())),
9063            };
9064            let _ = id;
9065        }
9066        kept = next;
9067        spans = next_spans;
9068    }
9069
9070    // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
9071    // jump to the next instruction and is deleted, leaving the label at the end with
9072    // nothing pointing at it. If that also strands the last instruction, it goes
9073    // too — which is how a `try` whose body always returns ends on its `ret` rather
9074    // than an implicit `return_undef`.
9075    // Which instructions something still jumps to. Reading the surviving jumps is
9076    // what the reference's reference counts amount to: once a jump has been folded
9077    // away the label it named is unreferenced, even though the program still has a
9078    // label there.
9079    let mut references = vec![false; kept.len() + 1];
9080    let _ = real_labels;
9081    for (_, operands) in &kept {
9082        if let Some(target) = target_kept_index(operands, &label_kept)
9083            && target < references.len()
9084        {
9085            references[target] = true;
9086        }
9087    }
9088    let mut end = kept.len();
9089    while end > 0 {
9090        let last = end - 1;
9091        let reachable = references[last] || end < kept.len();
9092        if reachable {
9093            break;
9094        }
9095        let after_transfer = last
9096            .checked_sub(1)
9097            .map(|previous| {
9098                matches!(
9099                    kept[previous].0,
9100                    Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
9101                )
9102            })
9103            .unwrap_or(false);
9104        if !after_transfer {
9105            break;
9106        }
9107        end = last;
9108    }
9109    kept.truncate(end);
9110    spans.truncate(end);
9111
9112    // Choose an opcode for each instruction and its size, so label offsets can be
9113    // computed.
9114    let chosen = choose_opcodes(&kept, &label_kept);
9115    let offsets = instruction_offsets(&chosen);
9116    let offset = *offsets.last().unwrap_or(&0);
9117
9118    let mut code = Vec::with_capacity(offset);
9119    for (position, (_, operands)) in kept.iter().enumerate() {
9120        let op = chosen[position];
9121        code.push(op as u8);
9122        let operands = retarget_labels(operands, &label_kept, kept.len());
9123        encode_operands(&mut code, op, &operands, offsets[position], &offsets);
9124    }
9125    let stack_size = compute_stack_size(&code);
9126    // Keep only the offsets where the position actually changes: a run of
9127    // instructions on one line is one table entry, and the runtime binary searches
9128    // the table for the frame's pc.
9129    //
9130    // The table always starts at pc 0 with the *function's own* position, because the
9131    // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
9132    // last_line_num)` from `fd->source_pos`, the token the function definition starts at
9133    // (`function`, `async`, a method's property name). An instruction before the first
9134    // recorded operator therefore reports the function's own start, which is what makes a
9135    // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
9136    let mut positions: Vec<LineCol> = vec![LineCol {
9137        pc: 0,
9138        line: state.line,
9139        column: state.column,
9140    }];
9141    let mut last: Option<Position> = None;
9142    for (index, span) in spans.iter().enumerate() {
9143        let Some(pos) = *span else { continue };
9144        if last == Some(pos) {
9145            continue;
9146        }
9147        last = Some(pos);
9148        if pos.line == state.line && pos.column == state.column {
9149            // Already the seed entry above.
9150            continue;
9151        }
9152        positions.push(LineCol {
9153            pc: offsets[index] as u32,
9154            line: pos.line,
9155            column: pos.column,
9156        });
9157    }
9158    (code, stack_size, positions)
9159}
9160
9161/// Whether an instruction always transfers control away, so anything after it in the
9162/// same stream is unreachable.
9163fn is_transfer(op: Opcode) -> bool {
9164    matches!(
9165        op,
9166        Opcode::Goto
9167            | Opcode::Goto8
9168            | Opcode::Goto16
9169            | Opcode::Return
9170            | Opcode::ReturnUndef
9171            | Opcode::Throw
9172            | Opcode::ThrowError
9173            | Opcode::Ret
9174    )
9175}
9176
9177/// Remove the marked instructions and renumber the label table so it keeps pointing
9178/// at the same instructions. A label whose instruction went away moves to whatever
9179/// follows it, since a jump is never left with nowhere to land.
9180fn drop_instructions(
9181    kept: Vec<(Opcode, Vec<Op>)>,
9182    spans: Vec<Option<Position>>,
9183    label_kept: &mut [Option<usize>],
9184    doomed: &[bool],
9185) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
9186    let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
9187    let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
9188    let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
9189    for (old, entry) in kept.into_iter().enumerate() {
9190        if doomed.get(old).copied().unwrap_or(false) {
9191            continue;
9192        }
9193        moved[old] = Some(result.len());
9194        result.push(entry);
9195        result_spans.push(spans[old]);
9196    }
9197    for slot in label_kept.iter_mut() {
9198        let Some(old) = *slot else { continue };
9199        *slot = match moved.get(old).copied().flatten() {
9200            Some(new) => Some(new),
9201            None => (old..moved.len())
9202                .find_map(|i| moved[i])
9203                .or(Some(result.len())),
9204        };
9205    }
9206    (result, result_spans)
9207}
9208
9209fn is_goto(op: Opcode) -> bool {
9210    matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
9211}
9212
9213/// The kept index a jump operand points at.
9214fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
9215    let id = label_id(operands)?;
9216    label_kept.get(id as usize).copied().flatten()
9217}
9218
9219/// Follow a chain of unconditional jumps to its first real destination.
9220fn follow_jump_chain(
9221    kept: &[(Opcode, Vec<Op>)],
9222    label_kept: &[Option<usize>],
9223    start: usize,
9224) -> usize {
9225    let mut current = start;
9226    // `for(;;)` jumps to itself, so the walk has to be bounded.
9227    for _ in 0..kept.len() {
9228        let Some((op, operands)) = kept.get(current) else {
9229            return current;
9230        };
9231        if !is_goto(*op) {
9232            return current;
9233        }
9234        let Some(next) = target_kept_index(operands, label_kept) else {
9235            return current;
9236        };
9237        if next == current {
9238            return current;
9239        }
9240        current = next;
9241    }
9242    current
9243}
9244
9245/// Rewrite label operands from label ids to kept instruction indices.
9246fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
9247    operands
9248        .iter()
9249        .map(|operand| match operand {
9250            Op::Label(label) => {
9251                let target = label_kept
9252                    .get(label.0 as usize)
9253                    .copied()
9254                    .flatten()
9255                    .unwrap_or(kept_len);
9256                Op::Label(Label(target as u32))
9257            }
9258            other => other.clone(),
9259        })
9260        .collect()
9261}
9262
9263/// Encode the resolved instruction stream, choosing short forms where possible.
9264///
9265/// Compute the maximum value-stack depth by exploring the control-flow graph.
9266///
9267/// This is a breadth-first walk from the first instruction, tracking the stack
9268/// depth on entry to each instruction. Every instruction has at most two
9269/// successors (fall through, and a jump target), so a worklist over byte offsets
9270/// is enough. The reference does the same thing in `compute_stack_size`, which is
9271/// why the resulting numbers match exactly.
9272///
9273/// Instructions that pop a variable number of values (`call`, `array_from`, …)
9274/// encode that count in their operand, which is added to the static `n_pop`.
9275fn compute_stack_size(code: &[u8]) -> u32 {
9276    let mut depth_at = vec![u16::MAX; code.len()];
9277    // Each entry carries the enclosing `catch` levels, innermost last, because
9278    // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
9279    // offset and forgets that level.
9280    let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
9281    let mut max_depth = 0u32;
9282
9283    while let Some((pc, depth, catch_levels)) = worklist.pop() {
9284        if pc >= code.len() {
9285            continue;
9286        }
9287        if depth_at[pc] != u16::MAX {
9288            continue;
9289        }
9290        force_depth(&mut depth_at, pc, depth);
9291
9292        let Some(op) = Opcode::from_u8(code[pc]) else {
9293            break;
9294        };
9295        let info = op.info();
9296        let next = pc + info.size as usize;
9297        if next > code.len() {
9298            break;
9299        }
9300        let mut n_pop = info.n_pop as u32;
9301        let mut n_push = info.n_push as u32;
9302        // Variable-length forms carry their count in the operand.
9303        match info.format {
9304            crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
9305                n_pop += read_u16(code, pc + 1) as u32;
9306            }
9307            crate::opcode::OpFormat::Npopx => {
9308                n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
9309            }
9310            _ => {}
9311        }
9312        // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
9313        // are the `set_` variant; the table already records that, so nothing to
9314        // adjust here.
9315        let _ = &mut n_push;
9316
9317        // The depth before this instruction's own push, which is what a `catch`
9318        // records as its level.
9319        let depth_before = depth;
9320        let mut depth = depth.saturating_sub(n_pop) + n_push;
9321        let mut catch_levels = catch_levels;
9322        if op == Opcode::NipCatch {
9323            // Discard everything above the innermost catch offset, keeping the value
9324            // on top: the frame the code after this sees is the same shape it would
9325            // have had if the `try` were not there.
9326            if let Some(base) = catch_levels.pop() {
9327                depth = base + 1;
9328            }
9329        }
9330        max_depth = max_depth.max(depth);
9331
9332        // Successors.
9333        let target = jump_target_of(code, pc, op);
9334        match op {
9335            Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
9336                if let Some(target) = target {
9337                    worklist.push((target, depth, catch_levels));
9338                }
9339            }
9340            Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
9341                if let Some(target) = target {
9342                    worklist.push((target, depth, catch_levels.clone()));
9343                }
9344                worklist.push((next, depth, catch_levels));
9345            }
9346            // A `catch` records an exception edge to the handler. The handler is
9347            // entered with the thrown value on top of the stack, in the slot the
9348            // catch offset occupies on the normal path — which is why the handler's
9349            // first instruction can `put_loc` the exception away, and why the depth
9350            // is the same on both paths.
9351            Opcode::Catch => {
9352                if let Some(target) = target {
9353                    // The handler is protected by the *enclosing* catch, not by this
9354                    // one: an error raised inside it is what the handler's own
9355                    // `catch` catches.
9356                    worklist.push((target, depth, catch_levels.clone()));
9357                }
9358                catch_levels.push(depth_before);
9359                worklist.push((next, depth, catch_levels));
9360            }
9361            // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
9362            // rewind past it too. Its level sits one slot higher than a `catch`'s:
9363            // the iterator and next-method slots occupy the offset's place.
9364            Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
9365                if let Some(target) = target {
9366                    worklist.push((target, depth, catch_levels.clone()));
9367                }
9368                catch_levels.push(depth_before + 1);
9369                worklist.push((next, depth, catch_levels));
9370            }
9371            // `gosub` calls a subroutine with the return address on top. The opcode
9372            // table records no push for it — `ret` is what pops the slot — so the
9373            // extra one is added here, where the depth of the subroutine's first
9374            // instruction is being computed.
9375            Opcode::Gosub => {
9376                if let Some(target) = target {
9377                    worklist.push((target, depth + 1, catch_levels.clone()));
9378                }
9379                worklist.push((next, depth, catch_levels));
9380            }
9381            // `ret` goes back to a `gosub`; nothing here follows it.
9382            Opcode::Ret
9383            | Opcode::Return
9384            | Opcode::ReturnUndef
9385            | Opcode::Throw
9386            | Opcode::ThrowError => {}
9387            _ => worklist.push((next, depth, catch_levels)),
9388        }
9389    }
9390    max_depth
9391}
9392
9393/// Record the stack depth on entry to `pc`, keeping the deeper value if the
9394/// instruction is reachable more than once.
9395fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
9396    let clamped = depth.min(u16::MAX as u32 - 1) as u16;
9397    if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
9398        depth_at[pc] = clamped;
9399    }
9400}
9401
9402fn read_u16(code: &[u8], at: usize) -> u16 {
9403    let mut value = 0u16;
9404    for i in 0..2 {
9405        value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
9406    }
9407    value
9408}
9409
9410/// The absolute target of a jump instruction, if it has one.
9411fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
9412    let info = op.info();
9413    let position = pc + 1;
9414    match info.format {
9415        crate::opcode::OpFormat::Label8 => {
9416            let offset = *code.get(position)? as i8 as i64;
9417            Some((position as i64 + offset) as usize)
9418        }
9419        crate::opcode::OpFormat::Label16 => {
9420            let offset = read_u16(code, position) as i16 as i64;
9421            Some((position as i64 + offset) as usize)
9422        }
9423        crate::opcode::OpFormat::Label => {
9424            let mut offset = 0i32;
9425            for i in 0..4 {
9426                offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
9427            }
9428            Some((position as i64 + offset as i64) as usize)
9429        }
9430        _ => None,
9431    }
9432}
9433
9434fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
9435    use Opcode::*;
9436    match (op, operands.first()) {
9437        (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
9438            op.short_form(*value as u32).unwrap_or(op)
9439        }
9440        (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
9441        (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
9442        (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
9443        | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
9444        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
9445        // A declared global is reached through its reference cell, so it shares
9446        // the `var_ref` encodings, short forms included.
9447        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
9448            op.short_form(*index).unwrap_or(op)
9449        }
9450        (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
9451            op.short_form(*count as u32).unwrap_or(op)
9452        }
9453        _ => op,
9454    }
9455}
9456
9457/// The byte offset each instruction will start at, plus the total code size.
9458fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
9459    let mut offsets = Vec::with_capacity(chosen.len() + 1);
9460    let mut offset = 0usize;
9461    for op in chosen {
9462        offsets.push(offset);
9463        offset += op.size() as usize;
9464    }
9465    offsets.push(offset);
9466    offsets
9467}
9468
9469/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
9470/// the offset actually fits.
9471///
9472/// The choice is circular: an instruction's size decides the offsets of everything after
9473/// it, and the offsets decide whether a jump may be short. So this starts with every jump
9474/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
9475/// Shrinking only ever *shortens* distances, so the loop converges.
9476///
9477/// Doing it in one pass instead — which is what this used to do — silently truncated any
9478/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
9479/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
9480/// with four closures in its body simply stopped, with no error and no output past the
9481/// first iteration.
9482fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
9483    let mut chosen: Vec<Opcode> = kept
9484        .iter()
9485        .map(|(op, operands)| choose_short_form(*op, operands))
9486        .collect();
9487    // A jump the compiler emitted in its widest form, and the forms it may shrink to.
9488    let candidates = |op: Opcode| match op {
9489        Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
9490        Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
9491        Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
9492        _ => None,
9493    };
9494    loop {
9495        let offsets = instruction_offsets(&chosen);
9496        let mut changed = false;
9497        for index in 0..kept.len() {
9498            let (op, operands) = &kept[index];
9499            let Some((short, medium, has_medium)) = candidates(*op) else {
9500                continue;
9501            };
9502            if chosen[index] == short {
9503                continue;
9504            }
9505            let Some(target) = target_kept_index(operands, label_kept) else {
9506                continue;
9507            };
9508            let Some(&target_offset) = offsets.get(target) else {
9509                continue;
9510            };
9511            // A jump is relative to the byte after its opcode, which is the convention
9512            // `jump_target_of` decodes with.
9513            let relative = target_offset as i64 - (offsets[index] as i64 + 1);
9514            if (-128..=127).contains(&relative) {
9515                chosen[index] = short;
9516                changed = true;
9517            } else if has_medium
9518                && chosen[index] == Opcode::Goto
9519                && (-32_768..=32_767).contains(&relative)
9520            {
9521                // Too far for 8 bits and close enough for 16. Only `goto` has a medium
9522                // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
9523                // the reference encodes them.
9524                chosen[index] = medium;
9525                changed = true;
9526            }
9527        }
9528        if !changed {
9529            return chosen;
9530        }
9531    }
9532}
9533
9534fn encode_operands(
9535    code: &mut Vec<u8>,
9536    op: Opcode,
9537    operands: &[Op],
9538    position: usize,
9539    offsets: &[usize],
9540) {
9541    use crate::opcode::OpFormat::*;
9542    let info = op.info();
9543    let write_slot = |code: &mut Vec<u8>, slot: Slot| {
9544        let index = match slot {
9545            Slot::Arg(i)
9546            | Slot::Loc(i)
9547            | Slot::VarRef(i)
9548            | Slot::Global(i)
9549            | Slot::GlobalDecl(i) => i,
9550        };
9551        code.extend_from_slice(&(index as u16).to_be_bytes());
9552    };
9553    match info.format {
9554        None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
9555        U8 | Const8 => {
9556            if let Some(value) = operands.first().and_then(operand_uint) {
9557                code.push(value as u8);
9558            }
9559        }
9560        // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
9561        // like their wide counterparts, only one byte wide.
9562        Loc8 => {
9563            if let Some(Op::Slot(slot)) = operands.first() {
9564                let index = match slot {
9565                    Slot::Arg(i)
9566                    | Slot::Loc(i)
9567                    | Slot::VarRef(i)
9568                    | Slot::Global(i)
9569                    | Slot::GlobalDecl(i) => *i,
9570                };
9571                code.push(index as u8);
9572            }
9573        }
9574        I8 => {
9575            if let Some(value) = operands.first().and_then(operand_int) {
9576                code.push(value as i8 as u8);
9577            }
9578        }
9579        U16 | Npop => {
9580            if let Some(value) = operands.first().and_then(operand_int) {
9581                code.extend_from_slice(&(value as u16).to_be_bytes());
9582            }
9583        }
9584        I16 => {
9585            if let Some(value) = operands.first().and_then(operand_int) {
9586                code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
9587            }
9588        }
9589        I32 => {
9590            if let Some(value) = operands.first().and_then(operand_int) {
9591                code.extend_from_slice(&value.to_be_bytes());
9592            }
9593        }
9594        U32 | Const => {
9595            if let Some(value) = operands.first().and_then(operand_uint) {
9596                code.extend_from_slice(&value.to_be_bytes());
9597            }
9598        }
9599        Loc | Arg | VarRef => {
9600            if let Some(Op::Slot(slot)) = operands.first() {
9601                write_slot(code, *slot);
9602            }
9603        }
9604        Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
9605            if let Some(Op::AtomId(index)) = operands.first() {
9606                code.extend_from_slice(&index.to_be_bytes());
9607            }
9608            // The trailing immediate means different things per format, and the
9609            // atom forms that carry a *label* have to resolve it like any other
9610            // jump, so they cannot share the `U8`/`U16` arms above.
9611            match info.format {
9612                AtomU8 | AtomLabelU8 => {
9613                    if let Some(value) = operands.get(1).and_then(operand_uint) {
9614                        code.push(value as u8);
9615                    }
9616                }
9617                AtomU16 | AtomLabelU16 => {
9618                    if let Some(value) = operands.get(1).and_then(operand_uint) {
9619                        code.extend_from_slice(&(value as u16).to_be_bytes());
9620                    }
9621                }
9622                _ => {}
9623            }
9624        }
9625        NpopU16 => {
9626            for operand in operands.iter().take(2) {
9627                if let Some(value) = operand_uint(operand) {
9628                    code.extend_from_slice(&(value as u16).to_be_bytes());
9629                }
9630            }
9631        }
9632        Label | Label8 | Label16 | LabelU16 => {
9633            if let Some(Op::Label(label)) = operands.first() {
9634                // Labels were already remapped to kept-instruction indices.
9635                let Some(&target) = offsets.get(label.0 as usize) else {
9636                    debug_assert!(false, "label {} is past the end", label.0);
9637                    return;
9638                };
9639                let relative = target as i64 - (position as i64 + 1);
9640                match info.format {
9641                    Label8 => code.push(relative as i8 as u8),
9642                    Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
9643                    // `label_u16` stores the target followed by an unrelated u16.
9644                    LabelU16 => {
9645                        code.extend_from_slice(&(relative as i32).to_be_bytes());
9646                        if let Some(value) = operands.get(1).and_then(operand_uint) {
9647                            code.extend_from_slice(&(value as u16).to_be_bytes());
9648                        }
9649                    }
9650                    _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
9651                }
9652            }
9653        }
9654    }
9655}
9656
9657fn operand_int(op: &Op) -> Option<i32> {
9658    match op {
9659        Op::Int(value) => Some(*value),
9660        _ => None,
9661    }
9662}
9663
9664fn operand_uint(op: &Op) -> Option<u32> {
9665    match op {
9666        Op::Const(value) | Op::AtomId(value) => Some(*value),
9667        Op::Int(value) => Some(*value as u32),
9668        _ => None,
9669    }
9670}
9671
9672/// Disassemble a compiled function.
9673pub fn disassemble(function: &CompiledFunction) -> String {
9674    disasm::disassemble_program(function)
9675}