Skip to main content

js_compile/
compiler.rs

1//! The bytecode compiler.
2//!
3//! Compilation is a single walk over the AST that emits *symbolic* instructions
4//! (jump targets are label ids, variable references are names), followed by a
5//! resolution pass that turns them into final bytecode. Splitting it this way
6//! keeps the emitter readable: nothing has to know slot indices or byte offsets
7//! while it is still discovering them.
8//!
9//! Variable resolution follows the reference implementation's model:
10//!
11//! * every function has a flat table of arguments and locals;
12//! * block scopes form a chain through [`VarDef::scope_next`], which is what makes
13//!   `let`/`const` bindings visible only inside their block and lets the runtime
14//!   put them back into the temporal dead zone on entry;
15//! * a name that is not in the current function is looked up in the enclosing
16//!   ones; if found, the variable is marked captured and reached through a
17//!   closure reference;
18//! * a name found nowhere is a global, reached through a closure entry as well.
19//!
20//! Emission order and instruction choice deliberately mirror `quickjs.c`: the
21//! differential test compares disassembly with the reference opcode by opcode, so
22//! an unnecessary `dup` or a differently chosen short form shows up immediately.
23
24use crate::bytecode::LineCol;
25use crate::bytecode::{
26    ANONYMOUS_BINDING, Atom, ClosureType, ClosureVar, Constant, EvalPrivate, EvalPrivateKind,
27    EvalSite, EvalVisible, ExportEntry, Function as CompiledFunction, FunctionKind, ImportEntry,
28    ModuleMeta, ModuleRequest, VarDef, VarKind,
29};
30use crate::disasm;
31use crate::opcode::Opcode;
32use js_parse::Position;
33use js_parse::Span;
34use js_parse::SyntaxError;
35use js_parse::Wtf8;
36use js_parse::ast::{self, *};
37
38/// A label id, local to the function being compiled.
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
40pub struct Label(u32);
41
42/// The name of the hidden local that carries a function's `[[HomeObject]]` for `super`.
43///
44/// The reference calls the variable `home_object` and prints it as `"<home_object>"`, which
45/// is why the brackets are part of the name; nothing a program writes can collide with it.
46const HOME_OBJECT: &str = "<home_object>";
47
48/// The local holding the function `super()` constructs from.
49///
50/// The reference's `JS_ATOM_this_active_func`. Unlike `<home_object>` this one is printed
51/// with its dots, because that is the atom's text: its dump shows `1: var this.active_func`.
52const ACTIVE_FUNC: &str = "this.active_func";
53
54/// The local holding `new.target`, likewise spelled the way the reference's dump shows it.
55const NEW_TARGET: &str = "new.target";
56
57/// Stand-in for a constant-pool index that is only known later in the instruction stream.
58///
59/// One user: the class constructor's `fclosure`, whose slot the reference assigns after the
60/// members have taken theirs. `u32::MAX` is not a reachable pool index — a class with four
61/// billion members is not a thing — and the compiler patches it before resolution runs, so a
62/// missed patch is a panic-free compiler error rather than a wrong jump.
63const CTOR_INDEX_PLACEHOLDER: u32 = u32::MAX;
64
65/// One step of a class's initialisation, in source order.
66///
67/// A static block is not a member the class keeps — it is a run of statements that executes
68/// at the point the class definition reaches it — so it belongs *inside* the initialiser
69/// function rather than alongside the fields as a separate pass. Merging the two is what
70/// makes `static a = 1; static {}` and `static {}; static a = 1` order-sensitive in the
71/// same way the reference is.
72enum StaticInitItem<'a> {
73    /// `static x = value`, or `x = value` for the instance half.
74    Field(FieldKey<'a>, Option<&'a Expr>),
75    /// `static { … }`
76    Block {
77        body: &'a [Stmt],
78        /// Position of the `{`, which is where the reference puts the function.
79        body_start: Position,
80    },
81}
82
83/// The next template-site identity, process-wide.
84///
85/// A counter rather than something derived from the unit: two compilation units that both
86/// number their sites from zero would collide in the realm's registry, and a collision
87/// there is observable — it would hand the *same* template object to two unrelated sites.
88fn next_template_site() -> u32 {
89    static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
90    NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
91}
92
93/// How one field names its property.
94///
95/// A computed key is *not* re-evaluated per instance: the reference evaluates it once at
96/// class definition and stores it in a `<computed_field>N` binding, because the key of a field
97/// is fixed when the class is created. Keeping the expression here instead made
98/// `class C { [k] = 1 }` re-read `k` on every `new`, which is a different program when `k`
99/// changes — and worse, the operand order was wrong, so `class C { ["a"] = 1 }` produced
100/// `{1: "a"}`.
101enum FieldKey<'a> {
102    /// `x`, `"x"`, `0` — the property name is static text.
103    Literal(&'a PropKey),
104    /// `#x`: the class-scope binding that holds the private symbol.
105    Private(String),
106    /// `[expr]`: the class-scope binding that holds the evaluated key.
107    Computed(String),
108}
109
110/// The `var_block` sentinel for a binding that lives at function scope.
111///
112/// It has to be a value a *real* block key can never take. Block keys are source
113/// offsets, so `0` is a perfectly ordinary key — the first block statement of a file
114/// gets it — and using `0` as the sentinel made `{ let y = 2 }` at offset zero look
115/// like a function-scoped `var`, which is how a top-level block's `let` leaked out of
116/// its block. The body block already uses `u64::MAX` to stay clear of offsets, so the
117/// sentinel takes the slot below it.
118const FUNCTION_SCOPE: u64 = u64::MAX - 3;
119
120/// The `var_block` sentinel for a binding of the parameter list.
121///
122/// A function whose parameter list contains a default expression gets *two* variable
123/// environments: one for the parameters and one for the body, so a `var` in the body
124/// that shares a name with a parameter is a different binding. The parameter bindings
125/// therefore need a scope key of their own: reachable while the defaults are
126/// evaluated, invisible to the body, and never merged with a body `var` of the same
127/// name.
128///
129/// Without this, `function f(a = 1, p = () => a) { var a = 2 }` made `p()` return 2:
130/// the closure and the body shared one slot, when only the parameters were in scope
131/// when it was created.
132const PARAM_SCOPE: u64 = u64::MAX - 4;
133
134/// The name of the hidden local a `using` declaration caches its dispose method in.
135///
136/// It has to be a name no source can produce, because a script may declare anything: the
137/// angle brackets keep it out of the identifier grammar, exactly like `<ret>`.
138fn using_method_name(name: &str) -> String {
139    format!("<using.method {name}>")
140}
141
142/// The `blocks` parent sentinel for "this block has no enclosing block".
143///
144/// Same reasoning as [`FUNCTION_SCOPE`]: `0` is a legal block key, and when it was
145/// also the terminator the chain walk from the script body reached the file's
146/// offset-zero block and treated it as an *enclosing* block — so that block's `let`
147/// leaked into the body scope.
148const NO_PARENT: u64 = u64::MAX - 2;
149
150/// The block key for a script body. Distinct from both sentinels and unreachable from
151/// any source offset.
152const SCRIPT_BODY: u64 = u64::MAX - 1;
153
154/// An operand of a symbolic instruction.
155#[derive(Debug, Clone, PartialEq)]
156enum Op {
157    /// An immediate integer.
158    Int(i32),
159    /// A jump target.
160    Label(Label),
161    /// A constant pool index.
162    Const(u32),
163    /// An atom, before interning.
164    Atom(Atom),
165    /// An interned atom, as an index into [`Function::atoms`].
166    AtomId(u32),
167    /// A resolved slot.
168    Slot(Slot),
169}
170
171/// Where a resolved variable lives.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173enum Slot {
174    Arg(u32),
175    Loc(u32),
176    VarRef(u32),
177    /// A global, by closure-var index.
178    Global(u32),
179    /// A global *declared* in this script. The reference keeps these bindings in
180    /// reference cells so that the script and any closure share one variable, so
181    /// a store goes through `put_var_ref` while a read uses `get_var`.
182    GlobalDecl(u32),
183}
184
185/// What a symbolic variable access does, which decides the final opcode.
186#[derive(Debug, Clone, Copy, PartialEq, Eq)]
187enum VarAction {
188    /// Read the value.
189    Get,
190    /// Read the value, yielding `undefined` for an undeclared global.
191    GetUndef,
192    /// Write, leaving nothing on the stack.
193    Put,
194    /// Write and initialise, leaving the value on the stack.
195    PutInit,
196    /// Write, leaving the value on the stack.
197    Set,
198    /// Initialise a binding that may only be initialised once, such as a derived
199    /// constructor's `this`.
200    PutInitChecked,
201    /// Initialise, leaving the value on the stack and without the `const` check.
202    ///
203    /// A class's own scope binding is a `const` that has to be initialised in the middle
204    /// of the definition — after the constructor exists but before the static fields run
205    /// — and the value has to survive for the outer store to use.
206    SetInit,
207    /// Write a binding that lives in a reference cell.
208    PutRef,
209}
210
211#[derive(Debug, Clone)]
212enum Insn {
213    /// A fully determined instruction.
214    Fixed { op: Opcode, operands: Vec<Op> },
215    /// A variable access, resolved in the second pass.
216    ///
217    /// `block` is the lexical block the access appears in, which is what makes
218    /// shadowing work: two bindings can share a name, and the one that wins is
219    /// whichever scope encloses the access.
220    Var {
221        action: VarAction,
222        name: String,
223        block: u64,
224        /// Whether the access was written in the parameter list; see
225        /// [`FnState::in_params`].
226        in_params: bool,
227    },
228    /// Close a binding *if* it turned out to be captured.
229    ///
230    /// Whether a `for (let i ...)` loop variable needs a fresh per-iteration cell is
231    /// only known once the body has been compiled — a closure created there is the
232    /// thing that makes it necessary. The reference emits `close_loc` exactly in that
233    /// case and nothing otherwise, so the decision is deferred to [`resolve`] instead
234    /// of emitted blind.
235    CloseCaptured { name: String, block: u64 },
236    /// `delete name`, which can only answer `false` once the binding is known.
237    ///
238    /// It is not a `Var` action because `delete_var` carries an *atom*: the runtime
239    /// looks the name up on the global object, which is what distinguishes an implicit
240    /// global (configurable, deletable) from a declared one (a binding, always `false`).
241    DeleteVar { name: String },
242    /// An instruction that dead-code elimination removed. It keeps its slot so
243    /// that label indices stay valid, and resolves to no bytecode.
244    Dead,
245}
246
247/// Where `break` and `continue` jump to.
248///
249/// Targets are stacked as the compiler enters loops and labelled statements, so a
250/// bare `break` needs no analysis: it is simply the innermost target. A labelled
251/// one searches outward by name.
252#[derive(Debug, Clone)]
253struct JumpTarget {
254    /// The labels attached to this target. `l: for(;;)` gives one name; a bare
255    /// loop gives none; `a: b: for(;;)` gives two, because both labels name the
256    /// same statement and `break a` must reach the same place as `break b`.
257    names: Vec<String>,
258    /// Where `break` lands. `None` for a construct `break` may only leave, not
259    /// target — a `try`, whose entry exists purely to unwind.
260    break_label: Option<Label>,
261    /// Where `continue` lands. `None` for anything that is not a loop.
262    continue_label: Option<Label>,
263    /// Stack slots to discard when control leaves this construct by a jump.
264    ///
265    /// Both `switch` and `try` leave something on the value stack for the duration
266    /// of the construct — the discriminant, or the `catch` offset — and a jump out
267    /// has to take it with it. A loop leaves nothing.
268    drop_count: u32,
269    /// The finalizer to run when control leaves this construct.
270    ///
271    /// Set on a `try` even when it has no `finally`: the label is always emitted and
272    /// the empty-subroutine removal cleans up afterwards, so the code that unwinds
273    /// does not have to know whether a finalizer exists.
274    finally_label: Option<Label>,
275    /// Whether this is a labelled non-loop statement, which an unlabelled `break`
276    /// does not reach.
277    is_regular_stmt: bool,
278    /// Whether leaving this construct has to close an iterator.
279    ///
280    /// A `for`/`of` loop keeps an iterator on the value stack, and leaving early has
281    /// to run its `return` method. `for`/`in` keeps only an enumeration object, which
282    /// is dropped rather than closed.
283    has_iterator: bool,
284    /// Whether that iterator speaks the *async* protocol.
285    ///
286    /// An async close has to `await` the inner `return`, so it is an inline instruction
287    /// sequence rather than one opcode — the reference's `emit_iterator_close`.
288    is_async_iterator: bool,
289}
290
291/// Whether a named property read should be `get_field2` rather than `dup; get_field`.
292///
293/// Both leave `source value` on the stack, so this is purely which spelling the reference
294/// picked, and it picked it by whether it had to build a *reference* for the target:
295///
296/// * a target that is itself a pattern starts by boxing the value, so the copy is what it
297///   consumes — `get_field2` (and a default does not change that: `{a: {b} = {}}` still
298///   destructures);
299/// * a `let`/`const` binding needs no reference, so the reference takes the short form;
300/// * a `var`, and any assignment target, go through `dup; get_field`, because the
301///   reference builds a reference for them — which is what `with` needs.
302fn reads_with_get_field2(decl: Option<VarDeclKind>, value: &Pattern) -> bool {
303    nests_a_pattern(value) || matches!(decl, Some(VarDeclKind::Let) | Some(VarDeclKind::Const))
304}
305
306/// Whether binding this pattern starts by boxing the value it was handed.
307fn nests_a_pattern(pattern: &Pattern) -> bool {
308    match &pattern.kind {
309        PatternKind::Array { .. } | PatternKind::Object { .. } => true,
310        PatternKind::Assign { target, .. } => nests_a_pattern(target),
311        _ => false,
312    }
313}
314
315/// `copy_data_properties` flags for an object-literal spread.
316///
317/// The byte packs three fields: the low bits are the stack offset of the source,
318/// the next three the offset of the exclusion list, and bit 2 asks for symbol keys
319/// as well as string keys. A spread passes a literal `null` exclusion list right
320/// below the source, so that field stays zero and only the source offset and the
321/// symbol bit are set — hence `{...v}` copies symbols, which the flag name says.
322const COPY_ALL_PROPERTIES: i32 = 2 | (1 << 2);
323
324/// The expression a `...` introduces.
325///
326/// The parser marks the spread in two places — the element/property variant and an
327/// [`ExprKind::Spread`] wrapper around the argument — so the wrapper has to be
328/// stepped through before the argument can be compiled.
329fn spread_argument(spread: &Expr) -> &Expr {
330    match &spread.kind {
331        ExprKind::Spread(inner) => inner,
332        _ => spread,
333    }
334}
335
336/// The flag byte `define_method` takes.
337///
338/// The low two bits pick value/getter/setter; bit 2 marks the property
339/// enumerable, which every object-literal method is.
340/// What kind of class constructor a function is being compiled as.
341///
342/// A constructor is not an ordinary method: a base one materialises `this` and refuses
343/// to run without `new`, and a derived one starts with `this` in the dead zone until
344/// `super()` produces it.
345#[derive(Debug, Clone, Copy, PartialEq, Eq)]
346enum CtorKind {
347    /// Not a class constructor.
348    None,
349    /// A constructor of a class without `extends`.
350    Base,
351    /// A constructor of a class with `extends`.
352    Derived,
353}
354
355/// The flag byte `define_method` takes for a class member.
356///
357/// The low two bits pick value/getter/setter; bit 2 marks the property enumerable, which
358/// a class method is *not* — that is the whole difference from an object-literal method,
359/// and the reason `Object.keys(C.prototype)` stays empty.
360fn class_method_flags(kind: MethodKind) -> i32 {
361    match kind {
362        MethodKind::Constructor | MethodKind::Method => 0,
363        MethodKind::Get => 1,
364        MethodKind::Set => 2,
365    }
366}
367
368fn define_method_flags(kind: PropertyKind) -> i32 {
369    let base = match kind {
370        PropertyKind::Value | PropertyKind::Method => 0,
371        PropertyKind::Get => 1,
372        PropertyKind::Set => 2,
373    };
374    base | 4
375}
376
377/// Convert a numeric property key to the text an atom would be made from.
378///
379/// `PropertyKey` of a number is `ToString(number)`, the same conversion every other place
380/// uses — so this goes through [`crate::number::number_to_string`] rather than formatting
381/// the value here. It used to accept only `[1e-6, 1e21)` and reject the rest, on the
382/// theory that Rust's `{}` and JavaScript's spelling diverge at the extremes; they do, and
383/// that is exactly why the spec's own algorithm is the thing to call. `get 0.0000001() {}`
384/// binds the key `"1e-7"`, and the rejection made it a `SyntaxError` instead.
385///
386/// The `Result` is kept because the call sites are in a `?` chain, and a key conversion
387/// that could still fail (a non-finite value from a source literal, which the lexer does
388/// not produce) belongs on the same path as the rest of a property name's errors.
389fn numeric_key_text(value: f64, _span: Span) -> Result<String, SyntaxError> {
390    Ok(crate::number::number_to_string(value))
391}
392
393/// Collect the operands of a same-operator logical run, in source order.
394///
395/// Recurses down the left spine only: `((a || b) || c)` contributes `a`, `b`, then
396/// the caller appends `c`. A node with a different operator is one operand.
397fn collect_same_operator<'a>(op: LogicalOp, expr: &'a Expr, out: &mut Vec<&'a Expr>) {
398    if let ExprKind::Logical {
399        op: inner_op,
400        left,
401        right,
402    } = &expr.kind
403        && *inner_op == op
404    {
405        collect_same_operator(op, left, out);
406        out.push(right);
407        return;
408    }
409    out.push(expr);
410}
411
412/// The jump a logical assignment or `??` takes when the value is kept.
413///
414/// `||` and `&&` branch on truthiness, so the same opcode serves both the operator
415/// and `??` once [`Compiler::emit_logical_test`] has pushed a boolean. `??` keeps
416/// the value when it is *not* null-ish, so it is the `if_false` side.
417fn logical_jump(op: AssignOp) -> Opcode {
418    match op {
419        AssignOp::Or => Opcode::IfTrue,
420        AssignOp::And | AssignOp::Coalesce => Opcode::IfFalse,
421        _ => Opcode::IfFalse,
422    }
423}
424
425/// Whether a loop enumerates keys or values.
426#[derive(Debug, Clone, Copy, PartialEq, Eq)]
427enum ForLoopKind {
428    /// `for (x in o)` — the keys of an object.
429    In,
430    /// `for (x of o)` — the values of an iterable.
431    Of,
432    /// `for await (x of o)` — the values of an async iterable, or of a sync one.
433    AwaitOf,
434}
435
436/// Which part of a `try` statement a block key refers to.
437#[derive(Debug, Clone, Copy)]
438enum TryPart {
439    /// The guarded block.
440    Block = 0,
441    /// The handler body, excluding the catch parameter.
442    Catch = 1,
443    /// The finalizer block.
444    Finally = 2,
445    /// The catch parameter's own scope.
446    Param = 3,
447}
448
449/// A lexical scope, identified while hoisting and numbered at the end.
450///
451/// Scope identity is needed in two passes that must agree: declarations are
452/// hoisted in source order (so slots come out in source order, as in the
453/// reference), but a binding belongs to the block it was written in, which is only
454/// entered later. Blocks are therefore keyed by the source position of their
455/// opening brace, which is stable across both walks.
456#[derive(Debug, Clone, Copy)]
457struct Block {
458    /// Source position of the block.
459    key: u64,
460    /// The block this one is nested in; `0` for the function scope.
461    parent: u64,
462}
463
464/// One function under construction.
465struct FnState {
466    /// The function's own source range, used to record its text for
467    /// `Function.prototype.toString`.
468    span: Option<(usize, usize)>,
469    name: String,
470    kind: FunctionKind,
471    strict: bool,
472    args: Vec<VarDef>,
473    vars: Vec<VarDef>,
474    closure_vars: Vec<ClosureVar>,
475    cpool: Vec<Constant>,
476    atoms: Vec<Atom>,
477    /// Every lexical scope, in creation order.
478    blocks: Vec<Block>,
479    /// The block currently being parsed or compiled.
480    current_block: u64,
481    /// The block a *nested* function was created in, so a capture made from here can be
482    /// resolved against the enclosing function's lexical scopes rather than against a
483    /// flat name table. Without it, `function f(){ class S{} }` capturing `S` found the
484    /// function's own `let S` instead of the class body's `const S`.
485    created_in_block: u64,
486    /// The block each local was declared in, parallel to `vars`. `0` means the
487    /// function scope, where `var` bindings live.
488    var_block: Vec<u64>,
489    /// Set when the expression just compiled left no value on the stack.
490    ///
491    /// Only a store can do that: `put_field` consumes the object and the value, so
492    /// an assignment whose result is unused emits nothing extra. The expression
493    /// statement then has nothing to drop.
494    no_value: bool,
495    /// Whether a label was placed since the last instruction was emitted.
496    ///
497    /// The `put`/`get` fold is only valid when the two are adjacent in the final
498    /// stream; a label in between means a jump can land on the read, so the store has
499    /// to keep consuming its value. A flag is enough and avoids having to reason about
500    /// which index a label recorded.
501    label_since_insn: bool,
502    /// Whether the value of the expression being compiled is thrown away.
503    ///
504    /// Only an expression *statement* discards its value, and only the outermost
505    /// assignment in it may act on that: in `x = (o.a = 1)` the inner assignment
506    /// still has to produce a value. Consumed by [`Compiler::assign`], which is
507    /// the one construct whose bytecode depends on it.
508    discard_value: bool,
509    /// The block that holds the function body.
510    body_block: u64,
511    /// Head of each scope's binding chain, indexed by level. Filled in by
512    /// [`rebuild_scope_chain`]; the scope chain is only needed at run time.
513    block_heads: Vec<i32>,
514    /// Enclosing `break`/`continue` targets, innermost last.
515    jump_targets: Vec<JumpTarget>,
516    insns: Vec<Insn>,
517    labels: Vec<Option<usize>>,
518    /// Captured locals, which need a reference cell.
519    var_ref_count: u32,
520    line: u32,
521    column: u32,
522    /// Whether this is a script body. A script's top-level declarations create
523    /// global properties rather than locals, which is why they show up as
524    /// closure variables with `[global_decl]`.
525    is_script: bool,
526    /// Whether this is a module body.
527    ///
528    /// A module body is a script in every respect that matters here — no `arguments`,
529    /// no `this` of its own — but its top-level declarations are *module*-scoped
530    /// instead of global, which is what this flag changes.
531    is_module: bool,
532    /// Whether the function is an arrow, which never gets its own `arguments`.
533    is_arrow: bool,
534    /// The name a *named function expression* binds inside its own body.
535    /// How many parameters count towards `.length`.
536    defined_args: u32,
537    /// Parameters that are not a plain name, with the argument slot each came from.
538    param_prologue: Vec<(usize, Pattern)>,
539    /// What kind of class constructor this function is, if any.
540    ctor_kind: CtorKind,
541    /// Whether the class has instance fields, so the constructor has to run their
542    /// initialiser before it returns.
543    /// What the nested function about to be compiled should be told about its class.
544    class_ctor_pending: Option<CtorKind>,
545    /// Whether this function needs the hidden `this` local, because an arrow inside it
546    /// refers to `this`.
547    ///
548    /// An arrow has no `this` of its own, so the reference materialises the enclosing
549    /// function's receiver into a local and lets the arrow capture it as an ordinary
550    /// closure variable. Declaring the local is not enough on its own: the store that
551    /// fills it has to be prepended to the body, which is what this flag arranges.
552    needs_this_local: bool,
553    /// The same, for `arguments`.
554    needs_arguments_local: bool,
555    /// The same, for `new.target`.
556    needs_new_target_local: bool,
557    /// Whether the body already opens by filling a `this` local, which
558    /// [`Compiler::begin_this_local`] does for a constructor and a field initialiser.
559    has_this_prologue: bool,
560    /// The same, for `<home_object>`: the object `super` resolves against.
561    ///
562    /// An arrow and a static block have no home object of their own — only the method or
563    /// initialiser they were written in does — so `super.x` inside one is a read of the
564    /// enclosing function's `[[HomeObject]]`. The value is materialised into a local there
565    /// by `special_object 4`, the same way `this` is.
566    needs_home_object_local: bool,
567    /// Whether this function has an `arguments` binding of its own.
568    ///
569    /// False for a class field initialiser and a static block: §15.7 puts them outside any
570    /// function, so `arguments` does not exist there and `eval('arguments')` inside one is a
571    /// `SyntaxError` rather than the caller's arguments object. The parser already enforces
572    /// that for written code; this carries the same fact to the `eval` call site, which has
573    /// to compile the eval'd source under the caller's restriction.
574    no_arguments_binding: bool,
575    /// The same, for `this.active_func`: the function `super()` constructs from.
576    ///
577    /// An arrow has no `super` of its own, so it reads the enclosing function's — and that
578    /// is a *lexical* relationship, not a stack one. The reference keeps `this_active_func`
579    /// as a local of the enclosing function; an arrow that escaped the constructor
580    /// (`iter.return = () => super()`) then finds it in its closure even with the
581    /// constructor nowhere on the call stack.
582    needs_active_func_local: bool,
583    /// Hidden locals of the `with` blocks currently open, innermost last.
584    with_names: Vec<String>,
585    /// How many of [`FnState::with_names`] were already open when this function was
586    /// created, i.e. belong to an *enclosing* function.
587    ///
588    /// The distinction decides shadowing, and it is positional rather than lexical. A
589    /// `with` opened **inside** this function's body sits nearer than the function's own
590    /// environment, so it shadows even a `var` of this function:
591    /// `function f(){ with(o){ var v = 1 } }` writes `o.v`. A `with` opened **outside**
592    /// does not: `with(o){ function f(){ var v = 1 } }` writes `f`'s local `v`, because
593    /// `f`'s environment is the inner one. Treating both alike broke one family or the
594    /// other — `S12.10_A1.2` and `S12.10_A1.7` are these two cases.
595    inherited_with_names: usize,
596    /// Set while a with-guard is being emitted, so the guard's own accesses are not
597    /// wrapped in another guard.
598    emitting_with_guard: bool,
599    self_name: Option<String>,
600    /// Where the function body starts, in source order; see [`Function::body_start`].
601    body_start: (u32, u32),
602    /// Whether the body contains a *direct* `eval(...)` call.
603    ///
604    /// A direct eval sees every binding of the function that called it, including ones
605    /// no other code mentions. It also hands those bindings to any closure it creates,
606    /// which can outlive the function. Both need the bindings to live in cells, so this
607    /// flag makes the function treat all of them as captured.
608    has_direct_eval: bool,
609    /// Whether the parameter list contains a default expression, which is what gives
610    /// the function a second variable environment (see [`PARAM_SCOPE`]).
611    has_parameter_expressions: bool,
612    /// `IsSimpleParameterList`: every parameter is a plain binding identifier.
613    simple_parameter_list: bool,
614    /// Whether the instructions being emitted belong to the parameter list.
615    ///
616    /// References made here must not see the body's `var`s: the body has not run yet,
617    /// and the reference's own model keeps the two scopes apart.
618    in_params: bool,
619    /// Whether an arrow created in this function's parameter list needs the parameter
620    /// scope's `arguments` binding.
621    needs_param_arguments: bool,
622    /// Whether this function was *created* inside a parameter list.
623    ///
624    /// Inherited, so `f(a = () => () => c)` hides `f`'s body bindings from the inner
625    /// arrow too. The name reference is the arrow's, but the scope it must not see
626    /// belongs to the function the arrow was born in.
627    created_in_params: bool,
628    /// What each direct `eval(...)` in this function can see; see [`EvalSite`].
629    ///
630    /// Only filled in by [`Compiler::materialize_eval_sites`], because the answer is not
631    /// final while the body is still being compiled: a named function expression declares
632    /// its own name binding *after* the body, and that binding is exactly what
633    /// `eval("myfunc = 1")` has to find.
634    eval_sites: Vec<EvalSite>,
635    /// Direct `eval` call sites seen so far: where, and the block that was current.
636    pending_eval_sites: Vec<(Span, u64, bool, Vec<EvalPrivate>, bool)>,
637    /// Whether this body contains `await`.
638    ///
639    /// For a *module* this decides whether its body is an async function: top-level
640    /// `await` makes the whole graph's evaluation asynchronous, which is why the flag has
641    /// to survive to the compiled function rather than being a local of the compiler.
642    has_await: bool,
643    /// The module tables, when this body is a module.
644    ///
645    /// Only the top-level state ever has one: `export` and `import` are top-level
646    /// statements, so nothing nested can add to these tables.
647    module: Option<ModuleMeta>,
648    /// Whether the self-name prologue (`special_object 2` then the store) has been
649    /// emitted for this function.
650    ///
651    /// A *nested* function's lookup declares the binding early (see
652    /// [`resolve_slot`]), so `provide_self_name` cannot decide on its own whether the
653    /// prologue is still needed — the binding existing is not the same as it being
654    /// initialised.
655    self_name_initialized: bool,
656    /// Whether the code emitted so far leaves the program's result on the stack.
657    /// The reference tracks this for the hidden `<ret>` local of an eval script.
658    leaves_value: bool,
659    /// Statement nesting depth, used to tell top-level statements apart.
660    stmt_depth: u32,
661    /// Function declarations waiting to be instantiated at scope entry, as
662    /// (target slot, constant pool index). The reference emits these from
663    /// `instantiate_hoisted_definitions` rather than at the statement, because a
664    /// declaration is visible before it is reached.
665    hoisted: Vec<(u64, HoistTarget, u32)>,
666    /// Function declarations whose bodies are compiled only once the enclosing scope
667    /// has finished hoisting, as (owning block, declaration).
668    ///
669    /// Compiling a body at the declaration makes the result depend on source order: in
670    /// `function f(){ return t } var t`, `t` is not declared yet when `f` is compiled,
671    /// so the read resolved to a *global* instead of the enclosing `var`. Hoisting the
672    /// names first and the bodies second is what removes that dependence.
673    deferred_funcs: Vec<(u64, Box<ast::Function>)>,
674    /// The source position of the node being compiled. Every instruction emitted
675    /// takes it, which is how the position table that feeds stack traces is built.
676    cur_pos: Option<Position>,
677    /// One position per entry in `insns`, index-aligned.
678    insn_pos: Vec<Option<Position>>,
679}
680
681/// Where a hoisted function declaration is stored.
682#[derive(Debug, Clone)]
683enum HoistTarget {
684    Arg(u32),
685    Loc(u32),
686    /// A global, which the resolver looks up by name.
687    Global(String),
688}
689
690impl FnState {
691    /// Whether this function suspends: a generator or an async function.
692    ///
693    /// A suspending function's `return` is a `return_async` and its body starts with an
694    /// `initial_yield`, so almost every statement that touches control flow asks this.
695    fn is_suspending(&self) -> bool {
696        self.kind.is_generator() || self.kind.is_async()
697    }
698
699    fn new(name: impl Into<String>, kind: FunctionKind) -> FnState {
700        FnState {
701            span: None,
702            name: name.into(),
703            kind,
704            strict: false,
705            args: Vec::new(),
706            vars: Vec::new(),
707            closure_vars: Vec::new(),
708            cpool: Vec::new(),
709            atoms: Vec::new(),
710            blocks: Vec::new(),
711            current_block: 0,
712            created_in_block: NO_PARENT,
713            var_block: Vec::new(),
714            no_value: false,
715            label_since_insn: false,
716            discard_value: false,
717            body_block: 0,
718            block_heads: Vec::new(),
719            jump_targets: Vec::new(),
720            insns: Vec::new(),
721            labels: Vec::new(),
722            var_ref_count: 0,
723            line: 1,
724            column: 1,
725            is_script: false,
726            is_module: false,
727            is_arrow: false,
728            defined_args: 0,
729            param_prologue: Vec::new(),
730            ctor_kind: CtorKind::None,
731            class_ctor_pending: None,
732            needs_this_local: false,
733            needs_arguments_local: false,
734            needs_new_target_local: false,
735            has_this_prologue: false,
736            needs_home_object_local: false,
737            no_arguments_binding: false,
738            needs_active_func_local: false,
739            with_names: Vec::new(),
740            inherited_with_names: 0,
741            emitting_with_guard: false,
742            self_name: None,
743            has_direct_eval: false,
744            body_start: (0, 0),
745            has_parameter_expressions: false,
746            simple_parameter_list: true,
747            in_params: false,
748            needs_param_arguments: false,
749            created_in_params: false,
750            eval_sites: Vec::new(),
751            pending_eval_sites: Vec::new(),
752            has_await: false,
753            module: None,
754            self_name_initialized: false,
755            leaves_value: false,
756            stmt_depth: 0,
757            hoisted: Vec::new(),
758            deferred_funcs: Vec::new(),
759            cur_pos: None,
760            insn_pos: Vec::new(),
761        }
762    }
763
764    /// The scope a declaration lands in: a script's top-level declarations are
765    /// globals, everything else gets a slot.
766    /// Whether a binding declared *now* becomes a property of the global object.
767    ///
768    /// For a script, a top-level `var` and the top-level `let`/`const` are globals.
769    /// The `var` case is decided by the keyword rather than by the cursor position:
770    /// `var` is function-scoped, so a `var i` in a `for` head is still the same
771    /// binding as a `var i` in the body, even though the head has its own block.
772    fn declares_globally(&self, def: &VarDef) -> bool {
773        // A module's top-level declarations are *module*-scoped: they live in the module
774        // record, never on the global object. Two modules can both declare `var x`
775        // without seeing each other, which is the whole point.
776        if self.is_module {
777            return false;
778        }
779        self.is_script && (!def.is_lexical || self.current_block == self.body_block)
780    }
781}
782
783/// The compiler's entry point.
784pub struct Compiler {
785    /// The text being compiled, kept so each function can record its own slice for
786    /// `Function.prototype.toString`.
787    source: Option<String>,
788    module: bool,
789    /// Whether the program itself is the body of an `async` function.
790    ///
791    /// This is the reference's `JS_EVAL_FLAG_ASYNC`: the body may `await`, and its
792    /// completion value is wrapped so a returned promise is not adopted.
793    async_body: bool,
794    /// Enclosing functions, outermost first. The last entry is the current one.
795    stack: Vec<FnState>,
796    /// The private names visible at this point, innermost class body last.
797    ///
798    /// A stack rather than a field of `FnState` because a private name is *lexically* scoped
799    /// to the class body: a method, an arrow inside it and a class nested inside that arrow
800    /// all resolve against the same entries, and the parser accepts exactly that set
801    /// (`self.private` in `parser.rs`). `FnState` is per-function, so it would lose the outer
802    /// class's names the moment a method started.
803    private_scopes: Vec<std::collections::HashMap<String, PrivateUse>>,
804    /// Whether the expression [`Compiler::expr`] is about to compile is the one its
805    /// statement asked to discard.
806    ///
807    /// `FnState::discard_value` says "the statement's value is thrown away", which is only
808    /// ever true of the statement's own expression — an assignment nested inside it, as in
809    /// `f(x = 1)`, has a value that is very much used. Clearing the flag on the way in and
810    /// keeping the answer here is what tells the two apart; without it the nested store
811    /// consumed its value, `call` took the callee as its argument, and `f(x = 1)` inside a
812    /// function threw `undefined is not a function`.
813    discard_root: bool,
814}
815
816/// How a use site of a private name compiles.
817///
818/// The four cases come straight from the reference's `JSVarKindEnum`: the binding holds a
819/// symbol for a field, a function for a method or getter, and nothing at all for the `#a` half
820/// of a setter-only accessor pair.
821#[derive(Clone, Copy, PartialEq, Eq)]
822enum PrivateKind {
823    /// `#x = 1`: an own property keyed by the symbol in the binding.
824    Field,
825    /// `#m() {}`: the binding holds the function; a use site brand-checks the receiver.
826    Method,
827    /// `get #a() {}`: the binding holds the getter, and a read calls it.
828    Getter,
829    /// `set #a(v) {}` with no getter: `#a` is declared but never filled, and reading it is
830    /// the same `TypeError` as reading an uninitialised `const`.
831    Setter,
832}
833
834/// What the compiler knows about one `#name` where it is used.
835#[derive(Clone)]
836struct PrivateUse {
837    kind: PrivateKind,
838    /// `#a<set>` when the class defines a setter for this name.
839    ///
840    /// A second binding, not a second field of the first: the reference stores the setter
841    /// closure under `#a<set>` (`get_private_setter_name`) and reads it back by that name.
842    setter: Option<String>,
843}
844
845/// The class-scope bindings one class body needs, in declaration order.
846#[derive(Default)]
847struct ClassPlan {
848    /// `#x`, `#m`, `#a`, `#a<set>`, `<computed_field>0`, … — everything declared in a `const`
849    /// at class entry, in member order.
850    bindings: Vec<String>,
851    /// The private names, for the use sites inside the body.
852    uses: std::collections::HashMap<String, PrivateUse>,
853    /// Computed field keys, by element index, so the emission pass does not have to redo the
854    /// per-half counter that names them.
855    computed: std::collections::HashMap<usize, String>,
856    /// Whether the instance initialiser has to add the brand to `this`.
857    instance_brand: bool,
858    /// Whether the constructor itself has to carry the brand.
859    static_brand: bool,
860}
861
862impl ClassPlan {
863    /// Walk a class body once and decide every class-scope binding it needs.
864    ///
865    /// Order is the reference's: a member's binding is created when the member is parsed, so
866    /// `class C { #m(){} #x = 1 }` declares `#m` before `#x`, and a setter adds `#a<set>`
867    /// immediately after `#a`. Getting this order wrong renumbers every slot in the class and
868    /// the disassembly stops matching even when every instruction is right.
869    fn build(class: &Class) -> ClassPlan {
870        let mut plan = ClassPlan::default();
871        let mut instance_keys = 0usize;
872        let mut static_keys = 0usize;
873        for (index, element) in class.elements.iter().enumerate() {
874            match element {
875                ClassElement::Method {
876                    key: PropName::Private(ident),
877                    kind,
878                    is_static,
879                    ..
880                } => {
881                    let name = format!("#{}", ident.name);
882                    let first = !plan.uses.contains_key(&name);
883                    if first {
884                        plan.bindings.push(name.clone());
885                        plan.uses.insert(
886                            name.clone(),
887                            PrivateUse {
888                                kind: match kind {
889                                    MethodKind::Get => PrivateKind::Getter,
890                                    MethodKind::Set => PrivateKind::Setter,
891                                    _ => PrivateKind::Method,
892                                },
893                                setter: None,
894                            },
895                        );
896                    }
897                    match kind {
898                        MethodKind::Set => {
899                            let binding = format!("{name}<set>");
900                            plan.bindings.push(binding.clone());
901                            if let Some(use_) = plan.uses.get_mut(&name) {
902                                use_.setter = Some(binding);
903                            }
904                        }
905                        // A getter is what makes the name readable, so a pair that started
906                        // as a setter becomes readable once the getter arrives.
907                        MethodKind::Get => {
908                            if let Some(use_) = plan.uses.get_mut(&name) {
909                                use_.kind = PrivateKind::Getter;
910                            }
911                        }
912                        _ => {}
913                    }
914                    if *is_static {
915                        plan.static_brand = true;
916                    } else {
917                        plan.instance_brand = true;
918                    }
919                }
920                ClassElement::Method {
921                    key: PropName::Computed(_),
922                    ..
923                } => {}
924                ClassElement::Method { .. } => {}
925                ClassElement::Field {
926                    key: PropName::Private(ident),
927                    ..
928                } => {
929                    let name = format!("#{}", ident.name);
930                    if !plan.uses.contains_key(&name) {
931                        plan.bindings.push(name.clone());
932                        plan.uses.insert(
933                            name,
934                            PrivateUse {
935                                kind: PrivateKind::Field,
936                                setter: None,
937                            },
938                        );
939                    }
940                }
941                ClassElement::Field {
942                    key: PropName::Computed(_),
943                    is_static,
944                    ..
945                } => {
946                    let index_in_half = if *is_static {
947                        static_keys += 1;
948                        static_keys - 1
949                    } else {
950                        instance_keys += 1;
951                        instance_keys - 1
952                    };
953                    let binding = computed_field_binding(index_in_half, *is_static);
954                    plan.bindings.push(binding.clone());
955                    plan.computed.insert(index, binding);
956                }
957                ClassElement::Field { .. } | ClassElement::StaticBlock { .. } => {}
958            }
959        }
960        plan
961    }
962
963    /// How a private name used inside the body compiles, or `None` if no enclosing class
964    /// declares it.
965    fn find<'a>(compiler: &'a Compiler, name: &str) -> Option<&'a PrivateUse> {
966        compiler
967            .private_scopes
968            .iter()
969            .rev()
970            .find_map(|scope| scope.get(name))
971    }
972}
973
974impl Compiler {
975    /// The exact source text of a function, for `Function.prototype.toString`.
976    ///
977    /// §20.2.3.5 requires the *original* text: a function must stringify back to what
978    /// was written, comments and odd spacing included. Slicing the recorded span out of
979    /// the whole source is the only way to get that — rebuilding it from the AST would
980    /// normalise the text, and answering `[native code]` for a script function (which is
981    /// what this engine used to do) makes the result useless for feature detection and
982    /// for libraries that read their own source.
983    ///
984    /// Top-level bodies have no single expression span, so their `source` stays `None`
985    /// and `toString` falls back to the calling convention the spec allows.
986    fn function_source(
987        &self,
988        span: Option<(usize, usize)>,
989        line: u32,
990        column: u32,
991    ) -> Option<String> {
992        let source = self.source.as_ref()?;
993        let span = span?;
994        let bytes = source.as_bytes();
995        let start = span.0;
996        let end = span.1;
997        if start >= bytes.len() || end > bytes.len() || start >= end {
998            let _ = (line, column);
999            return None;
1000        }
1001        Some(source.get(start..end)?.to_string())
1002    }
1003}
1004
1005/// Compile a script.
1006pub fn compile_script(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1007    Compiler::new(false).compile(program)
1008}
1009
1010/// Compile a script, keeping its text so `Function.prototype.toString` can answer with
1011/// the original source.
1012///
1013/// The separate entry point rather than a parameter on [`compile_script`] because the
1014/// tests and the disassembler compile from an AST they built themselves and have no
1015/// source to give; they keep the `None` behaviour they already relied on.
1016pub fn compile_script_with_source(
1017    program: &Program,
1018    source: &str,
1019) -> Result<CompiledFunction, SyntaxError> {
1020    let mut compiler = Compiler::new(false);
1021    compiler.source = Some(source.to_string());
1022    compiler.compile(program)
1023}
1024
1025/// [`compile_script_with_source`] for a module.
1026pub fn compile_module_with_source(
1027    program: &Program,
1028    source: &str,
1029) -> Result<CompiledFunction, SyntaxError> {
1030    let mut compiler = Compiler::new(true);
1031    compiler.source = Some(source.to_string());
1032    compiler.compile(program)
1033}
1034
1035/// Compile a script whose top level is the body of an `async` function.
1036/// The body is an ordinary script in every other way — it still reports a completion value
1037/// — but the value is wrapped in `{value}` and the function's kind is `Async`, so running
1038/// it answers a promise instead of a value. The wrapper is what keeps that promise from
1039/// being *adopted*: `await 1` completes with `1`, and the reference resolves to
1040/// `{value: 1}` rather than to `1` — the same shape `std.evalScript(…, {async: true})`
1041/// documents.
1042pub fn compile_script_suspensible(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1043    Compiler::for_suspensible_script().compile(program)
1044}
1045
1046/// Compile a module.
1047pub fn compile_module(program: &Program) -> Result<CompiledFunction, SyntaxError> {
1048    Compiler::new(true).compile(program)
1049}
1050
1051/// Compile a direct `eval` body that inherits private names from its caller.
1052///
1053/// `class C { #m = 44; f() { return eval("this.#m") } }` is legal — private names are
1054/// lexically scoped and the eval runs inside the caller's scope — but the names live in the
1055/// *call site's* compilation unit, so they have to be handed over. Seeding them as the
1056/// outermost private scope is what lets the eval resolve `#m` to the caller's binding: the
1057/// read compiles as an ordinary name lookup of `#m`, which at run time finds the caller's
1058/// slot through the same `eval`-scope machinery every other inherited name uses.
1059///
1060/// `suspensible` selects the `{async: true}` form (`std.evalScript(s, {async: true})`), whose
1061/// body may `await`.
1062pub fn compile_eval_with_private(
1063    program: &Program,
1064    private: &[EvalPrivate],
1065    suspensible: bool,
1066) -> Result<CompiledFunction, SyntaxError> {
1067    let mut compiler = if suspensible {
1068        Compiler::for_suspensible_script()
1069    } else {
1070        Compiler::new(false)
1071    };
1072    if !private.is_empty() {
1073        let scope: std::collections::HashMap<String, PrivateUse> = private
1074            .iter()
1075            .map(|entry| {
1076                (
1077                    entry.name.clone(),
1078                    PrivateUse {
1079                        kind: match entry.kind {
1080                            EvalPrivateKind::Field => PrivateKind::Field,
1081                            EvalPrivateKind::Method => PrivateKind::Method,
1082                            EvalPrivateKind::Getter => PrivateKind::Getter,
1083                            EvalPrivateKind::Setter => PrivateKind::Setter,
1084                        },
1085                        setter: entry.setter.clone(),
1086                    },
1087                )
1088            })
1089            .collect();
1090        compiler.private_scopes.push(scope);
1091    }
1092    compiler.compile(program)
1093}
1094
1095impl Compiler {
1096    /// Create a compiler.
1097    pub fn new(module: bool) -> Compiler {
1098        Compiler {
1099            source: None,
1100            module,
1101            async_body: false,
1102            stack: Vec::new(),
1103            private_scopes: Vec::new(),
1104            discard_root: false,
1105        }
1106    }
1107
1108    /// Create a compiler for a script whose top level is an `async` function body.
1109    fn for_suspensible_script() -> Compiler {
1110        Compiler {
1111            source: None,
1112            module: false,
1113            async_body: true,
1114            stack: Vec::new(),
1115            private_scopes: Vec::new(),
1116            discard_root: false,
1117        }
1118    }
1119
1120    /// Compile a whole program into its top-level function.
1121    pub fn compile(mut self, program: &Program) -> Result<CompiledFunction, SyntaxError> {
1122        let mut state = FnState::new("<eval>", FunctionKind::Normal);
1123        // A module body is *not* a script: it has no completion value, so no hidden
1124        // `<ret>` local and no `put_loc0` before each statement. What it shares with one
1125        // is having no `arguments` of its own and no receiver — see `is_module`.
1126        state.is_script = !self.module;
1127        state.is_module = self.module;
1128        if self.module {
1129            state.module = Some(ModuleMeta::default());
1130        }
1131        state.strict = program.strict || self.module;
1132        state.line = program.span.start.line;
1133        state.column = program.span.start.column;
1134        // Locals are numbered in declaration order; `<ret>` is always slot 0.
1135        //
1136        // `var_block` has to grow in step with `vars`: it is indexed by slot, so a
1137        // slot that only appears in one of the two arrays shifts every later
1138        // binding's block and silently loses the temporal-dead-zone marking for
1139        // the script's own blocks. A function frame has no `<ret>`, which is why
1140        // the misalignment only showed up at the top level.
1141        if !self.module {
1142            state.vars.push(VarDef::var("<ret>"));
1143            state.var_block.push(FUNCTION_SCOPE);
1144        }
1145        self.stack.push(state);
1146        // The body is its own scope, keyed by the position of the program.
1147        // The script body needs a key no statement can produce. Statement keys are
1148        // source offsets, and the program's own start offset is `0` — which is also
1149        // the offset of the first statement, so a top-level `{ let x }` or
1150        // `for (let i …)` used to share the body's block and lose its scope.
1151        let body_key = SCRIPT_BODY;
1152        self.push_block(body_key, NO_PARENT);
1153        self.state().body_block = body_key;
1154        // A module body opens with a re-entry guard. The host evaluates a module exactly
1155        // once, so the guard never fires in practice — but the reference emits it, and a
1156        // module function called a second time (through `eval` of its own source, say)
1157        // must not run its body again.
1158        let module_guard = self.module.then(|| self.new_label());
1159        if let Some(body) = module_guard {
1160            // The guard wraps the *hoisting* too: a second evaluation of the same module
1161            // body must not even re-create its function declarations.
1162            self.emit(Opcode::PushThis, &[]);
1163            self.emit_jump(Opcode::IfFalse, body, &[]);
1164        }
1165        self.hoist(&program.body, body_key)?;
1166        // The scope entry is what emits the hoisted `fclosure`/store pairs, so it has to
1167        // come before the guard's `return_undef`: the reference's jump target sits past
1168        // both, and a second evaluation therefore re-creates nothing.
1169        self.emit_scope_enter(body_key);
1170        if let Some(body) = module_guard {
1171            self.emit(Opcode::ReturnUndef, &[]);
1172            self.place_label(body);
1173        }
1174        // Through `stmts` rather than the loop, so a `using` region at the top level of an
1175        // eval'd body or a module gets its disposal epilogue like any other block.
1176        self.stmts(&program.body)?;
1177        if self.module {
1178            // A module has no completion value; its body simply ends.
1179            self.emit(Opcode::Undefined, &[]);
1180            self.emit(Opcode::ReturnAsync, &[]);
1181            // Top-level `await` makes the body an async function, so the host runs it as
1182            // a coroutine and waits. Without this the `await` opcode would suspend in a
1183            // body that nothing knows how to resume — which is what "a generator body ran
1184            // as an ordinary call" was reporting.
1185            if self.cur().has_await {
1186                self.state().kind = FunctionKind::Async;
1187            }
1188        } else if self.async_body {
1189            // An async body reports its completion value the same way, but through an
1190            // object: the function answers a promise, and resolving that promise *with*
1191            // the completion value would adopt a promise completion instead of reporting
1192            // it. `{value}` is what makes `evalScript("Promise.resolve(7)", {async:true})`
1193            // resolve to `{value: <promise>}` rather than to `7`.
1194            //
1195            // The shape is the reference's, byte for byte (`quickjs.c`: "wrap the return
1196            // value in an object so that promises can be safely returned").
1197            self.emit(Opcode::Object, &[]);
1198            self.emit(Opcode::Dup, &[]);
1199            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1200            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("value"))]);
1201            self.emit(Opcode::Return, &[]);
1202            self.state().kind = FunctionKind::Async;
1203        } else {
1204            // The program's value is whatever the last expression statement stored in
1205            // the hidden `<ret>` local; `put_loc0`/`get_loc0` folding turns the common
1206            // case into a single `set_loc0`.
1207            self.emit(Opcode::GetLoc, &[Op::Slot(Slot::Loc(0))]);
1208            self.emit(Opcode::Return, &[]);
1209        }
1210        Ok(self.finish_current())
1211    }
1212
1213    // -- emitting ----------------------------------------------------------
1214
1215    fn state(&mut self) -> &mut FnState {
1216        self.stack.last_mut().expect("a function is being compiled")
1217    }
1218
1219    fn cur(&self) -> &FnState {
1220        self.stack.last().expect("a function is being compiled")
1221    }
1222
1223    fn emit(&mut self, op: Opcode, operands: &[Op]) {
1224        self.state().label_since_insn = false;
1225        let pos = self.cur().cur_pos;
1226        self.state().insns.push(Insn::Fixed {
1227            op,
1228            operands: operands.to_vec(),
1229        });
1230        self.state().insn_pos.push(pos);
1231    }
1232
1233    /// Reset the script's hidden return value to `undefined`.
1234    ///
1235    /// Called at the start of every statement that does not itself produce the
1236    /// program's value, which is how the reference keeps `if`/loop results from
1237    /// leaking into an eval result.
1238    fn reset_value(&mut self) {
1239        if !self.cur().is_script {
1240            return;
1241        }
1242        self.emit(Opcode::Undefined, &[]);
1243        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1244        self.state().leaves_value = false;
1245    }
1246
1247    /// Whether `name` is a local or argument slot rather than a global.
1248    fn is_slot(&self, name: &str) -> bool {
1249        self.cur().vars.iter().any(|v| v.name == name)
1250            || self.cur().args.iter().any(|a| a.name == name)
1251    }
1252
1253    /// `with (object) body`
1254    ///
1255    /// The boxed object lives in a hidden local marked [`VarKind::With`]. A local is
1256    /// what makes the object reachable from a closure created inside the block, and it
1257    /// is also what lets an `eval` find it: the runtime collects the active `With`
1258    /// locals of every frame and resolves names against them before the realm.
1259    ///
1260    /// Inside the block every name reference is spelled as "look in the with objects
1261    /// first", innermost outwards, and falls through to the ordinary access. The test is
1262    /// `in`, which is `HasProperty` — the same question the spec's Object Environment
1263    /// Record asks.
1264    fn with_stmt(&mut self, object: &Expr, body: &Stmt) -> Result<(), SyntaxError> {
1265        // `with (e) s` completes with `UpdateEmpty(s, undefined)` — an *empty* body still
1266        // produces `undefined`, it does not inherit the previous statement's value. So
1267        // `eval("1; with({}){}")` is `undefined` while `eval("1; with({}){2;}")` is `2`.
1268        // Without this the sticky `<ret>` local leaked the `1` through, the same way it
1269        // would for an `if` or a loop.
1270        self.reset_value();
1271        let name = self.next_with_name();
1272        // The object expression is evaluated *outside* the scope it introduces, so no
1273        // wrapper may be emitted for the names it mentions.
1274        let saved = std::mem::take(&mut self.state().with_names);
1275        self.expr(object)?;
1276        self.state().with_names = saved;
1277        self.emit(Opcode::ToObject, &[]);
1278        self.declare_hidden_local(&name, VarKind::With);
1279        // Pushed before the store so the store itself is not guarded by an *outer*
1280        // `with` — the object being stored is the new one, not something to look up.
1281        self.state().with_names.push(name.clone());
1282        self.emit_var(VarAction::Put, &name);
1283        let result = self.stmt(body);
1284        self.state().with_names.pop();
1285        result
1286    }
1287
1288    /// A hidden-local name for one `with` block, distinct from every enclosing one.
1289    fn next_with_name(&self) -> String {
1290        let depth = self.cur().with_names.len();
1291        if depth == 0 {
1292            "<with>".to_string()
1293        } else {
1294            format!("<with{depth}>")
1295        }
1296    }
1297
1298    /// Declare a hidden local that must stay a *local* even in a script.
1299    ///
1300    /// A script's `var` is a property of the global object, but the `with` object is not
1301    /// part of the source program's name space at all — it only exists for the compiler
1302    /// and the runtime — so it goes straight into the frame's slot list.
1303    fn declare_hidden_local(&mut self, name: &str, kind: VarKind) {
1304        let state = self.state();
1305        if state.vars.iter().any(|v| v.name == name) {
1306            return;
1307        }
1308        state.var_block.push(FUNCTION_SCOPE);
1309        state.vars.push(VarDef {
1310            kind,
1311            ..VarDef::var(name)
1312        });
1313    }
1314
1315    /// Emit a name access, guarded by every active `with` object.
1316    ///
1317    /// Each guard is `get_loc <with>; push_atom_value name; in; if_false <next>` and then
1318    /// the read itself; the outer guards and the plain access are what the `if_false`
1319    /// jumps to, so the innermost object wins.
1320    fn emit_with_guarded(&mut self, action: VarAction, name: &str) {
1321        let names = self.visible_with_names(name);
1322        let done = self.new_label();
1323        let mut starts = Vec::new();
1324        // Innermost object first: the last `with` opened is the one that shadows the
1325        // others, so its guard has to be the first chance to satisfy the name.
1326        for with_name in names.iter().rev() {
1327            let next = self.new_label();
1328            // `with_has_var` takes the object and carries the name as an atom. It is not
1329            // `in`: an Object Environment Record also consults `Symbol.unscopables`, so
1330            // `globalThis[Symbol.unscopables] = {v: true}` leaves `v` to the outer scope.
1331            self.emit_var(VarAction::Get, with_name);
1332            self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1333            self.emit_jump(Opcode::IfFalse, next, &[]);
1334            starts.push(next);
1335            // The operation is `with_get_var`/`with_put_var`, not a plain property access:
1336            // `GetBindingValue`/`SetMutableBinding` ask `HasProperty` **again** before
1337            // getting or setting. That second question is observable — a proxy's `has`
1338            // trap runs one more time (`get-binding-value-call-with-proxy-env` logs
1339            // `has, get unscopables, has, get`) and an `unscopables` getter that deletes
1340            // the property leaves a binding that has gone, which strict code must report
1341            // as a `ReferenceError` rather than write to.
1342            match action {
1343                // A store already has its value on the stack, and `with_put_var` takes the
1344                // pair in `put_field`'s order: object first, then the value.
1345                VarAction::Put | VarAction::PutInit => {
1346                    self.emit_var(VarAction::Get, with_name);
1347                    self.emit(Opcode::Swap, &[]);
1348                    self.emit(Opcode::WithPutVar, &[Op::Atom(Atom::from_text(name))]);
1349                }
1350                _ => {
1351                    self.emit_var(VarAction::Get, with_name);
1352                    self.emit(Opcode::WithGetVar, &[Op::Atom(Atom::from_text(name))]);
1353                }
1354            }
1355            self.emit_jump(Opcode::Goto, done, &[]);
1356            self.place_label(next);
1357        }
1358        self.emit_var(action, name);
1359        self.place_label(done);
1360    }
1361
1362    /// The `with` blocks that can shadow `name`, innermost last.
1363    ///
1364    /// A parameter or a local of this function is *inside* every `with` this function
1365    /// opened, so those shadow it; a `with` that was already open when this function was
1366    /// created is outside the function's own environment, so the local wins and that
1367    /// block is skipped. See [`FnState::inherited_with_names`].
1368    fn visible_with_names(&self, name: &str) -> Vec<String> {
1369        let state = self.cur();
1370        // The hidden `<with…>` locals are how the guard reaches its own objects, so they
1371        // must never be guarded themselves — not by their own block (which would recurse)
1372        // and not by an enclosing one (which would ask a `with` object whether it has a
1373        // property called `<with>`, always answer no, and waste the chain). Source can
1374        // never spell these names, so exempting all of them changes nothing else.
1375        if state.with_names.iter().any(|hidden| hidden == name) {
1376            return Vec::new();
1377        }
1378        let start = if self.is_slot(name) {
1379            state.inherited_with_names
1380        } else {
1381            0
1382        };
1383        state.with_names[start..]
1384            .iter()
1385            .filter(|hidden| hidden.as_str() != name)
1386            .cloned()
1387            .collect()
1388    }
1389
1390    /// Compile `x` as a **reference** to the with object's property, resolving the object
1391    /// once for the whole read-modify-write.
1392    ///
1393    /// `x += 1`, `x++` and `x ||= v` read and then write the same name. Two independent
1394    /// guards get that wrong the moment the read changes the answer: with
1395    /// `{ get x(){ delete this.x; return 2 } }`, `with (o) { x++ }` reads through the
1396    /// getter — which removes the property — and then the write's own guard no longer
1397    /// finds it, so the store landed on the *global* `x` and `o.x` stayed `undefined`. The
1398    /// reference resolves the base once (`with_make_ref`) and reuses it for both halves.
1399    ///
1400    /// The same shape comes out of compiling the name as a **member** of the with object:
1401    /// `get_field2`/`put_field` already evaluate their receiver once, and the hidden
1402    /// `<with>` local holds exactly the object the guard just tested. So each candidate
1403    /// object gets `if the name is bound here, compile as `this.name`; otherwise fall
1404    /// through to the next object`, and the last fallback is the ordinary name.
1405    fn with_reference(
1406        &mut self,
1407        name: &str,
1408        guarded: &mut dyn FnMut(&mut Self, &str) -> Result<(), SyntaxError>,
1409        plain: &mut dyn FnMut(&mut Self) -> Result<(), SyntaxError>,
1410    ) -> Result<(), SyntaxError> {
1411        let targets = self.visible_with_names(name);
1412        if targets.is_empty() {
1413            return plain(self);
1414        }
1415        let done = self.new_label();
1416        let result = self.with_reference_inner(name, &targets, guarded, plain, done);
1417        self.place_label(done);
1418        result
1419    }
1420
1421    fn with_reference_inner(
1422        &mut self,
1423        name: &str,
1424        targets: &[String],
1425        guarded: &mut dyn FnMut(&mut Self, &str) -> Result<(), SyntaxError>,
1426        plain: &mut dyn FnMut(&mut Self) -> Result<(), SyntaxError>,
1427        done: Label,
1428    ) -> Result<(), SyntaxError> {
1429        let Some((innermost, outer)) = targets.split_last() else {
1430            return plain(self);
1431        };
1432        let next = self.new_label();
1433        self.emit_var(VarAction::Get, innermost);
1434        self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1435        self.emit_jump(Opcode::IfFalse, next, &[]);
1436        guarded(self, innermost)?;
1437        self.emit_jump(Opcode::Goto, done, &[]);
1438        self.place_label(next);
1439        self.with_reference_inner(name, outer, guarded, plain, done)
1440    }
1441
1442    /// `delete name`, honouring any enclosing `with`.
1443    ///
1444    /// Inside a `with` the name may be a property of the with object, and then `delete`
1445    /// removes *that* property instead of touching the outer binding —
1446    /// `with (o) { delete p }` answers `true` and leaves `o` without `p` even when a
1447    /// global `p` exists. Left to the resolver it deleted the global instead, so the
1448    /// `statements/with/S12.10_A1.*` family then saw a `ReferenceError` on every later
1449    /// `p`.
1450    ///
1451    /// Emitted as a sequence here rather than during resolution because a resolution slot
1452    /// holds one instruction, and this is a loop over the with objects plus a fallback.
1453    fn delete_ident(&mut self, name: &str) {
1454        let names = self.cur().with_names.clone();
1455        let done = self.new_label();
1456        let mut starts = Vec::new();
1457        if !names.is_empty() {
1458            self.state().emitting_with_guard = true;
1459            // Innermost object first, like the read/write guard: the last `with` opened is
1460            // the one that shadows the others.
1461            for with_name in names.iter().rev() {
1462                let next = self.new_label();
1463                self.emit_var(VarAction::Get, with_name);
1464                self.emit(Opcode::WithHasVar, &[Op::Atom(Atom::from_text(name))]);
1465                self.emit_jump(Opcode::IfFalse, next, &[]);
1466                // `delete` takes the receiver then the key.
1467                self.emit_var(VarAction::Get, with_name);
1468                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_text(name))]);
1469                self.emit(Opcode::Delete, &[]);
1470                self.emit_jump(Opcode::Goto, done, &[]);
1471                self.place_label(next);
1472                starts.push(next);
1473            }
1474            self.state().emitting_with_guard = false;
1475        }
1476        // The fallback: not a property of any with object, so the ordinary rule applies.
1477        let pos = self.cur().cur_pos;
1478        self.state().insns.push(Insn::DeleteVar {
1479            name: name.to_string(),
1480        });
1481        self.state().insn_pos.push(pos);
1482        if !names.is_empty() {
1483            self.place_label(done);
1484        }
1485    }
1486
1487    fn emit_var(&mut self, action: VarAction, name: &str) {
1488        // Peephole: `put_x v` followed by `get_x v` becomes `set_x v`, which
1489        // stores and keeps the value in one instruction. The reference does this
1490        // in a post-pass; folding it at emit time keeps instruction indices
1491        // stable, which matters because labels are recorded as indices.
1492        //
1493        // Only slots have a `set_` form: a global is stored with `put_var` and
1494        // read with `get_var`, and the reference does not fold those.
1495        //
1496        // A label between the two cancels the fold. `set_x v` leaves the value on
1497        // the stack, which is only equivalent when the read immediately follows the
1498        // store; when a jump target sits in between, the store must *consume* the
1499        // value and the read must fetch it afresh. A loop head is exactly that
1500        // case — `for (var i = 0; i < 3; i++)` stores the initialiser, then the
1501        // condition re-reads it — and folding across the label would make the
1502        // condition compare whatever the previous iteration left on the stack.
1503        if action == VarAction::Get {
1504            let is_slot = self.is_slot(name);
1505            let at_label = std::mem::take(&mut self.state().label_since_insn);
1506            //
1507            // `arguments` is excluded because the reference treats it as a special
1508            // binding: it is initialised once and read many times, and folding its
1509            // initialisation into a `set_` would leave the object on the stack where
1510            // the reference leaves nothing.
1511            if is_slot
1512                && name != "arguments"
1513                && !at_label
1514                && let Some(Insn::Var {
1515                    action: previous,
1516                    name: previous_name,
1517                    ..
1518                }) = self.state().insns.last_mut()
1519                && *previous == VarAction::Put
1520                && previous_name == name
1521            {
1522                *previous = VarAction::Set;
1523                return;
1524            }
1525        }
1526        // Inside a `with`, every name lookup consults the with objects first. Two names
1527        // are exempt:
1528        //
1529        // * the hidden `<with…>` locals themselves, or the guard would recurse;
1530        // * a name this function **declares** — a parameter, a `var`, or a `let` of the
1531        //   current body. `with` sits *outside* the function's own environment, so a
1532        //   function declared inside a `with` still resolves its own bindings first:
1533        //   `with (o) { function f(){ var value = "x" } }` writes `f`'s local `value`, not
1534        //   `o.value`. Guarding it anyway wrote through to the with object whenever it
1535        //   happened to have the name, which is why
1536        //   `statements/with/S12.10_A1.7` saw `myObj.value` change. The runtime's
1537        //   `eval_binding_value` already models the same order.
1538        let guarded = !self.visible_with_names(name).is_empty()
1539            && matches!(action, VarAction::Get | VarAction::Put | VarAction::PutInit)
1540            && !self.state().emitting_with_guard;
1541        if guarded {
1542            self.state().emitting_with_guard = true;
1543            self.emit_with_guarded(action, name);
1544            self.state().emitting_with_guard = false;
1545            return;
1546        }
1547        let block = self.cur().current_block;
1548        self.state().label_since_insn = false;
1549        let pos = self.cur().cur_pos;
1550        let in_params = self.cur().in_params;
1551        self.state().insns.push(Insn::Var {
1552            action,
1553            name: name.to_string(),
1554            block,
1555            in_params,
1556        });
1557        self.state().insn_pos.push(pos);
1558    }
1559
1560    fn new_label(&mut self) -> Label {
1561        let state = self.state();
1562        state.labels.push(None);
1563        Label(state.labels.len() as u32 - 1)
1564    }
1565
1566    fn place_label(&mut self, label: Label) {
1567        let index = self.cur().insns.len();
1568        self.state().label_since_insn = true;
1569        self.state().labels[label.0 as usize] = Some(index);
1570    }
1571
1572    fn emit_jump(&mut self, op: Opcode, label: Label, extra: &[Op]) {
1573        let mut operands = vec![Op::Label(label)];
1574        operands.extend_from_slice(extra);
1575        self.emit(op, &operands);
1576    }
1577
1578    // -- scopes ------------------------------------------------------------
1579
1580    /// Start a new lexical scope inside `parent`.
1581    fn push_block(&mut self, key: u64, parent: u64) {
1582        let state = self.state();
1583        if !state.blocks.iter().any(|b| b.key == key) {
1584            state.blocks.push(Block { key, parent });
1585        }
1586        state.current_block = key;
1587    }
1588
1589    /// Emit the code that runs when a lexical scope is entered.
1590    ///
1591    /// Every `let`/`const`/`class` binding starts out in the temporal dead zone,
1592    /// so entering its block marks it uninitialised. Hoisted function
1593    /// declarations are created here instead, which is why a call before the
1594    /// declaration still works.
1595    ///
1596    /// The order is not obvious: bindings are emitted in *reverse* declaration
1597    /// order, because the reference walks its scope chain, which is built by
1598    /// prepending.
1599    fn emit_scope_enter(&mut self, block: u64) {
1600        // Only *this* scope's hoisted declarations are consumed here; the rest stay in the
1601        // list for the scope that owns them. `std::mem::take` used to empty the whole list,
1602        // so entering an outer scope threw away every nested block's function
1603        // declarations: `function h(){ { function k(){} } return k; }` answered
1604        // `undefined`, and `{ function g(){} }` was `undefined` even *inside* the block.
1605        // That is one Annex B rule the engine otherwise implements (a sloppy-mode function
1606        // in a block is also a `var` of the enclosing function), and it is what makes the
1607        // `for (const ctor of ctors) { function f(){} … }` shape in test262 work.
1608        let mut hoisted = std::mem::take(&mut self.state().hoisted);
1609        let mut rest = Vec::with_capacity(hoisted.len());
1610        let mut mine: Vec<(HoistTarget, u32)> = Vec::new();
1611        for (owner, target, pool_index) in hoisted.drain(..) {
1612            if owner == block {
1613                mine.push((target, pool_index));
1614            } else {
1615                rest.push((owner, target, pool_index));
1616            }
1617        }
1618        self.state().hoisted = rest;
1619        mine.sort_by_key(|(target, _)| match target {
1620            HoistTarget::Arg(index) | HoistTarget::Loc(index) => *index,
1621            HoistTarget::Global(_) => u32::MAX,
1622        });
1623        for (target, pool_index) in mine {
1624            self.emit(Opcode::Fclosure, &[Op::Const(pool_index)]);
1625            match target {
1626                HoistTarget::Arg(index) => self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index))]),
1627                HoistTarget::Loc(index) => self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(index))]),
1628                HoistTarget::Global(name) => {
1629                    // A global binding lives in a reference cell, so the store
1630                    // goes through `put_var_ref` while reads use `get_var`.
1631                    let block = self.cur().current_block;
1632                    let pos = self.cur().cur_pos;
1633                    let in_params = self.cur().in_params;
1634                    self.state().insns.push(Insn::Var {
1635                        action: VarAction::PutRef,
1636                        name,
1637                        block,
1638                        in_params,
1639                    });
1640                    self.state().insn_pos.push(pos);
1641                }
1642            }
1643        }
1644        for index in self.block_vars_reversed(block) {
1645            self.emit(
1646                Opcode::SetLocUninitialized,
1647                &[Op::Slot(Slot::Loc(index as u32))],
1648            );
1649        }
1650    }
1651
1652    /// Emit the code that runs when a lexical scope is exited.
1653    ///
1654    /// A captured binding has to be closed: detaching its reference cell freezes
1655    /// the value the binding had when the block ended, which is what a closure
1656    /// created inside the block must keep seeing.
1657    fn emit_scope_leave(&mut self, block: u64) {
1658        for index in self.block_vars_reversed(block) {
1659            if self.cur().vars[index].is_captured {
1660                self.emit(Opcode::CloseLoc, &[Op::Slot(Slot::Loc(index as u32))]);
1661            }
1662        }
1663    }
1664
1665    /// Locals declared in `block`, in reverse declaration order.
1666    fn block_vars_reversed(&self, block: u64) -> Vec<usize> {
1667        let state = self.cur();
1668        let mut out: Vec<usize> = (0..state.vars.len())
1669            .filter(|index| {
1670                state.var_block.get(*index).copied() == Some(block)
1671                    && state.vars[*index].is_lexical
1672                    // A derived constructor's `this` is lexical but is not initialised by
1673                    // entering the scope: `check_ctor` proves it, so its dead-zone marker
1674                    // was emitted with the constructor's own prologue.
1675                    && state.vars[*index].name != "this"
1676            })
1677            .collect();
1678        out.reverse();
1679        out
1680    }
1681
1682    /// Declare a local, even at the top level of a script.
1683    ///
1684    /// A `catch` parameter is always a local: the reference puts it in the
1685    /// function's own variable list (`1: catch e`), never in the global object,
1686    /// because it only exists while the handler runs.
1687    fn declare_local(&mut self, _name: &str, def: VarDef) -> u32 {
1688        let state = self.state();
1689        let index = state.vars.len() as u32;
1690        // A `catch` parameter belongs to a scope even though it is not lexical: the
1691        // runtime instantiates it per handler entry, but it never sits in the
1692        // temporal dead zone.
1693        let block = if def.is_lexical || def.kind == crate::bytecode::VarKind::Catch {
1694            state.current_block
1695        } else {
1696            0
1697        };
1698        state.var_block.push(block);
1699        state.vars.push(def);
1700        index
1701    }
1702
1703    fn declare(&mut self, name: &str, def: VarDef) -> u32 {
1704        if self.cur().is_module
1705            && self.cur().current_block == self.cur().body_block
1706            && !matches!(def.kind, VarKind::Using | VarKind::UsingMethod)
1707        {
1708            // Only the body's own block: a `let` inside a module-level `{}` is still an
1709            // ordinary local of that block, not a module variable.
1710            //
1711            // A `using` binding is excluded on purpose, and the reference excludes it in
1712            // the same place (`var_def_type != JS_VAR_DEF_USING`, with the comment
1713            // "'using' variables are currently not exported in modules"): a module-level
1714            // `using` is an ordinary *local* of the module body function, not a module
1715            // cell. Two things follow, and both are what the reference does — `export {a}`
1716            // of a `using` binding is "exported variable 'a' does not exist", and
1717            // disposal works, because the disposal epilogue addresses locals by slot.
1718            //
1719            // The hidden dispose-method variable is excluded for a stronger reason: it is
1720            // *always* a local (`add_scope_var` in the reference), and it must sit
1721            // immediately after its value so `using_dispose` can find it at `slot + 1`.
1722            return self.declare_module(name, &def);
1723        }
1724        if self.cur().declares_globally(&def) {
1725            self.declare_global(name, &def);
1726            return 0;
1727        }
1728        let state = self.state();
1729        let index = state.vars.len() as u32;
1730        let block = if def.is_lexical {
1731            state.current_block
1732        } else {
1733            0
1734        };
1735        state.var_block.push(block);
1736        state.vars.push(def);
1737        index
1738    }
1739
1740    /// Declare a `using` binding and its cached dispose method, returning both slots.
1741    ///
1742    /// The two are adjacent by construction, because `using_dispose` addresses the pair as
1743    /// `(value, value + 1)` — the reference does the same and documents the constraint.
1744    fn declare_using(&mut self, name: &str) -> (u32, u32) {
1745        let mut def = VarDef::lexical(name);
1746        def.kind = VarKind::Using;
1747        let value = self.declare(name, def);
1748        let mut method = VarDef::lexical(using_method_name(name));
1749        method.kind = VarKind::UsingMethod;
1750        let method_slot = self.declare(&using_method_name(name), method);
1751        (value, method_slot)
1752    }
1753
1754    /// The slot a `using` binding's dispose method lives in.
1755    fn using_method_slot(&self, name: &str) -> Option<u32> {
1756        let hidden = using_method_name(name);
1757        self.cur()
1758            .vars
1759            .iter()
1760            .position(|var| var.name == hidden)
1761            .map(|index| index as u32)
1762    }
1763
1764    // -- statements --------------------------------------------------------
1765
1766    fn stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
1767        self.stmt_labelled(stmt, &[])
1768    }
1769
1770    /// Compile a statement that a chain of labels names.
1771    ///
1772    /// Only a loop consumes `labels`; every other statement ignores them (the
1773    /// parser has already rejected a label on a statement that cannot use it).
1774    fn stmt_labelled(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1775        // Only a *top-level* expression statement supplies the program's value.
1776        let saved = self.cur().leaves_value;
1777        self.state().leaves_value =
1778            matches!(stmt.kind, StmtKind::Expr(_)) && self.cur().stmt_depth == 0;
1779        self.state().stmt_depth += 1;
1780        let result = self.stmt_inner(stmt, labels);
1781        self.state().stmt_depth -= 1;
1782        // A nested statement never contributes the program's value, so the flag
1783        // the wrapper set above is what survives.
1784        let produced = self.cur().leaves_value && self.cur().stmt_depth == 0;
1785        self.state().leaves_value = produced;
1786        let _ = saved;
1787        result
1788    }
1789
1790    fn stmt_inner(&mut self, stmt: &Stmt, labels: &[String]) -> Result<(), SyntaxError> {
1791        match &stmt.kind {
1792            StmtKind::Empty | StmtKind::Debugger => {}
1793            StmtKind::Expr(expr) => {
1794                // The statement's first token is a position the reference records: an
1795                // expression statement is the `hasexpr:` arm of `js_parse_statement`,
1796                // which calls `emit_source_pos(s, s->token.ptr)` before parsing it. That
1797                // is why an error from a construct with no position of its own (`[...it]`
1798                // with a throwing iterator, `` `${x}` ``) reports the statement's start.
1799                let saved = self.cur().cur_pos;
1800                self.state().cur_pos = Some(expr.span.start);
1801                // An expression statement's value is thrown away — except in a
1802                // script, where it becomes the program's result. `assign` reads this
1803                // and clears it, so a nested assignment still produces a value.
1804                self.state().discard_value = !self.cur().is_script;
1805                let result = self.expr(expr);
1806                self.state().discard_value = false;
1807                result?;
1808                if std::mem::take(&mut self.state().no_value) {
1809                    // A store whose value was discarded left nothing to drop.
1810                } else if self.cur().is_script {
1811                    // The program's value lands in the hidden `<ret>` local.
1812                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(0))]);
1813                } else {
1814                    self.emit(Opcode::Drop, &[]);
1815                }
1816                // Restored last: the trailing `drop` is part of the statement, and in the
1817                // reference it simply inherits whatever the expression last recorded.
1818                self.state().cur_pos = saved;
1819            }
1820            StmtKind::Block(body) => {
1821                // The block's declarations were hoisted with its enclosing
1822                // statement list, so there is nothing left to declare here.
1823                let key = stmt.span.start.offset as u64;
1824                let parent = self.cur().current_block;
1825                self.push_block(key, parent);
1826                self.emit_scope_enter(key);
1827                // A block is where a `using` region lives, so its statements have to go
1828                // through `stmts`: that is what emits the disposal epilogue.
1829                self.stmts(body)?;
1830                self.emit_scope_leave(key);
1831                self.state().current_block = parent;
1832            }
1833            StmtKind::VarDecl(decl) => self.var_decl(decl)?,
1834            // A function declaration was already instantiated when its scope was
1835            // entered, so the statement itself emits nothing.
1836            StmtKind::FuncDecl(_) => {}
1837            StmtKind::If { test, cons, alt } => {
1838                self.reset_value();
1839                let else_label = self.new_label();
1840                let end_label = self.new_label();
1841                self.expr(test)?;
1842                self.emit_jump(Opcode::IfFalse, else_label, &[]);
1843                self.stmt(cons)?;
1844                if alt.is_some() {
1845                    self.emit_jump(Opcode::Goto, end_label, &[]);
1846                }
1847                self.place_label(else_label);
1848                if let Some(alt) = alt {
1849                    self.stmt(alt)?;
1850                    self.place_label(end_label);
1851                }
1852            }
1853            StmtKind::While { test, body } => {
1854                self.reset_value();
1855                let top = self.new_label();
1856                let end = self.new_label();
1857                self.place_label(top);
1858                self.expr(test)?;
1859                // The condition's false branch and `break` share one target,
1860                // which is why a `while` loop needs only one end label.
1861                self.emit_jump(Opcode::IfFalse, end, &[]);
1862                self.loop_body(body, labels, top, end)?;
1863                self.emit_jump(Opcode::Goto, top, &[]);
1864                self.place_label(end);
1865            }
1866            StmtKind::DoWhile { body, test } => {
1867                self.reset_value();
1868                let top = self.new_label();
1869                let cont = self.new_label();
1870                let end = self.new_label();
1871                self.place_label(top);
1872                // `continue` in a `do…while` runs the test, so it lands on `cont`
1873                // rather than on the loop head.
1874                self.loop_body(body, labels, cont, end)?;
1875                self.place_label(cont);
1876                self.expr(test)?;
1877                self.emit_jump(Opcode::IfTrue, top, &[]);
1878                self.place_label(end);
1879            }
1880            StmtKind::For {
1881                init,
1882                test,
1883                update,
1884                body,
1885            } => {
1886                self.reset_value();
1887                let for_key = stmt.span.start.offset as u64;
1888                let for_parent = self.cur().current_block;
1889                self.push_block(for_key, for_parent);
1890                self.emit_scope_enter(for_key);
1891                if let Some(init) = init {
1892                    match init {
1893                        ForInit::VarDecl(decl) => {
1894                            self.var_decl(decl)?;
1895                        }
1896                        ForInit::Expr(expr) => {
1897                            // The head's value is discarded. Saying so lets an
1898                            // assignment store with `put` instead of `dup`+`put`, which
1899                            // is what the reference emits — and the difference matters:
1900                            // a `dup`/`drop` pair around the store gives the peephole a
1901                            // chance to fold the store into the *condition's* read.
1902                            self.state().discard_value = true;
1903                            let result = self.expr(expr);
1904                            self.state().discard_value = false;
1905                            result?;
1906                            if !std::mem::take(&mut self.state().no_value) {
1907                                self.emit(Opcode::Drop, &[]);
1908                            }
1909                        }
1910                    }
1911                }
1912                // A `let`/`const` in the head gets a *fresh binding per iteration*,
1913                // so a closure made in the body captures that iteration's value
1914                // instead of sharing one. The reference expresses this with
1915                // `close_loc`, which swaps in a new reference cell holding the
1916                // current value; the three points below are the ones it uses — after
1917                // the initialiser, before the update, and after the loop.
1918                let loop_bindings = match init {
1919                    Some(ForInit::VarDecl(decl)) if decl.kind != VarDeclKind::Var => {
1920                        let mut names: Vec<String> = Vec::new();
1921                        for declarator in &decl.declarators {
1922                            let mut idents = Vec::new();
1923                            declarator.target.bound_names(&mut idents);
1924                            names.extend(idents.into_iter().map(|ident| ident.name));
1925                        }
1926                        names
1927                    }
1928                    _ => Vec::new(),
1929                };
1930                // The reference also closes right after the initialiser, so the first
1931                // iteration's closures get their own cell rather than sharing the one
1932                // the initialiser wrote into.
1933                for name in &loop_bindings {
1934                    let pos = self.cur().cur_pos;
1935                    self.state().insns.push(Insn::CloseCaptured {
1936                        name: name.clone(),
1937                        block: for_key,
1938                    });
1939                    self.state().insn_pos.push(pos);
1940                }
1941                let top = self.new_label();
1942                let cont = self.new_label();
1943                let end = self.new_label();
1944                self.place_label(top);
1945                if let Some(test) = test {
1946                    self.expr(test)?;
1947                    self.emit_jump(Opcode::IfFalse, end, &[]);
1948                }
1949                // `continue` runs the update expression first, so it lands on
1950                // `cont`, which sits just before the update.
1951                self.loop_body(body, labels, cont, end)?;
1952                self.place_label(cont);
1953                // Each iteration ends with a fresh cell, so the closures the body just
1954                // created keep the cell they captured and the update writes to a new
1955                // one. Without this every closure in the loop shares one binding.
1956                let binding_block = for_key;
1957                for name in &loop_bindings {
1958                    let pos = self.cur().cur_pos;
1959                    self.state().insns.push(Insn::CloseCaptured {
1960                        name: name.clone(),
1961                        block: binding_block,
1962                    });
1963                    self.state().insn_pos.push(pos);
1964                }
1965                if let Some(update) = update {
1966                    self.state().discard_value = true;
1967                    let result = self.expr(update);
1968                    self.state().discard_value = false;
1969                    result?;
1970                    if !std::mem::take(&mut self.state().no_value) {
1971                        self.emit(Opcode::Drop, &[]);
1972                    }
1973                }
1974                self.emit_jump(Opcode::Goto, top, &[]);
1975                self.place_label(end);
1976                self.emit_scope_leave(for_key);
1977                self.state().current_block = for_parent;
1978            }
1979            StmtKind::Return(value) => self.return_stmt(value.as_deref())?,
1980            StmtKind::Throw(expr) => {
1981                self.expr(expr)?;
1982                self.emit(Opcode::Throw, &[]);
1983            }
1984            StmtKind::Break(_) | StmtKind::Continue(_) => {
1985                // Labels and loops are wired up in a later milestone; a bare
1986                // break/continue jumps to the innermost enclosing target, which
1987                // the loop helpers register.
1988                self.control_transfer(stmt)?;
1989            }
1990            StmtKind::Labeled { label, body } => {
1991                self.labeled(label, body, stmt)?;
1992            }
1993            StmtKind::Switch {
1994                discriminant,
1995                cases,
1996            } => {
1997                self.switch(discriminant, cases, stmt)?;
1998            }
1999            StmtKind::Try {
2000                block,
2001                handler,
2002                finalizer,
2003            } => {
2004                self.try_stmt(stmt, block, handler, finalizer.as_deref())?;
2005            }
2006            StmtKind::ForIn { left, right, body } => {
2007                self.for_in_of(stmt, left, right, body, ForLoopKind::In, labels)?;
2008            }
2009            StmtKind::ForOf {
2010                left,
2011                right,
2012                body,
2013                is_await,
2014            } => {
2015                let kind = if *is_await {
2016                    ForLoopKind::AwaitOf
2017                } else {
2018                    ForLoopKind::Of
2019                };
2020                self.for_in_of(stmt, left, right, body, kind, labels)?;
2021            }
2022            StmtKind::With { object, body } => self.with_stmt(object, body)?,
2023            StmtKind::ClassDecl(class) => self.class_definition(class, false)?,
2024            // `import` emits nothing: hoisting already bound its names, and the host
2025            // fills their cells before the body runs.
2026            StmtKind::Import(_) => {}
2027            StmtKind::Export(decl) => self.export_stmt(decl)?,
2028        }
2029        Ok(())
2030    }
2031
2032    /// Compile `return`, running every enclosing finalizer on the way out.
2033    ///
2034    /// `nip_catch` is what makes this possible: it discards everything on the stack
2035    /// down to and including the `catch` offset while keeping the return value on
2036    /// top, so the frame the finalizer sees has the same shape as on the normal
2037    /// path.
2038    fn return_stmt(&mut self, value: Option<&Expr>) -> Result<(), SyntaxError> {
2039        let mut has_value = value.is_some();
2040        if let Some(expr) = value {
2041            // `return f(x)` is a tail call *only* when nothing has to happen to the
2042            // value afterwards. A `finally` or an open iterator in scope forces the
2043            // normal path, because the cleanup has to run after the call returns —
2044            // which is exactly what a tail call refuses to do.
2045            //
2046            // A **generator or async function** never tail-calls either: its `return` is
2047            // not a return to the caller but `return_async`, which reads the value off the
2048            // stack and finishes the coroutine. A tail call replaces the frame and hands
2049            // the callee's result straight to whoever resumed us, so the value vanished and
2050            // `it.next(42)` answered `{done: true, value: undefined}` for
2051            // `function* g(){ return f(yield) }`. The reference emits `call1` plus
2052            // `return_async` there and has no tail form for a suspending body at all.
2053            let plain = !self.cur().is_suspending()
2054                // A derived constructor's return is not just the value: a non-object answer
2055                // becomes `this`, so the frame has to survive to run that.
2056                && self.cur().ctor_kind != CtorKind::Derived
2057                && self
2058                    .cur()
2059                    .jump_targets
2060                    .iter()
2061                    .all(|target| target.finally_label.is_none() && !target.has_iterator);
2062            if plain && self.expr_if_tail_call(expr)? {
2063                // A tail call never reaches `expr`, so the direct-eval bookkeeping has to
2064                // happen here as well.
2065                self.note_direct_eval(expr);
2066                return Ok(());
2067            }
2068            self.expr(expr)?;
2069        }
2070        // `return v` in an *async generator* awaits `v` before anything else happens —
2071        // `AsyncGeneratorYield`/`AsyncGeneratorReturn` settle the value first, and the
2072        // reference's `emit_return` puts the `await` ahead of the `finally` unwinding for
2073        // exactly that reason ("the await must be done before handling the finally in case
2074        // it raises an exception").
2075        if has_value && self.cur().kind == FunctionKind::AsyncGenerator {
2076            self.emit(Opcode::Await, &[]);
2077            self.state().has_await = true;
2078        }
2079        has_value = self.emit_unwind_for_return(has_value);
2080        // A generator or async function does not return to its caller: it either
2081        // finishes, and the value becomes `{value, done: true}`, or it suspends.
2082        // `return_async` is the "finished" half, and it reads the value off the stack
2083        // rather than carrying it, which is what the resume machinery expects.
2084        if self.cur().is_suspending() {
2085            if !has_value {
2086                self.emit(Opcode::Undefined, &[]);
2087            }
2088            self.emit(Opcode::ReturnAsync, &[]);
2089            return Ok(());
2090        }
2091        // A derived constructor's result is `this` whenever the body does not answer an
2092        // object, and `this` is a local in the dead zone until `super()` returns — which is
2093        // why reading it here is also what turns `constructor(){ return; }` into the
2094        // ReferenceError the reference reports. The interpreter could not do this on its
2095        // own: by the time it sees `undefined` come back, the frame that held `this` is
2096        // gone, and `construct`'s own idea of `this` is the placeholder it made before the
2097        // body ran (`derived-class-return-override-with-{undefined,empty}`).
2098        if self.cur().ctor_kind == CtorKind::Derived {
2099            if !has_value {
2100                self.emit_var(VarAction::Get, "this");
2101                self.emit(Opcode::Return, &[]);
2102                return Ok(());
2103            }
2104            // `return <expr>` is only *sometimes* `this`: `undefined` is, any other
2105            // primitive is a `TypeError` (raised by `construct`), and an object replaces
2106            // `this` outright. Which one it is can only be known at run time.
2107            let keep = self.new_label();
2108            self.emit(Opcode::Dup, &[]);
2109            self.emit(Opcode::IsUndefined, &[]);
2110            self.emit_jump(Opcode::IfFalse, keep, &[]);
2111            self.emit(Opcode::Drop, &[]);
2112            self.emit_var(VarAction::Get, "this");
2113            self.place_label(keep);
2114            self.emit(Opcode::Return, &[]);
2115            return Ok(());
2116        }
2117        if has_value {
2118            self.emit(Opcode::Return, &[]);
2119        } else {
2120            self.emit(Opcode::ReturnUndef, &[]);
2121        }
2122        Ok(())
2123    }
2124
2125    /// Close an iterator: the reference's `emit_iterator_close`.
2126    ///
2127    /// The synchronous form is one opcode. The asynchronous one has to *await* the inner
2128    /// `return` — §7.4.6 calls the method and then `Await`s its result — so it is an inline
2129    /// sequence, and three details in it are load-bearing:
2130    ///
2131    /// * the iterator object is compared against `undefined` first, because a loop that
2132    ///   ran to completion clears that slot rather than closing an exhausted iterator;
2133    /// * a missing `return` method is not an error, so it is tested for `undefined`/`null`;
2134    /// * `preserve_completion` keeps whatever was underneath (the return value of the
2135    ///   function being left), which is why one branch ends on `nip` and the other on `drop`.
2136    fn emit_iterator_close(&mut self, is_async: bool, preserve_completion: bool) {
2137        if !is_async {
2138            if preserve_completion {
2139                self.emit(Opcode::Rot3r, &[]);
2140                self.emit(Opcode::Undefined, &[]);
2141            }
2142            self.emit(Opcode::IteratorClose, &[]);
2143            return;
2144        }
2145        if preserve_completion {
2146            // `iter next completion -> completion iter`
2147            self.emit(Opcode::Nip, &[]);
2148            self.emit(Opcode::Swap, &[]);
2149        } else {
2150            // `iter next catch_offset -> iter`
2151            self.emit(Opcode::Drop, &[]);
2152            self.emit(Opcode::Drop, &[]);
2153        }
2154        let done = self.new_label();
2155        let no_return = self.new_label();
2156        self.emit(Opcode::Dup, &[]);
2157        self.emit(Opcode::IsUndefined, &[]);
2158        self.emit_jump(Opcode::IfTrue, done, &[]);
2159        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("return"))]);
2160        self.emit(Opcode::Dup, &[]);
2161        self.emit(Opcode::IsUndefinedOrNull, &[]);
2162        self.emit_jump(Opcode::IfTrue, no_return, &[]);
2163        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
2164        self.emit(Opcode::Await, &[]);
2165        self.state().has_await = true;
2166        self.emit_jump(Opcode::Goto, done, &[]);
2167        self.place_label(no_return);
2168        self.emit(Opcode::Drop, &[]);
2169        self.place_label(done);
2170        self.emit(Opcode::Drop, &[]);
2171    }
2172
2173    /// Emit the finalizer/iterator cleanup for leaving the current position with a
2174    /// return, and report whether a value is now on the stack for it to carry.
2175    ///
2176    /// Shared by `return` and by the `return(v)` half of a `yield`: both abandon every
2177    /// enclosing `finally` at once, and the two used to be separate — the `yield` path
2178    /// simply emitted `return_async`, so `it.return()` ended the generator without ever
2179    /// running `finally` blocks the body was sitting inside.
2180    fn emit_unwind_for_return(&mut self, mut has_value: bool) -> bool {
2181        let targets = self.cur().jump_targets.clone();
2182        for target in targets.iter().rev() {
2183            if target.finally_label.is_none() && !target.has_iterator {
2184                continue;
2185            }
2186            if !has_value {
2187                // The cleanup expects a value to pass through; with nothing to
2188                // return, `undefined` stands in.
2189                self.emit(Opcode::Undefined, &[]);
2190                has_value = true;
2191            }
2192            self.emit(Opcode::NipCatch, &[]);
2193            if target.has_iterator {
2194                // Rewind to the loop's own slots and hand the close a dummy catch offset:
2195                // the loop is being abandoned, so there is nothing left to catch.
2196                self.emit_iterator_close(target.is_async_iterator, true);
2197            } else if let Some(finally) = target.finally_label {
2198                self.emit_jump(Opcode::Gosub, finally, &[]);
2199            }
2200        }
2201        has_value
2202    }
2203
2204    /// Compile a statement list, stopping at the first statement that cannot
2205    /// fall through.
2206    fn stmts(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2207        for (index, stmt) in body.iter().enumerate() {
2208            // A `using` declaration is not just a binding: everything after it, to the end
2209            // of the list, runs inside its disposal region. Compiling the rest of the list
2210            // recursively is what gives nested regions their innermost-first order.
2211            if Self::using_declaration(stmt).is_some() {
2212                return self.using_region(stmt, &body[index + 1..]);
2213            }
2214            self.stmt(stmt)?;
2215            if Self::terminates(stmt) {
2216                break;
2217            }
2218        }
2219        Ok(())
2220    }
2221
2222    /// The declaration a `using` statement carries, if it is one.
2223    fn using_declaration(stmt: &Stmt) -> Option<&VarDecl> {
2224        match &stmt.kind {
2225            StmtKind::VarDecl(decl) if decl.kind.is_using() => Some(decl),
2226            _ => None,
2227        }
2228    }
2229
2230    /// Compile `decl` and then the rest of its block, disposing when the block ends.
2231    ///
2232    /// The shape mirrors a `try`/`finally`, and deliberately so: the disposal has to run on
2233    /// every way out of the block — reaching its end, `return`, `break`, `continue`, and an
2234    /// exception — and this engine already funnels all of those through `catch` plus
2235    /// `gosub`. Registering the region as a jump target with a `finally_label` is what makes
2236    /// `return` and `break` dispose without knowing anything about `using`.
2237    ///
2238    /// ```text
2239    ///   <declaration>              value -> x, method -> x+1
2240    ///   catch CATCH                <- an exception in the rest lands here
2241    /// REST:
2242    ///   <the rest of the block>
2243    ///   drop                       <- the catch offset, on the fall-through path
2244    ///   undefined; gosub DISPOSE; drop
2245    ///   goto END
2246    /// CATCH:
2247    ///   using_dispose x            <- merges the failure into the pending exception
2248    ///   throw
2249    /// DISPOSE:
2250    ///   using_dispose_init
2251    ///   using_dispose x
2252    ///   using_dispose_end          <- rethrows if a dispose failed
2253    ///   ret
2254    /// END:
2255    /// ```
2256    fn using_region(&mut self, stmt: &Stmt, rest: &[Stmt]) -> Result<(), SyntaxError> {
2257        let Some(decl) = Self::using_declaration(stmt) else {
2258            unreachable!("using_region is only called for a using declaration");
2259        };
2260        // `using` binds exactly one name and has no pattern form, which the parser
2261        // enforces; the region still has to know *which* slot to dispose.
2262        let name = decl
2263            .declarators
2264            .first()
2265            .and_then(|declarator| match &declarator.target.kind {
2266                PatternKind::Ident(ident) => Some(ident.name.clone()),
2267                _ => None,
2268            });
2269        self.stmt(stmt)?;
2270        let Some(name) = name else {
2271            // Unreachable for a well-formed `using`, but a bare `using` with no declarator
2272            // must not make the compiler panic.
2273            return self.stmts(rest);
2274        };
2275        let Some(value_slot) = self.using_value_slot(&name) else {
2276            // Declared globally, which the parser rules out for a script; a module's
2277            // top level is a scope, and there the disposal stays a known gap.
2278            return self.stmts(rest);
2279        };
2280        // A block that ends in a `return` or a `throw` never reaches its own epilogue; the
2281        // exit path already disposed.
2282        let live = !rest.last().is_some_and(Self::terminates);
2283        self.using_region_around(value_slot, live, |compiler| compiler.stmts(rest))
2284    }
2285
2286    /// The slot a `using` binding's value lives in.
2287    fn using_value_slot(&self, name: &str) -> Option<u32> {
2288        self.cur()
2289            .vars
2290            .iter()
2291            .position(|var| var.name == name && var.kind == VarKind::Using)
2292            .map(|index| index as u32)
2293    }
2294
2295    /// Wrap `inside` in a disposal region for the resource in `value_slot`.
2296    ///
2297    /// Shared between a `using` statement — which owns the rest of its block — and a
2298    /// `for (using x of …)` body, which owns only one iteration. The shape mirrors a
2299    /// `try`/`finally`, deliberately: the disposal has to run on every way out — reaching
2300    /// the end, `return`, `break`, `continue`, and an exception — and this engine already
2301    /// funnels all of those through `catch` plus `gosub`. Registering the region as a jump
2302    /// target with a `finally_label` is what makes `return` and `break` dispose without
2303    /// knowing anything about `using`.
2304    ///
2305    /// ```text
2306    ///   catch CATCH                <- an exception inside lands here
2307    ///   <inside>
2308    ///   drop                       <- the catch offset, on the fall-through path
2309    ///   undefined; gosub DISPOSE; drop
2310    ///   goto END
2311    /// CATCH:
2312    ///   using_dispose slot         <- merges the failure into the pending exception
2313    ///   throw
2314    /// DISPOSE:
2315    ///   using_dispose_init
2316    ///   using_dispose slot
2317    ///   using_dispose_end          <- rethrows if a dispose failed
2318    ///   ret
2319    /// END:
2320    /// ```
2321    fn using_region_around(
2322        &mut self,
2323        value_slot: u32,
2324        live: bool,
2325        inside: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
2326    ) -> Result<(), SyntaxError> {
2327        let catch_label = self.new_label();
2328        let end_label = self.new_label();
2329        let dispose_label = self.new_label();
2330
2331        self.emit_jump(Opcode::Catch, catch_label, &[]);
2332        self.push_jump_target(JumpTarget {
2333            names: Vec::new(),
2334            break_label: None,
2335            continue_label: None,
2336            // The catch offset is the one thing on the stack that leaving has to remove.
2337            drop_count: 1,
2338            finally_label: Some(dispose_label),
2339            is_regular_stmt: false,
2340            has_iterator: false,
2341            is_async_iterator: false,
2342        });
2343        inside(self)?;
2344        self.pop_jump_target();
2345
2346        if live {
2347            self.emit(Opcode::Drop, &[]);
2348            self.emit(Opcode::Undefined, &[]);
2349            self.emit_jump(Opcode::Gosub, dispose_label, &[]);
2350            self.emit(Opcode::Drop, &[]);
2351            self.emit_jump(Opcode::Goto, end_label, &[]);
2352        }
2353
2354        // An exception unwinds to here with the thrown value on the stack, which is exactly
2355        // the shape `using_dispose` expects as its error state.
2356        self.place_label(catch_label);
2357        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2358        self.emit(Opcode::Throw, &[]);
2359
2360        self.place_label(dispose_label);
2361        // Inside the subroutine the return value and the `gosub` return address are both
2362        // live, and neither an outer finalizer nor another region may run before this one
2363        // has finished.
2364        self.push_jump_target(JumpTarget {
2365            names: Vec::new(),
2366            break_label: None,
2367            continue_label: None,
2368            drop_count: 2,
2369            finally_label: None,
2370            is_regular_stmt: false,
2371            has_iterator: false,
2372            is_async_iterator: false,
2373        });
2374        self.emit(Opcode::UsingDisposeInit, &[]);
2375        self.emit(Opcode::UsingDispose, &[Op::Slot(Slot::Loc(value_slot))]);
2376        self.emit(Opcode::UsingDisposeEnd, &[]);
2377        self.pop_jump_target();
2378        self.emit(Opcode::Ret, &[]);
2379        self.place_label(end_label);
2380        Ok(())
2381    }
2382
2383    /// Declare every name a statement list introduces, before compiling any of
2384    /// it, so a reference that appears textually before a declaration still
2385    /// resolves.
2386    ///
2387    /// Declarations are walked in source order because that is the order the
2388    /// reference numbers its slots in: `let a; var b;` gives `a` slot 0 and `b`
2389    /// slot 1, while `var b; let a;` gives the opposite. `var` and function
2390    /// declarations hoist out to the function scope; lexical names belong to the
2391    /// block they were written in, which `block` records.
2392    fn hoist(&mut self, body: &[Stmt], block: u64) -> Result<(), SyntaxError> {
2393        let saved = self.cur().current_block;
2394        self.state().current_block = block;
2395        let result = self.hoist_list(body);
2396        // Only now is every binding of this scope known, so the deferred function
2397        // bodies can be compiled against the finished list. Compiled at its own
2398        // declaration instead, a body that names a `var` written further down would
2399        // have resolved that name as a global.
2400        if result.is_ok() {
2401            let deferred = std::mem::take(&mut self.state().deferred_funcs);
2402            let mut outcome = Ok(());
2403            for (owner, func) in deferred {
2404                let previous = self.cur().current_block;
2405                self.state().current_block = owner;
2406                outcome = self.func_decl(&func);
2407                self.state().current_block = previous;
2408                if outcome.is_err() {
2409                    break;
2410                }
2411            }
2412            self.state().current_block = saved;
2413            return outcome;
2414        }
2415        // `current_block` is restored by the caller for a block statement, since
2416        // it needs it set while compiling; only clean up on the hoist path.
2417        self.state().current_block = saved;
2418        result
2419    }
2420
2421    fn hoist_list(&mut self, body: &[Stmt]) -> Result<(), SyntaxError> {
2422        for stmt in body {
2423            self.hoist_stmt(stmt)?;
2424        }
2425        Ok(())
2426    }
2427
2428    /// Whether a statement always transfers control away, making everything after
2429    /// it in the same list unreachable.
2430    ///
2431    /// The reference drops such statements in `skip_dead_code`, so `return 1;
2432    /// let x = 2;` compiles to the same bytecode as `return 1;`.
2433    fn terminates(stmt: &Stmt) -> bool {
2434        matches!(
2435            stmt.kind,
2436            StmtKind::Return(_) | StmtKind::Throw(_) | StmtKind::Break(_) | StmtKind::Continue(_)
2437        )
2438    }
2439
2440    fn hoist_stmt(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
2441        match &stmt.kind {
2442            StmtKind::VarDecl(decl) => {
2443                for declarator in &decl.declarators {
2444                    let mut names = Vec::new();
2445                    declarator.target.bound_names(&mut names);
2446                    for name in names {
2447                        let text = name.name.clone();
2448                        if decl.kind == VarDeclKind::Var {
2449                            let def = VarDef::var(text.clone());
2450                            self.declare_var(&text, def);
2451                        } else if decl.kind.is_using() {
2452                            // Two adjacent slots: the resource, then the dispose method
2453                            // snapshotted at declaration. `using_dispose` reads them as a
2454                            // pair `(slot, slot + 1)`, so nothing may be declared between
2455                            // them — which is why both are declared here, in one step,
2456                            // rather than the method being added at emission time.
2457                            self.declare_using(&text);
2458                        } else {
2459                            let def = if decl.kind == VarDeclKind::Const {
2460                                VarDef::constant(text.clone())
2461                            } else {
2462                                VarDef::lexical(text.clone())
2463                            };
2464                            self.declare(&text, def);
2465                        }
2466                    }
2467                }
2468            }
2469            StmtKind::FuncDecl(func) => {
2470                if let Some(name) = &func.name {
2471                    // A function declaration is a `var` binding that happens to
2472                    // hold a function, not a lexical one.
2473                    let def = VarDef::var(name.name.clone());
2474                    self.declare_var(&name.name.clone(), def);
2475                }
2476                // The function object is created when the scope is entered, so it
2477                // exists before the declaration is reached. Its body is compiled
2478                // *after* this scope's hoisting finishes, so a name it uses resolves
2479                // even when the `var` that declares it comes later in the source.
2480                let owner = self.cur().current_block;
2481                self.state().deferred_funcs.push((owner, func.clone()));
2482            }
2483            StmtKind::ClassDecl(class) => {
2484                if let Some(name) = &class.name {
2485                    self.declare(&name.name.clone(), VarDef::lexical(name.name.clone()));
2486                }
2487            }
2488            // A module's imports are bound before any of its code runs, and its exports
2489            // declare the very bindings they export — so both hoist the declarations
2490            // their `StmtKind` arm will later emit code for.
2491            StmtKind::Import(decl) => self.hoist_import(decl)?,
2492            StmtKind::Export(decl) => self.hoist_export(decl)?,
2493            StmtKind::Block(inner) => self.hoist_block(stmt.span.start.offset as u64, inner)?,
2494            StmtKind::If { cons, alt, .. } => {
2495                self.hoist_stmt(cons)?;
2496                if let Some(alt) = alt {
2497                    self.hoist_stmt(alt)?;
2498                }
2499            }
2500            StmtKind::While { body, .. }
2501            | StmtKind::DoWhile { body, .. }
2502            | StmtKind::Labeled { body, .. }
2503            | StmtKind::With { body, .. } => self.hoist_stmt(body)?,
2504            StmtKind::For { init, body, .. } => {
2505                // A `for` head gets its own scope even when it declares nothing,
2506                // because `let` in the head is scoped to the loop.
2507                let key = stmt.span.start.offset as u64;
2508                let parent = self.cur().current_block;
2509                self.push_block(key, parent);
2510                if let Some(init) = init
2511                    && let ForInit::VarDecl(decl) = init
2512                {
2513                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2514                }
2515                self.hoist_stmt(body)?;
2516                self.state().current_block = parent;
2517            }
2518            StmtKind::ForIn { left, body, .. } | StmtKind::ForOf { left, body, .. } => {
2519                let key = stmt.span.start.offset as u64;
2520                let parent = self.cur().current_block;
2521                self.push_block(key, parent);
2522                if let ForHead::VarDecl(decl) = left {
2523                    self.hoist_stmt(&Stmt::new(StmtKind::VarDecl(decl.clone()), stmt.span))?;
2524                }
2525                self.hoist_stmt(body)?;
2526                self.state().current_block = parent;
2527            }
2528            StmtKind::Try {
2529                block,
2530                handler,
2531                finalizer,
2532            } => {
2533                self.hoist_block(Self::try_block_key(stmt, TryPart::Block), block)?;
2534                let try_parent = self.cur().current_block;
2535                if let Some(handler) = handler {
2536                    // The catch parameter belongs to the function scope, not to a
2537                    // block: it is a `catch` binding rather than a `let`, so it is
2538                    // never in the temporal dead zone and `emit_scope_enter` must
2539                    // not mark it uninitialised. It still has to be declared before
2540                    // the handler body is hoisted, so it takes the slot the
2541                    // reference gives it (bindings are numbered in source order).
2542                    if let Some(pattern) = &handler.param {
2543                        // The parameter gets its own scope, so entering the handler
2544                        // does not have to re-declare it. It is not lexical, so it
2545                        // is never marked uninitialised.
2546                        let key = Self::try_block_key(stmt, TryPart::Param);
2547                        let parent = self.cur().current_block;
2548                        self.push_block(key, parent);
2549                        // A destructuring parameter binds several names, one slot each,
2550                        // in the order they are written. The reference declares those as
2551                        // `let`s rather than as one `catch` binding — its dump prints
2552                        // `0: let e` for `catch ({e})` but `0: catch e` for `catch (e)` —
2553                        // so the kind follows the shape of the parameter.
2554                        //
2555                        // Neither form is in the dead zone: the stores run as the handler
2556                        // is entered, so both use the unchecked `put_loc`.
2557                        let destructures = !matches!(pattern.kind, PatternKind::Ident(_));
2558                        let mut names = Vec::new();
2559                        pattern.bound_names(&mut names);
2560                        for name in names {
2561                            let def = VarDef {
2562                                name: name.name.clone(),
2563                                is_const: false,
2564                                is_lexical: destructures,
2565                                kind: if destructures {
2566                                    crate::bytecode::VarKind::LexicalCatch
2567                                } else {
2568                                    crate::bytecode::VarKind::Catch
2569                                },
2570                                is_captured: false,
2571                                scope_level: 0,
2572                                scope_next: None,
2573                            };
2574                            self.declare_local(&name.name.clone(), def);
2575                        }
2576                        // The handler body nests inside the parameter's scope, so the
2577                        // body's bindings chain on to the parameter (the reference
2578                        // prints `let y [next:1]`, pointing at `e`).
2579                        self.state().current_block = key;
2580                    }
2581                    self.hoist_block(Self::try_block_key(stmt, TryPart::Catch), &handler.body)?;
2582                    // Back to the block the `try` itself lives in, so the finalizer
2583                    // is a sibling of the handler rather than nested in it.
2584                    self.state().current_block = try_parent;
2585                }
2586                if let Some(finalizer) = finalizer {
2587                    self.hoist_block(Self::try_block_key(stmt, TryPart::Finally), finalizer)?;
2588                }
2589            }
2590            StmtKind::Switch { cases, .. } => {
2591                let key = stmt.span.start.offset as u64;
2592                let parent = self.cur().current_block;
2593                self.push_block(key, parent);
2594                for case in cases {
2595                    self.hoist_list(&case.body)?;
2596                }
2597                self.state().current_block = parent;
2598            }
2599            _ => {}
2600        }
2601        Ok(())
2602    }
2603
2604    /// Hoist a nested statement list, which is its own lexical scope.
2605    fn hoist_block(&mut self, key: u64, body: &[Stmt]) -> Result<(), SyntaxError> {
2606        let parent = self.cur().current_block;
2607        self.push_block(key, parent);
2608        self.hoist_list(body)?;
2609        self.state().current_block = parent;
2610        Ok(())
2611    }
2612
2613    /// A block key for one part of a `try` statement.
2614    ///
2615    /// The three parts are three separate scopes, so they cannot share the key a
2616    /// statement's own offset would give them: the try block, the handler body and
2617    /// the finalizer would then look like one scope, and their `let` bindings would
2618    /// be marked uninitialised only on entering the first of them.
2619    fn try_block_key(stmt: &Stmt, part: TryPart) -> u64 {
2620        (stmt.span.start.offset as u64) * 4 + part as u64
2621    }
2622
2623    /// Declare a `var`: it lives in the function's own scope, not the block's.
2624    fn declare_var(&mut self, name: &str, def: VarDef) {
2625        if self.cur().is_module {
2626            self.declare_module(name, &def);
2627            return;
2628        }
2629        if self.cur().declares_globally(&def) {
2630            self.declare_global(name, &def);
2631            return;
2632        }
2633        let state = self.state();
2634        // A binding of the *parameter* scope does not count: the body's `var` of the
2635        // same name is a different binding and needs a slot of its own.
2636        if state.vars.iter().enumerate().any(|(index, v)| {
2637            v.name == name && state.var_block.get(index).copied() != Some(PARAM_SCOPE)
2638        }) {
2639            return;
2640        }
2641        // A `var` belongs to the function scope, never to the enclosing block.
2642        state.var_block.push(FUNCTION_SCOPE);
2643        state.vars.push(def);
2644    }
2645
2646    /// Declare `name` as a binding of the parameter scope, returning its slot.
2647    fn declare_param_var(&mut self, name: &str) -> u32 {
2648        declare_param_var_at(self.state(), name)
2649    }
2650
2651    /// Declare one of the parameter list's own bindings: a `let` of the parameter scope.
2652    ///
2653    /// The `scope_next` chain is the reference's. Bindings are prepended to their scope,
2654    /// so each points at the one declared before it and the oldest ends the chain with
2655    /// `-2` (`ARG_SCOPE_END`); the dump prints exactly that, and the chain is what the
2656    /// runtime walks when it instantiates them.
2657    fn declare_param_binding(&mut self, name: &str) -> u32 {
2658        let state = self.state();
2659        let previous = state
2660            .vars
2661            .iter()
2662            .enumerate()
2663            .rev()
2664            .find(|(index, var)| {
2665                state.var_block.get(*index).copied() == Some(PARAM_SCOPE) && var.is_lexical
2666            })
2667            .map(|(index, _)| index as i32);
2668        let index = state.vars.len() as u32;
2669        state.var_block.push(PARAM_SCOPE);
2670        let mut def = VarDef::lexical(name);
2671        // A scope of its own, so the dump prints `[next:…]`. The parameter scope is not
2672        // the function's, and its bindings are initialised one by one rather than all at
2673        // once — which is exactly what the dead zone needs.
2674        def.scope_level = 1;
2675        def.scope_next = Some(previous.unwrap_or(-2));
2676        state.vars.push(def);
2677        index
2678    }
2679
2680    /// The slot of a parameter-list binding, if the list has one by that name.
2681    fn param_binding_slot(&self, name: &str) -> Option<u32> {
2682        let state = self.cur();
2683        state
2684            .vars
2685            .iter()
2686            .enumerate()
2687            .position(|(index, var)| {
2688                var.name == name
2689                    && var.is_lexical
2690                    && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
2691            })
2692            .map(|index| index as u32)
2693    }
2694
2695    /// Every parameter-list binding, in declaration order.
2696    fn param_binding_names(&self) -> Vec<String> {
2697        let state = self.cur();
2698        state
2699            .vars
2700            .iter()
2701            .enumerate()
2702            .filter(|(index, var)| {
2703                var.is_lexical && state.var_block.get(*index).copied() == Some(PARAM_SCOPE)
2704            })
2705            .map(|(_, var)| var.name.clone())
2706            .collect()
2707    }
2708
2709    /// The body's own binding for `name`, as opposed to the parameter's copy of it.
2710    fn body_var_slot(&self, name: &str) -> Option<u32> {
2711        let state = self.cur();
2712        state
2713            .vars
2714            .iter()
2715            .enumerate()
2716            .find(|(index, var)| {
2717                var.name == name && state.var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
2718            })
2719            .map(|(index, _)| index as u32)
2720    }
2721
2722    /// Give the *parameter* scope an `arguments` binding if the parameter list mentions
2723    /// one.
2724    ///
2725    /// With parameter expressions the reference creates two: an unmapped one in the
2726    /// argument scope, for the defaults and anything they close over, and the body's own.
2727    /// They are separate bindings, which is what makes
2728    /// `(a = eval("var arguments = 1"), p = () => arguments) => { var arguments = 2 }`
2729    /// report 1 from `p` and 2 from the body.
2730    fn provide_param_arguments(&mut self) {
2731        if !self.cur().has_parameter_expressions {
2732            return;
2733        }
2734        let mentioned = self.cur().needs_param_arguments
2735            || self
2736                .cur()
2737                .insns
2738                .iter()
2739                .any(|insn| matches!(insn, Insn::Var { name, in_params: true, .. } if name == "arguments"));
2740        if !mentioned {
2741            return;
2742        }
2743        let slot = self.declare_param_var("arguments");
2744        let magic = if self.cur().strict || !self.cur().simple_parameter_list {
2745            0
2746        } else {
2747            1
2748        };
2749        self.prepend_initialiser_to(
2750            slot,
2751            Insn::Fixed {
2752                op: Opcode::SpecialObject,
2753                operands: vec![Op::Int(magic)],
2754            },
2755        );
2756    }
2757
2758    /// [`Compiler::prepend_initialiser`] for a slot rather than a name.
2759    fn prepend_initialiser_to(&mut self, slot: u32, producer: Insn) {
2760        let current = self.stack.len() - 1;
2761        let init = [
2762            producer,
2763            Insn::Fixed {
2764                op: Opcode::PutLoc,
2765                operands: vec![Op::Slot(Slot::Loc(slot))],
2766            },
2767        ];
2768        let inserted = init.len();
2769        for (index, instruction) in init.into_iter().enumerate() {
2770            self.stack[current].insns.insert(index, instruction);
2771        }
2772        for placed in self.stack[current].labels.iter_mut().flatten() {
2773            *placed += inserted;
2774        }
2775        self.state().label_since_insn = false;
2776    }
2777
2778    /// Give the function an `arguments` binding if its body mentions one.
2779    ///
2780    /// The check runs on the *instruction* stream rather than the AST: by this point
2781    /// every reference has become an `Insn::Var`, so scanning is exact and needs no
2782    /// AST walker. Declaring lazily matters for more than tidiness — always declaring
2783    /// would renumber every later local slot and stop the bytecode matching the
2784    /// reference, which only adds the binding when the body uses it.
2785    ///
2786    /// `arguments` is a local, initialised at the top of the body by
2787    /// `special_object`; that is the reference's shape, so the disassembly agrees.
2788    fn provide_arguments(&mut self) {
2789        let current = self.stack.len() - 1;
2790        if self.stack[current].is_script || self.stack[current].is_module {
2791            // A module has no `arguments` binding; referring to it is a ReferenceError,
2792            // which is exactly what an unbound name produces.
2793            return;
2794        }
2795        // An arrow has no `arguments` of its own: the binding belongs to the enclosing
2796        // function, which is why `() => arguments` sees the caller's arguments.
2797        if self.stack[current].is_arrow {
2798            if self.mentions("arguments") {
2799                self.ensure_enclosing_arguments();
2800            }
2801            return;
2802        }
2803        // Only a *body* mention needs the body's binding: the parameter list has one of
2804        // its own (see [`Compiler::provide_param_arguments`]).
2805        //
2806        // `delete arguments` counts too: it compiles to `DeleteVar`, which is not a
2807        // `Var`, so without this the body got no binding at all — the name resolved to
2808        // the global object and `delete` answered `true` for a binding that cannot be
2809        // deleted. The reference answers `false`.
2810        let mentioned = self.cur().insns.iter().any(|insn| match insn {
2811            Insn::Var {
2812                name, in_params, ..
2813            } => name == "arguments" && !*in_params,
2814            Insn::DeleteVar { name } => name == "arguments",
2815            _ => false,
2816        });
2817        // A mention that resolves to the body's *own* lexical `arguments` is not a request
2818        // for the implicit one — `function f(p = 1) { let arguments; }` shadows it, and the
2819        // implicit binding is not created at all. Providing it anyway was worse than useless:
2820        // its prologue store resolved past the shadowing `let` and landed on the **global**,
2821        // so `function f(p = eval("var arguments")) { let arguments; }` defined
2822        // `globalThis.arguments` as a side effect (`globalThis.arguments unchanged` in
2823        // test262's `fn-body-cntns-arguments-lex-bind` family).
2824        //
2825        // Lexical only. `var arguments = 1` in the body is a different thing entirely: the
2826        // var *is* the binding, and the implicit arguments object is initialised into it at
2827        // entry, which is why `function f(){ return typeof arguments; var arguments = 1 }`
2828        // answers `"object"` (`S13_A15_T4`). Suppressing the prologue for those two made
2829        // `typeof arguments` `"undefined"`.
2830        if self
2831            .cur()
2832            .vars
2833            .iter()
2834            .any(|var| var.name == "arguments" && var.needs_check())
2835        {
2836            return;
2837        }
2838        if !mentioned && !self.cur().needs_arguments_local {
2839            return;
2840        }
2841        // The request may have come only from a parameter-list arrow, in which case the
2842        // parameter scope's binding already answers for it and the body needs none.
2843        if !mentioned && self.cur().has_parameter_expressions && !self.body_mentions_arguments() {
2844            return;
2845        }
2846        // 0 is strict `arguments`, 1 is sloppy (mapped) `arguments`.
2847        //
2848        // With parameter expressions the list and the body are separate environments, so
2849        // an assignment to a parameter cannot be reflected into `arguments` at all — the
2850        // arguments object is unmapped whatever the mode, which is why the reference emits
2851        // `special_object 0` here even in sloppy code.
2852        // A non-simple parameter list (`[a]`, `...rest`, `a = 1`) makes the arguments
2853        // object unmapped whatever the mode — §10.4.4 keys the decision on
2854        // `IsSimpleParameterList`, not on strictness alone.
2855        let magic = if self.stack[current].strict || !self.stack[current].simple_parameter_list {
2856            0
2857        } else {
2858            1
2859        };
2860        // A mapped `arguments` shares storage with the parameters: `arguments[0] = 2`
2861        // has to be visible as `a`, and assigning `a` has to be visible as `arguments[0]`.
2862        // The only storage both sides can see is a reference cell, so every parameter the
2863        // object maps gets one — even a parameter no closure captured. Without this the
2864        // slot holds a plain copy and the mapping has nothing to write through.
2865        if magic == 1 {
2866            for arg in &mut self.stack[current].args {
2867                arg.is_captured = true;
2868            }
2869        }
2870        self.prepend_binding("arguments", magic);
2871    }
2872
2873    /// Whether a *body* instruction refers to `arguments`.
2874    fn body_mentions_arguments(&self) -> bool {
2875        self.cur()
2876            .insns
2877            .iter()
2878            .any(|insn| matches!(insn, Insn::Var { name, in_params, .. } if name == "arguments" && !*in_params))
2879    }
2880
2881    /// Whether the function body's instruction stream refers to `name`.
2882    fn mentions(&self, name: &str) -> bool {
2883        let current = self.stack.len() - 1;
2884        // A binding of the parameter scope does not answer for the body: the body's own
2885        // `arguments` (or self-name) still has to be provided for it.
2886        if self.stack[current]
2887            .vars
2888            .iter()
2889            .enumerate()
2890            .any(|(index, v)| {
2891                v.name == name
2892                    && self.stack[current].var_block.get(index).copied() != Some(PARAM_SCOPE)
2893            })
2894        {
2895            return false;
2896        }
2897        self.stack[current]
2898            .insns
2899            .iter()
2900            .any(|insn| matches!(insn, Insn::Var { name: used, .. } if used == name))
2901    }
2902
2903    /// Bind the name a named function expression uses to refer to itself.
2904    ///
2905    /// The value is `special_object 2`, the function currently running, so the binding
2906    /// is the closure itself and not a copy. It is a local of this function, which is
2907    /// what keeps `g` out of the enclosing scope.
2908    /// Give the function a local `this`, for an arrow inside it to capture.
2909    fn provide_this_local(&mut self) {
2910        let current = self.stack.len() - 1;
2911        if !self.stack[current].needs_this_local || self.stack[current].has_this_prologue {
2912            return;
2913        }
2914        if !self.stack[current]
2915            .vars
2916            .iter()
2917            .any(|var| var.name == "this")
2918        {
2919            self.declare_hidden_local("this", VarKind::Normal);
2920        }
2921        self.prepend_initialiser(
2922            "this",
2923            Insn::Fixed {
2924                op: Opcode::PushThis,
2925                operands: vec![],
2926            },
2927        );
2928    }
2929
2930    /// Give the function a local `<home_object>`, for an arrow or a static block inside it
2931    /// to read through `super`.
2932    fn provide_home_object_local(&mut self) {
2933        let current = self.stack.len() - 1;
2934        if !self.stack[current].needs_home_object_local {
2935            return;
2936        }
2937        if !self.stack[current]
2938            .vars
2939            .iter()
2940            .any(|var| var.name == HOME_OBJECT)
2941        {
2942            self.declare_hidden_local(HOME_OBJECT, VarKind::Normal);
2943        }
2944        self.prepend_initialiser(
2945            HOME_OBJECT,
2946            Insn::Fixed {
2947                op: Opcode::SpecialObject,
2948                operands: vec![Op::Int(4)],
2949            },
2950        );
2951    }
2952
2953    fn provide_self_name(&mut self) {
2954        let current = self.stack.len() - 1;
2955        let Some(name) = self.stack[current].self_name.clone() else {
2956            return;
2957        };
2958        if self.stack[current].self_name_initialized {
2959            return;
2960        }
2961        // Either the body refers to the name, or a nested function already forced the
2962        // binding into existence while being resolved. A direct `eval` can name it
2963        // without mentioning it, so its presence is a third reason: in strict mode
2964        // `eval("f = 1")` has to raise a `TypeError` rather than a `ReferenceError`, and
2965        // that only happens if the binding exists.
2966        let declared = self.stack[current].vars.iter().any(|v| v.name == name);
2967        if !declared && !self.mentions(&name) && !self.stack[current].has_direct_eval {
2968            return;
2969        }
2970        self.stack[current].self_name_initialized = true;
2971        self.prepend_binding_with(&name, 2, VarKind::FunctionName);
2972    }
2973
2974    /// Insert `special_object magic` plus the store to `name` at the top of the body.
2975    ///
2976    /// Prepending shifts every label that has been placed, so they are all moved by
2977    /// the number of instructions inserted.
2978    fn prepend_binding(&mut self, name: &str, magic: i32) {
2979        self.prepend_binding_with(name, magic, VarKind::Normal);
2980    }
2981
2982    /// [`Compiler::prepend_binding`] for a binding that is more than a plain local.
2983    fn prepend_binding_with(&mut self, name: &str, magic: i32, kind: VarKind) {
2984        let current = self.stack.len() - 1;
2985        // A function-expression's own name is immutable in strict mode, which is what
2986        // makes `f = 1` inside a strict body throw instead of being dropped.
2987        let is_const = kind == VarKind::FunctionName && self.stack[current].strict;
2988        self.declare_var(
2989            name,
2990            VarDef {
2991                kind,
2992                is_const,
2993                ..VarDef::var(name)
2994            },
2995        );
2996        let init = [
2997            Insn::Fixed {
2998                op: Opcode::SpecialObject,
2999                operands: vec![Op::Int(magic)],
3000            },
3001            Insn::Var {
3002                // An initialisation, not an assignment: sloppy mode drops stores to a
3003                // function-expression's own name, and the prologue is what puts the
3004                // value there in the first place.
3005                action: if kind == VarKind::FunctionName {
3006                    VarAction::PutInit
3007                } else {
3008                    VarAction::Put
3009                },
3010                name: name.to_string(),
3011                block: 0,
3012                in_params: false,
3013            },
3014        ];
3015        let inserted = init.len();
3016        for (index, instruction) in init.into_iter().enumerate() {
3017            self.stack[current].insns.insert(index, instruction);
3018        }
3019        for placed in self.stack[current].labels.iter_mut().flatten() {
3020            *placed += inserted;
3021        }
3022        // A store sits at the insertion point now, so the `put`/`get` fold must not
3023        // reach across it.
3024        self.stack[current].label_since_insn = true;
3025    }
3026
3027    /// Record a top-level script declaration as a global.
3028    ///
3029    /// A script's top-level `var`/`let`/`function` create properties of the
3030    /// global object, not slots in the script's frame, so they show up as closure
3031    /// variables instead.
3032    fn declare_global(&mut self, name: &str, def: &VarDef) {
3033        let state = self.state();
3034        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
3035            // The name was already referenced, from a function compiled before this
3036            // declaration was reached — `function a(){ b() } function b(){}` resolves
3037            // `b` while `b` is still unknown, and that guess has to be corrected here.
3038            // Leaving it as a plain global meant the declaration was never registered,
3039            // so the binding did not exist at run time and `a()` threw
3040            // `b is not defined`.
3041            if matches!(existing.closure_type, ClosureType::Global) {
3042                existing.closure_type = ClosureType::GlobalDecl;
3043                existing.is_const = def.is_const;
3044                existing.is_lexical = def.is_lexical;
3045            }
3046            return;
3047        }
3048        state.closure_vars.push(ClosureVar {
3049            name: name.to_string(),
3050            is_const: def.is_const,
3051            is_lexical: def.is_lexical,
3052            closure_type: ClosureType::GlobalDecl,
3053            var_idx: 0,
3054        });
3055    }
3056
3057    /// Record a module-level declaration as a module variable.
3058    ///
3059    /// The binding is a closure variable of the module body, so reads and writes are
3060    /// ordinary `var_ref` opcodes — the same shape a captured local has. What differs is
3061    /// *who fills the cell*: the module record does, before the body runs, and an import
3062    /// points its cell at the exporting module's, which is what makes bindings live and
3063    /// cycles work.
3064    fn declare_module(&mut self, name: &str, def: &VarDef) -> u32 {
3065        let state = self.state();
3066        if let Some(existing) = state.closure_vars.iter_mut().find(|c| c.name == name) {
3067            // The name may have been referenced before this declaration was hoisted,
3068            // which resolved it as a plain global. Correct that here, the way
3069            // `declare_global` does.
3070            if matches!(existing.closure_type, ClosureType::Global) {
3071                existing.closure_type = ClosureType::ModuleDecl;
3072                existing.is_const = def.is_const;
3073                existing.is_lexical = def.is_lexical;
3074            }
3075            return 0;
3076        }
3077        state.closure_vars.push(ClosureVar {
3078            name: name.to_string(),
3079            is_const: def.is_const,
3080            is_lexical: def.is_lexical,
3081            closure_type: ClosureType::ModuleDecl,
3082            var_idx: 0,
3083        });
3084        0
3085    }
3086
3087    /// Declare a module variable and answer its closure-variable index.
3088    ///
3089    /// [`Compiler::declare_module`] answers `0` because its callers want a *slot*, and a
3090    /// module variable is not one. The import table needs the real index instead, because
3091    /// that is the position the host writes the cell into.
3092    fn declare_module_var(&mut self, name: &str, def: &VarDef) -> u32 {
3093        self.declare_module(name, def);
3094        self.cur()
3095            .closure_vars
3096            .iter()
3097            .position(|c| c.name == name)
3098            .map(|index| index as u32)
3099            .unwrap_or(0)
3100    }
3101
3102    /// Declare one imported binding as a module variable.
3103    ///
3104    /// Returns the closure-variable index, which is what the import table records: the
3105    /// host writes the exporter's cell into that slot before the body runs.
3106    fn declare_import(&mut self, name: &str, is_const: bool) -> u32 {
3107        let state = self.state();
3108        if let Some(index) = state.closure_vars.iter().position(|c| c.name == name) {
3109            // Keep the slot, fix the kind: the name may already have been referenced.
3110            state.closure_vars[index].closure_type = ClosureType::ModuleImport;
3111            state.closure_vars[index].is_const = is_const;
3112            return index as u32;
3113        }
3114        state.closure_vars.push(ClosureVar {
3115            name: name.to_string(),
3116            // An imported binding cannot be assigned: `x = 1` on an import is a
3117            // `TypeError` at run time, which the const flag is what produces.
3118            is_const: true,
3119            // Lexical, so reads go through `get_var_ref_check`: before linking has filled
3120            // the cell an import is in its dead zone, and reading it there must say so
3121            // rather than answer `undefined`.
3122            is_lexical: true,
3123            closure_type: ClosureType::ModuleImport,
3124            var_idx: 0,
3125        });
3126        state.closure_vars.len() as u32 - 1
3127    }
3128
3129    /// Emit the code an `export` needs.
3130    ///
3131    /// Only `export default <expr>` has any: everything else is a table entry whose
3132    /// binding is declared elsewhere. The expression is stored into the hidden
3133    /// `*default*` variable rather than returned, because the module body has no value
3134    /// to speak of.
3135    fn export_stmt(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3136        match &decl.kind {
3137            ExportKind::Declaration(stmt) => self.stmt(stmt),
3138            ExportKind::Default(expr) => {
3139                // `export default class Foo {}`: evaluate the declaration (which binds
3140                // `Foo`), then copy its value into the hidden `*default*` binding, because a
3141                // class declaration is a *statement* and `expr` cannot be compiled as one.
3142                if let ExprKind::Class(class) = &expr.kind
3143                    && class.name.is_some()
3144                {
3145                    self.stmt(&Stmt {
3146                        kind: StmtKind::ClassDecl(class.clone()),
3147                        span: expr.span,
3148                    })?;
3149                    let Some(name) = &class.name else {
3150                        return Ok(());
3151                    };
3152                    self.emit_var(VarAction::Get, &name.name);
3153                    let index = self.declare_export_default();
3154                    self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3155                    return Ok(());
3156                }
3157                // A named default function/class is already a module binding; the export
3158                // points at it and there is nothing to evaluate.
3159                if matches!(&expr.kind, ExprKind::Function(func) if func.name.is_some()) {
3160                    return Ok(());
3161                }
3162                self.expr(expr)?;
3163                // §16.2.1.10 step 1.b: an *anonymous* default export is named `"default"`
3164                // by `SetFunctionName`, exactly as `var f = function(){}` is named `f`. The
3165                // name is observable — `imported.default.name` — and without this an
3166                // anonymous `export default class {}` arrived with the empty name.
3167                self.set_name_if_anonymous(expr, &Wtf8::new("default"));
3168                let index = self.declare_export_default();
3169                self.emit(Opcode::PutVarRef, &[Op::Slot(Slot::VarRef(index))]);
3170                Ok(())
3171            }
3172            ExportKind::Named { .. } | ExportKind::All { .. } => Ok(()),
3173        }
3174    }
3175
3176    /// A module name as the string it denotes.
3177    fn module_name_text(name: &ModuleName) -> &str {
3178        match name {
3179            ModuleName::Ident(ident) => &ident.name,
3180            ModuleName::Str(text) => text,
3181        }
3182    }
3183
3184    /// Bind `import`'s local names and record where each one comes from.
3185    ///
3186    /// Nothing is emitted: an import is not an instruction, it is a promise that the
3187    /// binding's cell will be filled before the body runs. The cell lands in the module's
3188    /// environment at a fixed index, and the host fills it from the exporter's cell —
3189    /// which is why a cyclic import can bind before the other module has evaluated.
3190    fn hoist_import(&mut self, decl: &ImportDecl) -> Result<(), SyntaxError> {
3191        let request = self.module_request(&decl.source, &decl.attributes);
3192        for specifier in &decl.specifiers {
3193            let (local, name, is_star) = match specifier {
3194                ImportSpecifier::Default(ident) => {
3195                    (ident.name.clone(), "default".to_string(), false)
3196                }
3197                ImportSpecifier::Namespace(ident) => (ident.name.clone(), String::new(), true),
3198                ImportSpecifier::Named { imported, local } => (
3199                    local.name.clone(),
3200                    Self::module_name_text(imported).to_string(),
3201                    false,
3202                ),
3203            };
3204            // `import * as ns` is *not* a live binding of another module's variable —
3205            // it is a value of its own, which is why the reference declares it like a
3206            // module variable and the host stores the namespace object in that cell.
3207            let var_idx = if is_star {
3208                // `const`: a namespace object is a value, and the binding is immutable.
3209                self.declare_module_var(&local, &VarDef::constant(local.clone()))
3210            } else {
3211                self.declare_import(&local, true)
3212            };
3213            self.module_meta().imports.push(ImportEntry {
3214                module: request,
3215                name,
3216                var_idx,
3217                is_star,
3218            });
3219        }
3220        Ok(())
3221    }
3222
3223    /// Record what an `export` offers, declaring the binding it exports.
3224    ///
3225    /// `export var x = 1` is a declaration like any other; only the table entry is extra.
3226    fn hoist_export(&mut self, decl: &ExportDecl) -> Result<(), SyntaxError> {
3227        match &decl.kind {
3228            ExportKind::Declaration(stmt) => {
3229                // The inner declaration keeps its own hoisting, then every name it binds
3230                // becomes an export of the same name.
3231                self.hoist_stmt(stmt)?;
3232                let mut names = Vec::new();
3233                Self::declared_names(stmt, &mut names);
3234                for name in names {
3235                    let var_idx = self.module_binding_index(&name);
3236                    self.exports_local(&name, var_idx);
3237                }
3238            }
3239            ExportKind::Default(expr) => {
3240                // The reference puts a default export in a hidden `*default*` variable,
3241                // so `export default function f(){}` can export a *value* while `f` stays
3242                // a binding of the module.
3243                if let ExprKind::Function(func) = &expr.kind
3244                    && let Some(name) = &func.name
3245                {
3246                    let text = name.name.clone();
3247                    self.hoist_stmt(&Stmt {
3248                        kind: StmtKind::FuncDecl(func.clone()),
3249                        span: expr.span,
3250                    })?;
3251                    let var_idx = self.module_binding_index(&text);
3252                    self.module_meta().exports.push(ExportEntry::Local {
3253                        export_name: "default".to_string(),
3254                        var_idx,
3255                    });
3256                    return Ok(());
3257                }
3258                if let ExprKind::Class(class) = &expr.kind
3259                    && class.name.is_some()
3260                {
3261                    // `export default class Foo {}` binds `Foo` in the module scope **and**
3262                    // stores the class into the hidden `*default*` binding — it is a
3263                    // declaration *and* a value, unlike `export default class {}` which is
3264                    // only a value.
3265                    //
3266                    // Pointing the `default` export straight at `Foo` looked simpler and was
3267                    // wrong twice over: `module_binding_index` did not find the lexical
3268                    // binding the hoist had just made, so it declared a second one that
3269                    // nothing ever wrote, and `export_stmt` then had no code to emit for the
3270                    // declaration either. `imported.default` came out `undefined` and `Foo`
3271                    // was not in scope inside its own module.
3272                    self.hoist_stmt(&Stmt {
3273                        kind: StmtKind::ClassDecl(class.clone()),
3274                        span: expr.span,
3275                    })?;
3276                    let var_idx = self.declare_export_default();
3277                    self.exports_local("default", var_idx);
3278                    return Ok(());
3279                }
3280                let var_idx = self.declare_export_default();
3281                self.module_meta().exports.push(ExportEntry::Local {
3282                    export_name: "default".to_string(),
3283                    var_idx,
3284                });
3285            }
3286            ExportKind::Named {
3287                specifiers,
3288                source,
3289                attributes,
3290            } => match source {
3291                Some(source) => {
3292                    let request = self.module_request(source, attributes);
3293                    for specifier in specifiers {
3294                        self.module_meta().exports.push(ExportEntry::Indirect {
3295                            export_name: Self::module_name_text(&specifier.exported).to_string(),
3296                            module: request,
3297                            import_name: Self::module_name_text(&specifier.local).to_string(),
3298                        });
3299                    }
3300                }
3301                None => {
3302                    for specifier in specifiers {
3303                        let local = Self::module_name_text(&specifier.local).to_string();
3304                        let export_name = Self::module_name_text(&specifier.exported).to_string();
3305                        // `export { x }` where `x` is itself an **import** re-exports the
3306                        // binding the import names, not a binding of this module
3307                        // (§16.2.1.6.3: a local export whose local name is imported resolves
3308                        // through the imported module). Recording it as a local made two
3309                        // modules that both forward one import look like two different
3310                        // bindings, and the name was reported ambiguous
3311                        // (`import-and-export-propagates-binding`;
3312                        // `namespace-unambiguous-if-import-star-as-and-export`).
3313                        let closure_names: Vec<String> = self
3314                            .cur()
3315                            .closure_vars
3316                            .iter()
3317                            .map(|var| var.name.clone())
3318                            .collect();
3319                        let forwarded = self
3320                            .module_meta()
3321                            .imports
3322                            .iter()
3323                            .filter(|entry| {
3324                                closure_names
3325                                    .get(entry.var_idx as usize)
3326                                    .is_some_and(|name| *name == local)
3327                            })
3328                            .map(|entry| (entry.module, entry.name.clone(), entry.is_star))
3329                            .find(|(_, name, is_star)| !is_star || name.is_empty());
3330                        if let Some((request, name, is_star)) = forwarded {
3331                            // A namespace import has no export *name* of its own; the
3332                            // resolution is `{ [[Module]]: m, [[BindingName]]: namespace }`,
3333                            // which is what the marker below records.
3334                            let import_name = if is_star {
3335                                "*namespace*".to_string()
3336                            } else {
3337                                name
3338                            };
3339                            self.module_meta().exports.push(ExportEntry::Indirect {
3340                                export_name,
3341                                module: request,
3342                                import_name,
3343                            });
3344                            continue;
3345                        }
3346                        let var_idx = self.module_binding_index(&local);
3347                        self.module_meta().exports.push(ExportEntry::Local {
3348                            export_name,
3349                            var_idx,
3350                        });
3351                    }
3352                }
3353            },
3354            ExportKind::All {
3355                source,
3356                exported,
3357                attributes,
3358            } => {
3359                let request = self.module_request(source, attributes);
3360                match exported {
3361                    Some(name) => {
3362                        self.module_meta().exports.push(ExportEntry::StarAs {
3363                            export_name: Self::module_name_text(name).to_string(),
3364                            module: request,
3365                        });
3366                    }
3367                    None => {
3368                        self.module_meta()
3369                            .exports
3370                            .push(ExportEntry::Star { module: request });
3371                    }
3372                }
3373            }
3374        }
3375        Ok(())
3376    }
3377
3378    /// The names a declaration binds, which is what `export <decl>` exports.
3379    fn declared_names(stmt: &Stmt, out: &mut Vec<String>) {
3380        match &stmt.kind {
3381            StmtKind::VarDecl(decl) => {
3382                for declarator in &decl.declarators {
3383                    let mut names = Vec::new();
3384                    declarator.target.bound_names(&mut names);
3385                    out.extend(names.into_iter().map(|name| name.name));
3386                }
3387            }
3388            StmtKind::FuncDecl(func) => {
3389                if let Some(name) = &func.name {
3390                    out.push(name.name.clone());
3391                }
3392            }
3393            StmtKind::ClassDecl(class) => {
3394                if let Some(name) = &class.name {
3395                    out.push(name.name.clone());
3396                }
3397            }
3398            _ => {}
3399        }
3400    }
3401
3402    /// The closure-variable index of a module binding, declaring it if the name was
3403    /// exported without being declared here.
3404    ///
3405    /// `export { x }` where `x` is not declared in the module is a link-time
3406    /// `SyntaxError`, not a compile-time one, so the slot still has to exist.
3407    fn module_binding_index(&mut self, name: &str) -> u32 {
3408        if let Some(index) = self.cur().closure_vars.iter().position(|c| c.name == name) {
3409            return index as u32;
3410        }
3411        self.declare_module_var(name, &VarDef::lexical(name.to_string()))
3412    }
3413
3414    fn exports_local(&mut self, export_name: &str, var_idx: u32) {
3415        self.module_meta().exports.push(ExportEntry::Local {
3416            export_name: export_name.to_string(),
3417            var_idx,
3418        });
3419    }
3420
3421    /// The hidden `*default*` binding `export default <expr>` stores into.
3422    fn declare_export_default(&mut self) -> u32 {
3423        const DEFAULT: &str = "*default*";
3424        if let Some(index) = self
3425            .cur()
3426            .closure_vars
3427            .iter()
3428            .position(|c| c.name == DEFAULT)
3429        {
3430            return index as u32;
3431        }
3432        self.declare_module_var(DEFAULT, &VarDef::lexical(DEFAULT.to_string()))
3433    }
3434
3435    /// The module tables, which only the top-level state has.
3436    fn module_meta(&mut self) -> &mut ModuleMeta {
3437        self.state()
3438            .module
3439            .as_mut()
3440            .expect("module tables are only touched while compiling a module")
3441    }
3442
3443    /// The index of `specifier`'s request, adding it if it is new.
3444    ///
3445    /// Deduplicated on the specifier *and* its attributes: the same file imported once as
3446    /// JSON and once as text is two modules with two different contents, which is exactly
3447    /// what `hello_module.js` does.
3448    fn module_request(&mut self, specifier: &str, attributes: &[ImportAttribute]) -> u32 {
3449        let attributes: Vec<(String, String)> = attributes
3450            .iter()
3451            .map(|attribute| (attribute.key.clone(), attribute.value.clone()))
3452            .collect();
3453        let meta = self.module_meta();
3454        if let Some(index) = meta
3455            .requests
3456            .iter()
3457            .position(|request| request.specifier == specifier && request.attributes == attributes)
3458        {
3459            return index as u32;
3460        }
3461        meta.requests.push(ModuleRequest {
3462            specifier: specifier.to_string(),
3463            attributes,
3464        });
3465        meta.requests.len() as u32 - 1
3466    }
3467
3468    /// Compile a loop body with a `break`/`continue` target pushed for it.
3469    fn loop_body(
3470        &mut self,
3471        body: &Stmt,
3472        labels: &[String],
3473        continue_label: Label,
3474        break_label: Label,
3475    ) -> Result<(), SyntaxError> {
3476        self.push_jump_target(JumpTarget {
3477            names: labels.to_vec(),
3478            break_label: Some(break_label),
3479            continue_label: Some(continue_label),
3480            // A loop leaves nothing of its own on the value stack.
3481            drop_count: 0,
3482            finally_label: None,
3483            is_regular_stmt: false,
3484            has_iterator: false,
3485            is_async_iterator: false,
3486        });
3487        let result = self.stmt(body);
3488        self.pop_jump_target();
3489        result
3490    }
3491
3492    fn push_jump_target(&mut self, target: JumpTarget) {
3493        self.state().jump_targets.push(target);
3494    }
3495
3496    fn pop_jump_target(&mut self) {
3497        self.state().jump_targets.pop();
3498    }
3499
3500    fn control_transfer(&mut self, stmt: &Stmt) -> Result<(), SyntaxError> {
3501        let (label, is_break) = match &stmt.kind {
3502            StmtKind::Break(label) => (label.as_ref(), true),
3503            StmtKind::Continue(label) => (label.as_ref(), false),
3504            _ => unreachable!("control_transfer is only called for break and continue"),
3505        };
3506
3507        // Walk outward from the innermost construct. Everything considered before
3508        // the match is a construct control is leaving, and leaving it has a cost:
3509        // its stack slots go, and its finalizer runs.
3510        let targets = self.cur().jump_targets.clone();
3511        for target in targets.iter().rev() {
3512            let destination = match (label, is_break) {
3513                // An unlabelled `break` skips a labelled non-loop statement: `break`
3514                // may name one, but the bare form only means "leave the loop".
3515                (None, true) => target.break_label.filter(|_| !target.is_regular_stmt),
3516                (None, false) => target.continue_label,
3517                (Some(name), true) => target
3518                    .break_label
3519                    .filter(|_| target.names.contains(&name.name)),
3520                (Some(name), false) => target
3521                    .continue_label
3522                    .filter(|_| target.names.contains(&name.name)),
3523            };
3524
3525            if let Some(destination) = destination {
3526                self.emit_jump(Opcode::Goto, destination, &[]);
3527                return Ok(());
3528            }
3529
3530            // Closing the iterator consumes the three slots the loop keeps on the
3531            // stack (iterator, next method, catch offset), so those are not dropped
3532            // again below.
3533            let mut remaining = target.drop_count;
3534            if target.has_iterator {
3535                self.emit_iterator_close(target.is_async_iterator, false);
3536                remaining = remaining.saturating_sub(3);
3537            }
3538            for _ in 0..remaining {
3539                self.emit(Opcode::Drop, &[]);
3540            }
3541            if let Some(finally) = target.finally_label {
3542                // The finalizer runs as a subroutine and is handed a dummy return
3543                // value, which is dropped afterwards to keep the stack the depth it
3544                // had before.
3545                self.emit(Opcode::Undefined, &[]);
3546                self.emit_jump(Opcode::Gosub, finally, &[]);
3547                self.emit(Opcode::Drop, &[]);
3548            }
3549        }
3550
3551        // The parser rejects a break/continue with no target, so reaching here
3552        // means the compiler's own bookkeeping is wrong.
3553        Err(SyntaxError::new(
3554            if is_break {
3555                "break has no enclosing loop or switch"
3556            } else {
3557                "continue has no enclosing loop"
3558            },
3559            stmt.span,
3560        ))
3561    }
3562
3563    /// Compile a labelled statement.
3564    ///
3565    /// `a: b: for(…)` is a chain of labels on one loop; every name has to reach
3566    /// that loop's targets, so the chain is collected and handed to the loop. A
3567    /// label on a non-loop statement only provides a `break` target, because
3568    /// `continue` may not target it.
3569    fn labeled(&mut self, label: &Ident, body: &Stmt, stmt: &Stmt) -> Result<(), SyntaxError> {
3570        let mut names = vec![label.name.clone()];
3571        let mut inner = body;
3572        while let StmtKind::Labeled {
3573            label: next,
3574            body: deeper,
3575        } = &inner.kind
3576        {
3577            names.push(next.name.clone());
3578            inner = deeper;
3579        }
3580        if Self::is_loop(inner) {
3581            return self.stmt_labelled(inner, &names);
3582        }
3583        let end = self.new_label();
3584        self.push_jump_target(JumpTarget {
3585            names,
3586            break_label: Some(end),
3587            continue_label: None,
3588            drop_count: 0,
3589            finally_label: None,
3590            is_regular_stmt: true,
3591            has_iterator: false,
3592            is_async_iterator: false,
3593        });
3594        let result = self.stmt(inner);
3595        self.pop_jump_target();
3596        result?;
3597        self.place_label(end);
3598        let _ = stmt;
3599        Ok(())
3600    }
3601
3602    /// Whether a statement is a loop, i.e. a valid target for `continue`.
3603    fn is_loop(stmt: &Stmt) -> bool {
3604        matches!(
3605            stmt.kind,
3606            StmtKind::While { .. }
3607                | StmtKind::DoWhile { .. }
3608                | StmtKind::For { .. }
3609                | StmtKind::ForIn { .. }
3610                | StmtKind::ForOf { .. }
3611        )
3612    }
3613
3614    /// Compile `switch`.
3615    ///
3616    /// The discriminant is evaluated once and stays on the value stack while the
3617    /// clauses compare against copies of it, so it is dropped at the end — which is
3618    /// why `switch (x) { }` still leaves `x` behind. Fallthrough is real: a
3619    /// clause's body jumps over the *next* clause's tests straight into its body.
3620    ///
3621    /// The tests form a chain: each `case` run compares and, on a miss, hands over to
3622    /// the next run's tests. Only the last run's miss reaches the `default` body, or
3623    /// the end of the switch when there is no `default`. That failure path can point
3624    /// backwards (`default` written first), so the runs and their labels are worked
3625    /// out before any code is emitted.
3626    fn switch(
3627        &mut self,
3628        discriminant: &Expr,
3629        cases: &[SwitchCase],
3630        stmt: &Stmt,
3631    ) -> Result<(), SyntaxError> {
3632        self.reset_value();
3633        // The discriminant is evaluated outside the switch's block scope, before
3634        // any `case` clause exists.
3635        self.expr(discriminant)?;
3636
3637        let switch_key = stmt.span.start.offset as u64;
3638        let switch_parent = self.cur().current_block;
3639        self.push_block(switch_key, switch_parent);
3640        self.emit_scope_enter(switch_key);
3641
3642        let break_label = self.new_label();
3643        self.push_jump_target(JumpTarget {
3644            names: Vec::new(),
3645            break_label: Some(break_label),
3646            // `switch` is a valid `break` target but not a `continue` target.
3647            continue_label: None,
3648            // The discriminant stays on the value stack for the whole statement, so
3649            // a `break` aimed further out has to discard it.
3650            drop_count: 1,
3651            finally_label: None,
3652            is_regular_stmt: false,
3653            has_iterator: false,
3654            is_async_iterator: false,
3655        });
3656
3657        // Runs of tests. `case 1: case 2: body` is one run: the empty clause hands
3658        // its label to the clause after it, so both tests reach the same body.
3659        let mut runs: Vec<(usize, usize)> = Vec::new();
3660        let mut scan = 0;
3661        while scan < cases.len() {
3662            if cases[scan].test.is_some() {
3663                let mut last = scan;
3664                while last + 1 < cases.len()
3665                    && cases[last].test.is_some()
3666                    && cases[last].body.is_empty()
3667                    && cases[last + 1].test.is_some()
3668                {
3669                    last += 1;
3670                }
3671                runs.push((scan, last));
3672                scan = last + 1;
3673            } else {
3674                scan += 1;
3675            }
3676        }
3677
3678        let body_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
3679        let run_labels: Vec<Label> = runs.iter().map(|_| self.new_label()).collect();
3680        let default_at = cases.iter().position(|case| case.test.is_none());
3681        // Where the last run sends control when nothing matched.
3682        let miss_target = match default_at {
3683            Some(index) => body_labels[index],
3684            None => break_label,
3685        };
3686
3687        // When `default` comes first, control has to jump over it to reach the
3688        // tests. It only needs to when some clause actually has a test; otherwise
3689        // the default body is the entry point.
3690        let mut entry = None;
3691        if default_at == Some(0) && !runs.is_empty() {
3692            self.emit_jump(Opcode::Goto, run_labels[0], &[]);
3693            entry = Some(run_labels[0]);
3694        }
3695
3696        let mut index = 0;
3697        let mut run = 0;
3698        let result = (|| -> Result<(), SyntaxError> {
3699            while index < cases.len() {
3700                if cases[index].test.is_some() {
3701                    let (first, last) = runs[run];
3702                    // Reaching these tests from the preceding body is a
3703                    // fallthrough, which continues inside the body and skips them.
3704                    if index > 0 {
3705                        self.emit_jump(Opcode::Goto, body_labels[index], &[]);
3706                    }
3707                    if let Some(label) = entry.take() {
3708                        self.place_label(label);
3709                    }
3710                    self.place_label(run_labels[run]);
3711
3712                    for (offset, case) in cases[first..=last].iter().enumerate() {
3713                        let test = case.test.as_ref().unwrap();
3714                        self.emit(Opcode::Dup, &[]);
3715                        self.expr(test)?;
3716                        self.emit(Opcode::StrictEq, &[]);
3717                        if first + offset < last {
3718                            self.emit_jump(Opcode::IfTrue, body_labels[index], &[]);
3719                        } else {
3720                            // Hand over to the next run's tests, or give up.
3721                            let next = match runs.get(run + 1) {
3722                                Some(_) => run_labels[run + 1],
3723                                None => miss_target,
3724                            };
3725                            self.emit_jump(Opcode::IfFalse, next, &[]);
3726                        }
3727                    }
3728
3729                    self.place_label(body_labels[index]);
3730                    for case in &cases[first..=last] {
3731                        self.stmts(&case.body)?;
3732                    }
3733                    index = last + 1;
3734                    run += 1;
3735                } else {
3736                    // `default`: control arrives here either by falling through or
3737                    // because every test missed.
3738                    self.place_label(body_labels[index]);
3739                    self.stmts(&cases[index].body)?;
3740                    index += 1;
3741                }
3742            }
3743            Ok(())
3744        })();
3745
3746        if result.is_ok() {
3747            self.place_label(break_label);
3748            // Discard the discriminant now that no test needs it.
3749            self.emit(Opcode::Drop, &[]);
3750        }
3751
3752        self.pop_jump_target();
3753        self.emit_scope_leave(switch_key);
3754        self.state().current_block = switch_parent;
3755        result
3756    }
3757
3758    /// Compile `try`/`catch`/`finally`.
3759    ///
3760    /// The shape is an exception table built out of `catch` instructions, each of
3761    /// which records where control goes if the instructions that follow raise:
3762    ///
3763    /// ```text
3764    /// catch HANDLER            <- if the guarded block throws, jump to HANDLER
3765    ///   <guarded block>
3766    ///   drop                   <- discard the catch offset
3767    ///   undefined; gosub FINALLY; drop
3768    ///   goto END
3769    /// HANDLER:
3770    ///   <bind the catch parameter>
3771    ///   catch CATCH2           <- if the handler itself throws, go to CATCH2
3772    ///   <handler body>
3773    ///   drop; undefined; gosub FINALLY; drop; goto END
3774    /// CATCH2:
3775    ///   gosub FINALLY; throw   <- run the finalizer, then let the error out
3776    /// FINALLY:
3777    ///   <finalizer>
3778    ///   ret                    <- return to the `gosub`
3779    /// END:
3780    /// ```
3781    ///
3782    /// `gosub` is a subroutine call and `ret` returns to it, which is how one copy
3783    /// of the finalizer serves the normal path, the handler path and the
3784    /// propagating-exception path.
3785    ///
3786    /// The `undefined` before each `gosub` is a dummy return value: the finalizer
3787    /// runs with `ret_value` on the stack, and the normal path has no value to
3788    /// keep, so it pushes one to keep the stack depth identical on every path.
3789    fn try_stmt(
3790        &mut self,
3791        stmt: &Stmt,
3792        block: &[Stmt],
3793        handler: &Option<CatchClause>,
3794        finalizer: Option<&[Stmt]>,
3795    ) -> Result<(), SyntaxError> {
3796        self.reset_value();
3797
3798        let catch_label = self.new_label();
3799        let catch2_label = self.new_label();
3800        let finally_label = self.new_label();
3801        let end_label = self.new_label();
3802
3803        self.emit_jump(Opcode::Catch, catch_label, &[]);
3804
3805        // The guarded block. `break` may not target it, so its entry exists purely
3806        // to unwind: a jump out has to discard the catch offset and run the
3807        // finalizer.
3808        self.push_jump_target(JumpTarget {
3809            names: Vec::new(),
3810            break_label: None,
3811            continue_label: None,
3812            drop_count: 1,
3813            finally_label: Some(finally_label),
3814            is_regular_stmt: false,
3815            has_iterator: false,
3816            is_async_iterator: false,
3817        });
3818
3819        let block_key = Self::try_block_key(stmt, TryPart::Block);
3820        let block_parent = self.cur().current_block;
3821        self.push_block(block_key, block_parent);
3822        self.emit_scope_enter(block_key);
3823        self.stmts(block)?;
3824        self.emit_scope_leave(block_key);
3825        self.state().current_block = block_parent;
3826        // A guarded block that ends in a `return`/`throw` never reaches the
3827        // epilogue, so the reference does not emit one.
3828        self.pop_jump_target();
3829        let block_live = !block.last().is_some_and(Self::terminates);
3830
3831        if block_live {
3832            self.emit(Opcode::Drop, &[]);
3833            self.emit(Opcode::Undefined, &[]);
3834            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3835            self.emit(Opcode::Drop, &[]);
3836            self.emit_jump(Opcode::Goto, end_label, &[]);
3837        }
3838
3839        if let Some(handler) = handler {
3840            self.place_label(catch_label);
3841            // The thrown value is on top of the stack: bind it, or discard it for
3842            // `catch { }`.
3843            match &handler.param {
3844                Some(pattern) => {
3845                    // The stores resolve the names, so they have to run inside the
3846                    // parameter's own scope; otherwise a same-named `catch` further out
3847                    // could win. A `catch` binding is never in the dead zone, so the store
3848                    // is the unchecked `put_loc` — the same one a plain `catch (e)` uses.
3849                    let param_key = Self::try_block_key(stmt, TryPart::Param);
3850                    let param_parent = self.cur().current_block;
3851                    self.push_block(param_key, param_parent);
3852                    self.destructure(pattern, Some(VarDeclKind::Var))?;
3853                    self.state().current_block = param_parent;
3854                }
3855                None => self.emit(Opcode::Drop, &[]),
3856            }
3857            self.emit_jump(Opcode::Catch, catch2_label, &[]);
3858
3859            self.push_jump_target(JumpTarget {
3860                names: Vec::new(),
3861                break_label: None,
3862                continue_label: None,
3863                drop_count: 1,
3864                finally_label: Some(finally_label),
3865                is_regular_stmt: false,
3866                has_iterator: false,
3867                is_async_iterator: false,
3868            });
3869            let catch_key = Self::try_block_key(stmt, TryPart::Catch);
3870            let catch_parent = self.cur().current_block;
3871            self.push_block(catch_key, catch_parent);
3872            self.emit_scope_enter(catch_key);
3873            self.stmts(&handler.body)?;
3874            self.emit_scope_leave(catch_key);
3875            self.state().current_block = catch_parent;
3876            self.pop_jump_target();
3877            let handler_live = !handler.body.last().is_some_and(Self::terminates);
3878
3879            if handler_live {
3880                self.emit(Opcode::Drop, &[]);
3881                self.emit(Opcode::Undefined, &[]);
3882                self.emit_jump(Opcode::Gosub, finally_label, &[]);
3883                self.emit(Opcode::Drop, &[]);
3884                self.emit_jump(Opcode::Goto, end_label, &[]);
3885            }
3886
3887            // An error raised inside the handler still has to run the finalizer.
3888            self.place_label(catch2_label);
3889            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3890            self.emit(Opcode::Throw, &[]);
3891        } else {
3892            // `try`/`finally` with no handler: the finalizer runs, then the error
3893            // keeps propagating.
3894            self.place_label(catch_label);
3895            self.emit_jump(Opcode::Gosub, finally_label, &[]);
3896            self.emit(Opcode::Throw, &[]);
3897        }
3898
3899        self.place_label(finally_label);
3900        // Inside the finalizer, leaving has a different cost: the return value and
3901        // the `gosub` return address are both on the stack, and neither finalizer nor
3902        // any outer one may run before the block has finished.
3903        self.push_jump_target(JumpTarget {
3904            names: Vec::new(),
3905            break_label: None,
3906            continue_label: None,
3907            drop_count: 2,
3908            finally_label: None,
3909            is_regular_stmt: false,
3910            has_iterator: false,
3911            is_async_iterator: false,
3912        });
3913        if let Some(finalizer) = finalizer {
3914            let finally_key = Self::try_block_key(stmt, TryPart::Finally);
3915            let finally_parent = self.cur().current_block;
3916            self.push_block(finally_key, finally_parent);
3917            self.emit_scope_enter(finally_key);
3918            self.stmts(finalizer)?;
3919            self.emit_scope_leave(finally_key);
3920            self.state().current_block = finally_parent;
3921        }
3922        self.pop_jump_target();
3923        self.emit(Opcode::Ret, &[]);
3924        self.place_label(end_label);
3925        Ok(())
3926    }
3927
3928    /// Compile `for`/`in` and `for`/`of`.
3929    ///
3930    /// Both keep an enumeration record on the value stack for the whole loop, which
3931    /// is what makes leaving early expensive: the record has to be dropped, or the
3932    /// iterator closed. The layout is
3933    ///
3934    /// ```text
3935    ///   <iterated expression>
3936    ///   for_in_start | for_of_start      <- pushes the record
3937    ///   goto TEST
3938    /// NEXT:
3939    ///   <bind the loop variable>
3940    ///   <body>
3941    /// TEST:
3942    ///   for_in_next | for_of_next 0
3943    ///   if_false NEXT                    <- not finished: next iteration
3944    ///   drop                             <- finished: discard the leftover value
3945    /// BREAK:
3946    ///   drop | iterator_close            <- the one cleanup `break` also uses
3947    /// ```
3948    ///
3949    /// `BREAK` sits *on* the cleanup rather than after it, so an early exit and the
3950    /// normal exit share one copy — which is why `break` inside the loop emits nothing
3951    /// of its own, and only a jump that passes *through* the loop pays for its record.
3952    fn for_in_of(
3953        &mut self,
3954        stmt: &Stmt,
3955        left: &ForHead,
3956        right: &Expr,
3957        body: &Stmt,
3958        kind: ForLoopKind,
3959        labels: &[String],
3960    ) -> Result<(), SyntaxError> {
3961        self.reset_value();
3962
3963        let loop_key = stmt.span.start.offset as u64;
3964        let loop_parent = self.cur().current_block;
3965        self.push_block(loop_key, loop_parent);
3966        self.emit_scope_enter(loop_key);
3967
3968        // The iterated expression is evaluated inside the loop's scope, after the
3969        // bindings exist in the temporal dead zone.
3970        self.expr(right)?;
3971
3972        let next = self.new_label();
3973        let test = self.new_label();
3974        let break_target = self.new_label();
3975
3976        let has_iterator = matches!(kind, ForLoopKind::Of | ForLoopKind::AwaitOf);
3977        match kind {
3978            ForLoopKind::In => self.emit(Opcode::ForInStart, &[]),
3979            ForLoopKind::Of => self.emit(Opcode::ForOfStart, &[]),
3980            ForLoopKind::AwaitOf => self.emit(Opcode::ForAwaitOfStart, &[]),
3981        }
3982        self.emit_jump(Opcode::Goto, test, &[]);
3983
3984        self.push_jump_target(JumpTarget {
3985            // `outer: for (x of xs) … break outer` needs the name here. Without it the
3986            // loop had no label to break to, and the compiler reported "break has no
3987            // enclosing loop" for a loop that was plainly enclosing it.
3988            names: labels.to_vec(),
3989            break_label: Some(break_target),
3990            continue_label: Some(test),
3991            // Passing through the loop has to dispose of its record. A `for`/`of`
3992            // record is three slots, and closing the iterator consumes all of them.
3993            drop_count: if has_iterator { 3 } else { 1 },
3994            finally_label: None,
3995            is_regular_stmt: false,
3996            has_iterator,
3997            is_async_iterator: matches!(kind, ForLoopKind::AwaitOf),
3998        });
3999
4000        self.place_label(next);
4001        self.bind_loop_variable(left)?;
4002
4003        // The reference marks the body with its own label here. Nothing jumps to it
4004        // once the loop is laid out, but it is not decoration: a label between the
4005        // store and the body is why `put_loc v; get_loc v` does *not* fold into
4006        // `set_loc v` when the body starts by reading the loop variable.
4007        let body_label = self.new_label();
4008        self.place_label(body_label);
4009        // `for (using x of …)` disposes once per iteration, so the body is a disposal
4010        // region rather than the whole loop: the resource is the element that this
4011        // iteration produced.
4012        let using_slot = match left {
4013            ForHead::VarDecl(decl) if decl.kind.is_using() => {
4014                decl.declarators
4015                    .first()
4016                    .and_then(|declarator| match &declarator.target.kind {
4017                        PatternKind::Ident(ident) => self.using_value_slot(&ident.name),
4018                        _ => None,
4019                    })
4020            }
4021            _ => None,
4022        };
4023        match using_slot {
4024            Some(slot) => {
4025                let live = !Self::terminates(body);
4026                self.using_region_around(slot, live, |compiler| compiler.stmt(body))?;
4027            }
4028            None => self.stmt(body)?,
4029        }
4030
4031        // §14.7.5.6 `ForIn/OfBodyEvaluation` step 6: a `let`/`const` head gets a **fresh
4032        // binding each iteration**, so a closure the body creates keeps that iteration's
4033        // value. `CloseCaptured` is the same instruction the C-style `for` uses: it swaps in
4034        // a new reference cell holding the current value.
4035        //
4036        // The position is the *end* of the body, not the start: closing before the body
4037        // would leave the closures pointing at the cell the next `put_loc` overwrites, and
4038        // `for (const x of [1,2,3]) fs.push(() => x)` answered `2,3,3` instead of `1,2,3`.
4039        for name in Self::loop_binding_names(left) {
4040            let pos = self.cur().cur_pos;
4041            self.state().insns.push(Insn::CloseCaptured {
4042                name,
4043                block: loop_key,
4044            });
4045            self.state().insn_pos.push(pos);
4046        }
4047        self.place_label(test);
4048        match kind {
4049            ForLoopKind::In => self.emit(Opcode::ForInNext, &[]),
4050            ForLoopKind::Of => self.emit(Opcode::ForOfNext, &[Op::Int(0)]),
4051            ForLoopKind::AwaitOf => {
4052                // The reference's shape: step, `await` the result, then unpack it.
4053                self.emit(Opcode::ForAwaitOfNext, &[Op::Int(0)]);
4054                self.emit(Opcode::Await, &[]);
4055                self.state().has_await = true;
4056                self.emit(Opcode::IteratorGetValueDone, &[]);
4057            }
4058        }
4059        self.emit_jump(Opcode::IfFalse, next, &[]);
4060        // The loop is finished; `for_xx_next` left an `undefined` behind.
4061        self.emit(Opcode::Drop, &[]);
4062
4063        self.pop_jump_target();
4064        self.place_label(break_target);
4065        if has_iterator {
4066            // A loop that ran to completion finds its iterator slot already cleared (see
4067            // `iterator_get_value_done`), so this closes only an iterator abandoned by a
4068            // `break` that jumped here.
4069            self.emit_iterator_close(matches!(kind, ForLoopKind::AwaitOf), false);
4070        } else {
4071            self.emit(Opcode::Drop, &[]);
4072        }
4073
4074        self.emit_scope_leave(loop_key);
4075        self.state().current_block = loop_parent;
4076        Ok(())
4077    }
4078
4079    /// The names a `for (let … of/in …)` head declares, which need a fresh cell per
4080    /// iteration. An assignment head (`for (x of …)`) declares nothing, so it is empty.
4081    fn loop_binding_names(left: &ForHead) -> Vec<String> {
4082        let ForHead::VarDecl(decl) = left else {
4083            return Vec::new();
4084        };
4085        if decl.kind == VarDeclKind::Var {
4086            return Vec::new();
4087        }
4088        let mut names = Vec::new();
4089        for declarator in &decl.declarators {
4090            let mut idents = Vec::new();
4091            declarator.target.bound_names(&mut idents);
4092            names.extend(idents.into_iter().map(|ident| ident.name));
4093        }
4094        names
4095    }
4096
4097    /// Store the value `for_xx_next` left on the stack into the loop variable.
4098    fn bind_loop_variable(&mut self, left: &ForHead) -> Result<(), SyntaxError> {
4099        // A declaration *initialises* the binding, which is what takes a `let` out of
4100        // the temporal dead zone, so the store is the unchecked form. Assigning to a
4101        // binding declared elsewhere is an ordinary write and keeps its check.
4102        let (pattern, action) = match left {
4103            ForHead::VarDecl(decl) => (&decl.declarators[0].target, VarAction::PutInit),
4104            ForHead::Assign(pattern) => (pattern.as_ref(), VarAction::Put),
4105        };
4106        match &pattern.kind {
4107            PatternKind::Ident(name) => {
4108                // `for (using x of …)` validates and snapshots each iteration's value
4109                // before the body runs, which is what makes a non-disposable element fail
4110                // on the iteration that produced it rather than at the end of the loop.
4111                if let ForHead::VarDecl(decl) = left
4112                    && decl.kind.is_using()
4113                {
4114                    let method_slot = self
4115                        .using_method_slot(&name.name)
4116                        .expect("a using binding was declared during hoisting");
4117                    self.emit(
4118                        Opcode::UsingCheck,
4119                        &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
4120                    );
4121                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
4122                }
4123                self.emit_var(action, &name.name);
4124                Ok(())
4125            }
4126            // Every other target stores through the same path an assignment pattern
4127            // uses, which is what makes `for (a[0] in obj)` write each key into the
4128            // property instead of refusing the loop outright.
4129            _ => self.destructure(
4130                pattern,
4131                match left {
4132                    ForHead::VarDecl(decl) => Some(decl.kind),
4133                    ForHead::Assign(_) => None,
4134                },
4135            ),
4136        }
4137    }
4138
4139    fn var_decl(&mut self, decl: &VarDecl) -> Result<(), SyntaxError> {
4140        for declarator in &decl.declarators {
4141            let Some(init) = &declarator.init else {
4142                // `var x;` stays `undefined`. A lexical binding is different: it
4143                // has to be *initialised* to leave the temporal dead zone, so the
4144                // compiler supplies an explicit `undefined`.
4145                if decl.kind.is_lexical() {
4146                    // A lexical binding has to be *initialised* to leave the temporal
4147                    // dead zone, and a destructuring one is no different — `let {a}`
4148                    // with no initialiser is a syntax error, but `let [a] = []` still
4149                    // needs `a` to be initialised from an empty source, which the
4150                    // pattern does on its own.
4151                    self.emit(Opcode::Undefined, &[]);
4152                    self.destructure(&declarator.target, Some(decl.kind))?;
4153                }
4154                continue;
4155            };
4156            match &declarator.target.kind {
4157                PatternKind::Ident(name) => {
4158                    self.expr(init)?;
4159                    self.set_name_if_anonymous(init, &Wtf8::new(&name.name));
4160                    if decl.kind.is_using() {
4161                        // `using_check` validates the value and snapshots its dispose
4162                        // method: `value -> value, method`. The snapshot is what makes a
4163                        // later change to `Symbol.dispose` irrelevant, and validating here
4164                        // is what keeps the body from running at all when the value is not
4165                        // disposable.
4166                        let method_slot = self
4167                            .using_method_slot(&name.name)
4168                            .expect("a using binding was declared during hoisting");
4169                        self.emit(
4170                            Opcode::UsingCheck,
4171                            &[Op::Int(if decl.kind.is_await_using() { 1 } else { 0 })],
4172                        );
4173                        self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(method_slot))]);
4174                        self.emit_var(VarAction::PutInit, &name.name);
4175                        continue;
4176                    }
4177                    // A declaration statement produces no value, so nothing is
4178                    // duplicated onto the stack.
4179                    match decl.kind {
4180                        VarDeclKind::Var => self.emit_var(VarAction::Put, &name.name),
4181                        _ => self.emit_var(VarAction::PutInit, &name.name),
4182                    }
4183                }
4184                _ => {
4185                    // A destructuring declaration keeps nothing on the stack: the
4186                    // pattern consumes the initialiser.
4187                    self.expr(init)?;
4188                    self.destructure(&declarator.target, Some(decl.kind))?;
4189                }
4190            }
4191        }
4192        Ok(())
4193    }
4194
4195    /// Bind a destructuring pattern from the value on top of the stack.
4196    ///
4197    /// `decl` picks the mode. `Some(kind)` is a *declaration*: every target is an
4198    /// identifier and the store is a binding write, `put_*` for `var` and `put_*_init`
4199    /// for `let`/`const` so the binding leaves its dead zone. `None` is a destructuring
4200    /// *assignment*, where a member expression is a legal target and the store is an
4201    /// ordinary property write.
4202    ///
4203    /// The value is consumed. An assignment expression's own result is the right-hand
4204    /// side, which the caller keeps separately — the spec does not make the pattern's
4205    /// last store produce it.
4206    fn destructure(
4207        &mut self,
4208        pattern: &Pattern,
4209        decl: Option<VarDeclKind>,
4210    ) -> Result<(), SyntaxError> {
4211        match &pattern.kind {
4212            PatternKind::Ident(name) => {
4213                match decl {
4214                    Some(VarDeclKind::Var) | None => {
4215                        self.emit_var(VarAction::Put, &name.name);
4216                    }
4217                    Some(_) => self.emit_var(VarAction::PutInit, &name.name),
4218                }
4219                Ok(())
4220            }
4221            PatternKind::Assign { target, default } => {
4222                // A default only applies to `undefined`, not to `null`: `[a = 1] = [null]`
4223                // keeps `null`.
4224                //
4225                // The shape is the reference's: test for `undefined`, and when the value is
4226                // present fall **through** to a single store both paths share. The
4227                // alternatives — branching to the store on each side — need a second store
4228                // and a jump between them, which is what the dump used to show.
4229                let has_value = self.new_label();
4230                self.emit(Opcode::Dup, &[]);
4231                self.emit(Opcode::IsUndefined, &[]);
4232                self.emit_jump(Opcode::IfFalse, has_value, &[]);
4233                self.emit(Opcode::Drop, &[]);
4234                self.expr(default)?;
4235                // `var {f = function(){}} = {}` names the function `f`, like a plain
4236                // `var f = function(){}` does. Both pattern forms do it:
4237                // `BindingInitialization` names the value for a *binding* target, and since
4238                // ES2018 `DestructuringAssignmentEvaluation` does the same, so
4239                // `[f = () => {}] = []` also leaves `f.name === "f"`. A member target has
4240                // no name to give, which is why only an identifier qualifies.
4241                if let PatternKind::Ident(name) = &target.kind {
4242                    self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
4243                }
4244                self.place_label(has_value);
4245                self.destructure(target, decl)
4246            }
4247            PatternKind::Array { elements, rest } => self.destructure_array(elements, rest, decl),
4248            PatternKind::Object { properties, rest } => {
4249                self.destructure_object(properties, rest, decl, pattern)
4250            }
4251            PatternKind::Member(member) if decl.is_none() => {
4252                // An assignment pattern may store into a property. The value is on the
4253                // stack, so the receiver and the key go above it and `rot3l`/`swap2`
4254                // put the three in the order `put_array_el`/`put_field` expect.
4255                self.expr(&member.object)?;
4256                match &member.property {
4257                    MemberProp::Ident(name) => {
4258                        // `value obj` -> `obj value`, the order `put_field` takes.
4259                        // Nothing needs to be left behind: a pattern element's value is
4260                        // consumed by its own store.
4261                        self.emit(Opcode::Swap, &[]);
4262                        self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4263                    }
4264                    MemberProp::Computed(index) => {
4265                        self.expr(index)?;
4266                        // `value obj key` -> `obj key value`.
4267                        self.emit(Opcode::Rot3l, &[]);
4268                        self.emit(Opcode::PutArrayEl, &[]);
4269                    }
4270                    MemberProp::Private(name) => {
4271                        // `value obj` -> `obj value`, and the store half of the assignment is
4272                        // the same one `obj.#x = value` uses — only without `insert2`,
4273                        // because a pattern element's value is not wanted back.
4274                        let binding = format!("#{}", name.name);
4275                        let (kind, setter) = self.private_use(&binding, member.span)?;
4276                        self.emit(Opcode::Swap, &[]);
4277                        self.private_store(&binding, kind, setter.as_deref())?;
4278                    }
4279                }
4280                Ok(())
4281            }
4282            PatternKind::Rest(inner) => self.destructure(inner, decl),
4283            PatternKind::Invalid(expr) => {
4284                Err(SyntaxError::new("invalid assignment target", expr.span))
4285            }
4286            _ => Err(SyntaxError::new(
4287                "this destructuring target is not supported by the compiler yet",
4288                pattern.span,
4289            )),
4290        }
4291    }
4292
4293    /// `[…]` on the left: drain an iterator, binding one target per element.
4294    ///
4295    /// A target that stores into a **property** — `[o.p] = it` — has its reference worked
4296    /// out *before* the value is pulled. That ordering is observable twice over
4297    /// (`array-elem-iter-thrw-close`):
4298    ///
4299    /// * `next` must not have been called yet when the reference throws, so
4300    ///   `[ {}[thrower()] ] = iterable` reports `nextCount === 0`;
4301    /// * the iterator must still be closed, because the throw happens while the record is
4302    ///   live — which is `catch_here`'s `catch_offset 0` doing its work.
4303    ///
4304    /// Doing it the other way round — pull the value, then evaluate the reference — got
4305    /// both wrong: an extra `next` call, and, when the reference threw, an iterator that had
4306    /// already been drained past.
4307    fn destructure_array(
4308        &mut self,
4309        elements: &[Option<PatternElement>],
4310        rest: &Option<Box<RestElement>>,
4311        decl: Option<VarDeclKind>,
4312    ) -> Result<(), SyntaxError> {
4313        // The iterator protocol is the same one `for (… of …)` uses, so a destructuring
4314        // pattern accepts any iterable and closes the iterator when the pattern ends
4315        // early. `for_of_next` pushes the value and a `done` flag; the flag comes off
4316        // first because it is on top.
4317        //
4318        // It also counts as an open iterator for `return` and `break`: a pattern is not a
4319        // loop, but the record is live across everything the pattern evaluates, so
4320        // `function* g(){ [ {} = yield ] = it }` resumed with `return()` has to close it
4321        // (`array-elem-iter-rtrn-close`). `emit_unwind_for_return` finds it by this entry
4322        // and `nip_catch` uncovers exactly the `iter next` pairs it left behind.
4323        //
4324        // A `break`/`continue` cannot occur inside a pattern, so `names` and both labels
4325        // are empty and `drop_count` — read only by that unreachable path — keeps the
4326        // reference's 2.
4327        self.push_jump_target(JumpTarget {
4328            names: Vec::new(),
4329            break_label: None,
4330            continue_label: None,
4331            drop_count: 2,
4332            finally_label: None,
4333            is_regular_stmt: false,
4334            has_iterator: true,
4335            is_async_iterator: false,
4336        });
4337        self.emit(Opcode::ForOfStart, &[]);
4338        for element in elements {
4339            match element {
4340                Some(PatternElement::Pattern(pattern)) => {
4341                    match Self::member_element_target(pattern, decl) {
4342                        // A prepared reference sits above the record, so `for_of_next` is
4343                        // told how many values are in the way.
4344                        Some(member) => {
4345                            let extra = self.prepare_member_target(member)?;
4346                            self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4347                            self.emit(Opcode::Drop, &[]);
4348                            self.destructure_prepared(pattern, member)?;
4349                        }
4350                        None => {
4351                            self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4352                            self.emit(Opcode::Drop, &[]);
4353                            self.destructure(pattern, decl)?;
4354                        }
4355                    }
4356                }
4357                Some(PatternElement::Property { span, .. }) => {
4358                    return Err(SyntaxError::new(
4359                        "a property pattern is not a valid array element",
4360                        *span,
4361                    ));
4362                }
4363                // An elision skips the value, which is already on the stack.
4364                None => {
4365                    self.emit(Opcode::ForOfNext, &[Op::Int(0)]);
4366                    self.emit(Opcode::Drop, &[]);
4367                    self.emit(Opcode::Drop, &[]);
4368                }
4369            }
4370        }
4371        if let Some(rest) = rest {
4372            // The remaining values go into a fresh array. The target and its running
4373            // index stay on the stack above the iterator, which is what the operand of
4374            // `for_of_next` accounts for: two values sit above the iterator triple.
4375            let prepared = match decl {
4376                None => Self::member_rest_target(rest),
4377                // A binding pattern cannot store into a property.
4378                Some(_) => None,
4379            };
4380            let extra = match prepared {
4381                Some(member) => 2 + self.prepare_member_target(member)?,
4382                None => 2,
4383            };
4384            self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4385            self.emit(Opcode::Push0, &[]);
4386            let top = self.new_label();
4387            self.place_label(top);
4388            self.emit(Opcode::ForOfNext, &[Op::Int(extra)]);
4389            let done = self.new_label();
4390            self.emit_jump(Opcode::IfTrue, done, &[]);
4391            self.emit(Opcode::DefineArrayEl, &[]);
4392            self.emit(Opcode::Inc, &[]);
4393            self.emit_jump(Opcode::Goto, top, &[]);
4394            self.place_label(done);
4395            self.emit(Opcode::Drop, &[]);
4396            self.emit(Opcode::Drop, &[]);
4397            match prepared {
4398                Some(member) => self.store_member_value(member)?,
4399                None => self.destructure_rest(rest, decl)?,
4400            }
4401        }
4402        self.emit(Opcode::IteratorClose, &[]);
4403        self.pop_jump_target();
4404        Ok(())
4405    }
4406
4407    /// The property an array element stores into, when it stores into one at all.
4408    ///
4409    /// `Assign` is peeled because `[o.p = d] = it` evaluates `o.p`'s reference at the same
4410    /// point `[o.p] = it` does; the default value is applied afterwards, on the pulled
4411    /// value. Nothing deeper is: a nested pattern's own targets are reached by recursing
4412    /// into `destructure`, and those never straddle a `for_of_next`.
4413    fn member_element_target(
4414        pattern: &Pattern,
4415        decl: Option<VarDeclKind>,
4416    ) -> Option<&ast::MemberPattern> {
4417        if decl.is_some() {
4418            return None;
4419        }
4420        match &pattern.kind {
4421            PatternKind::Member(member) => Some(member),
4422            PatternKind::Assign { target, .. } => Self::member_element_target(target, decl),
4423            _ => None,
4424        }
4425    }
4426
4427    /// The same, for a rest element.
4428    fn member_rest_target(rest: &RestElement) -> Option<&ast::MemberPattern> {
4429        match rest {
4430            RestElement::Member(member) => Some(member),
4431            RestElement::Pattern(pattern) => match &pattern.kind {
4432                PatternKind::Member(member) => Some(member),
4433                _ => None,
4434            },
4435        }
4436    }
4437
4438    /// Push a member target's reference — the object, and the key when the property is
4439    /// computed — and answer how many values that put above the iterator record.
4440    fn prepare_member_target(&mut self, member: &ast::MemberPattern) -> Result<i32, SyntaxError> {
4441        self.expr(&member.object)?;
4442        match &member.property {
4443            MemberProp::Ident(_) | MemberProp::Private(_) => Ok(1),
4444            MemberProp::Computed(index) => {
4445                self.expr(index)?;
4446                Ok(2)
4447            }
4448        }
4449    }
4450
4451    /// Store the value on top of the stack through a prepared member reference.
4452    ///
4453    /// `obj value` for a named property, `obj key value` for a computed one — the orders
4454    /// `put_field` and `put_array_el` take, so no reordering is needed here. The `swap` and
4455    /// `rot3l` in [`Compiler::destructure`]'s member case exist only because *it* starts
4456    /// with the value already on the stack.
4457    fn store_member_value(&mut self, member: &ast::MemberPattern) -> Result<(), SyntaxError> {
4458        match &member.property {
4459            MemberProp::Ident(name) => {
4460                self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
4461            }
4462            MemberProp::Computed(_) => self.emit(Opcode::PutArrayEl, &[]),
4463            MemberProp::Private(name) => {
4464                let binding = format!("#{}", name.name);
4465                let (kind, setter) = self.private_use(&binding, member.span)?;
4466                self.private_store(&binding, kind, setter.as_deref())?;
4467            }
4468        }
4469        Ok(())
4470    }
4471
4472    /// The value of an array element whose member reference is already prepared.
4473    ///
4474    /// Only the default-value test differs from [`Compiler::destructure`]: the reference
4475    /// and the value are both on the stack while the test runs, which is why the object is
4476    /// evaluated before the default rather than after it.
4477    fn destructure_prepared(
4478        &mut self,
4479        pattern: &Pattern,
4480        member: &ast::MemberPattern,
4481    ) -> Result<(), SyntaxError> {
4482        if let PatternKind::Assign { default, .. } = &pattern.kind {
4483            let has_value = self.new_label();
4484            self.emit(Opcode::Dup, &[]);
4485            self.emit(Opcode::IsUndefined, &[]);
4486            self.emit_jump(Opcode::IfFalse, has_value, &[]);
4487            self.emit(Opcode::Drop, &[]);
4488            self.expr(default)?;
4489            self.place_label(has_value);
4490        }
4491        self.store_member_value(member)
4492    }
4493
4494    /// `{…}` on the left: read properties off one boxed source object.
4495    fn destructure_object(
4496        &mut self,
4497        properties: &[Option<PatternElement>],
4498        rest: &Option<Box<RestElement>>,
4499        decl: Option<VarDeclKind>,
4500        pattern: &Pattern,
4501    ) -> Result<(), SyntaxError> {
4502        // `ToObject` is what refuses `null`/`undefined`, and it also puts the source
4503        // aside for the rest element below.
4504        self.emit(Opcode::ToObject, &[]);
4505        let mut taken: Vec<Wtf8> = Vec::new();
4506        // A computed key's *value* is only known at run time, so with a rest element the
4507        // exclusion list cannot be an `ArrayFrom` over literal atoms. It becomes a hidden
4508        // local array that every key is written into as the pattern is walked — literal
4509        // keys by name, computed ones by the value the expression produced. Without this,
4510        // `let { [k]: a, ...rest } = o` was refused outright.
4511        let needs_key_log = rest.is_some() && computed_key_count(properties) > 0;
4512        let key_log = if needs_key_log {
4513            let name = "<rest_exclude>";
4514            self.declare_hidden_local(name, VarKind::Normal);
4515            self.emit(Opcode::ArrayFrom, &[Op::Int(0)]);
4516            self.emit_var(VarAction::Put, name);
4517            Some(name)
4518        } else {
4519            None
4520        };
4521        for property in properties {
4522            let Some(PatternElement::Property {
4523                key, value, span, ..
4524            }) = property
4525            else {
4526                return Err(SyntaxError::new(
4527                    "a bare pattern is not a valid object property",
4528                    properties
4529                        .iter()
4530                        .flatten()
4531                        .map(|element| match element {
4532                            PatternElement::Pattern(pattern) => pattern.span,
4533                            PatternElement::Property { span, .. } => *span,
4534                        })
4535                        .next()
4536                        .unwrap_or(pattern.span),
4537                ));
4538            };
4539            // Every read needs the source twice: to read from, and to keep for the next
4540            // property. `get_field2` is that duplicate-and-read in one instruction, but it
4541            // leaves the copy *under* the value, so it is only usable when whatever
4542            // consumes the value tolerates that. See [`reads_with_get_field2`].
4543            let nested = reads_with_get_field2(decl, value);
4544            if !nested {
4545                self.emit(Opcode::Dup, &[]);
4546            }
4547            let slot = taken.len();
4548            match key {
4549                PropName::Literal(literal) => {
4550                    let name = self.property_key_text(literal, *span)?;
4551                    taken.push(name.clone());
4552                    if let Some(log) = &key_log {
4553                        // `arr index key -> arr`: the key is written into the log before
4554                        // the read, so the order of observable operations is unchanged.
4555                        self.emit_var(VarAction::Get, log);
4556                        self.push_number(slot as f64);
4557                        self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&name))]);
4558                        self.emit(Opcode::PutArrayEl, &[]);
4559                    }
4560                    self.emit(
4561                        if nested {
4562                            Opcode::GetField2
4563                        } else {
4564                            Opcode::GetField
4565                        },
4566                        &[Op::Atom(Atom::from_wtf8(&name))],
4567                    );
4568                }
4569                PropName::Computed(index) => {
4570                    self.expr(index)?;
4571                    // `key key`: one stays on the stack for the read, the other goes into
4572                    // the exclusion log. The index is a compile-time constant, so no counter
4573                    // local is needed.
4574                    if let Some(log) = &key_log {
4575                        taken.push(Wtf8::default());
4576                        self.emit(Opcode::Dup, &[]);
4577                        self.emit_var(VarAction::Get, log);
4578                        self.emit(Opcode::Swap, &[]);
4579                        self.push_number(slot as f64);
4580                        self.emit(Opcode::Swap, &[]);
4581                        self.emit(Opcode::PutArrayEl, &[]);
4582                    }
4583                    self.emit(Opcode::GetArrayEl, &[]);
4584                }
4585                PropName::Private(_) => {
4586                    return Err(SyntaxError::new(
4587                        "private fields are not supported by the compiler yet",
4588                        value.span,
4589                    ));
4590                }
4591            }
4592            self.destructure(value, decl)?;
4593        }
4594        match rest {
4595            Some(rest) => {
4596                // `target src exclude`: the exclusion list is an array of the keys the
4597                // literal part already took, so the rest object gets only the others.
4598                self.emit(Opcode::Object, &[]);
4599                self.emit(Opcode::Swap, &[]);
4600                match &key_log {
4601                    // Built while walking the pattern; see `needs_key_log`.
4602                    Some(log) => {
4603                        self.emit_var(VarAction::Get, log);
4604                    }
4605                    None => {
4606                        for name in &taken {
4607                            self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(name))]);
4608                        }
4609                        self.emit(Opcode::ArrayFrom, &[Op::Int(taken.len() as i32)]);
4610                    }
4611                }
4612                self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
4613                self.emit(Opcode::Drop, &[]);
4614                self.emit(Opcode::Drop, &[]);
4615                self.destructure_rest(rest, decl)?;
4616            }
4617            // The source was only kept for a rest element.
4618            None => self.emit(Opcode::Drop, &[]),
4619        }
4620        Ok(())
4621    }
4622
4623    /// The pattern a rest element binds, as a target [`Self::destructure`] takes.
4624    fn destructure_rest(
4625        &mut self,
4626        rest: &RestElement,
4627        decl: Option<VarDeclKind>,
4628    ) -> Result<(), SyntaxError> {
4629        match rest {
4630            RestElement::Pattern(pattern) => self.destructure(pattern, decl),
4631            // `[...a.b] = c` stores into a property.
4632            RestElement::Member(member) => {
4633                let pattern = Pattern {
4634                    kind: PatternKind::Member(member.clone()),
4635                    span: member.span,
4636                };
4637                self.destructure(&pattern, decl)
4638            }
4639        }
4640    }
4641
4642    /// Compile a function declaration and queue it for instantiation at scope
4643    /// entry.
4644    ///
4645    /// A declaration is visible before the statement that declares it, so the
4646    /// code that creates the function object belongs at the top of the enclosing
4647    /// scope, not at the declaration.
4648    fn func_decl(&mut self, func: &ast::Function) -> Result<(), SyntaxError> {
4649        let name = func.name.as_ref().expect("a declaration has a name");
4650        let function = self.compile_function(func)?;
4651        let pool_index = self.push_constant(Constant::Function(Box::new(function)));
4652        let target = self.hoist_target(&name.name);
4653        let block = self.cur().current_block;
4654        self.state().hoisted.push((block, target, pool_index));
4655        Ok(())
4656    }
4657
4658    /// Where a name lives, for a hoisted declaration.
4659    fn hoist_target(&self, name: &str) -> HoistTarget {
4660        let state = self.cur();
4661        if let Some(index) = state.args.iter().position(|a| a.name == name) {
4662            return HoistTarget::Arg(index as u32);
4663        }
4664        if let Some(index) = state.vars.iter().position(|v| v.name == name) {
4665            return HoistTarget::Loc(index as u32);
4666        }
4667        // A global function declaration is not a slot at all.
4668        HoistTarget::Global(name.to_string())
4669    }
4670
4671    // -- expressions -------------------------------------------------------
4672
4673    /// Compile one expression, recording where its instructions sit.
4674    ///
4675    /// The position is the node's operator when it has one and its first token
4676    /// otherwise, and it is restored on the way out so a parent's own instructions —
4677    /// which are emitted *after* its children — are blamed on the parent. Without the
4678    /// restore the `add` in `a + b` would inherit `b`'s position instead of the `+`.
4679    fn expr(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4680        // `discard_value` belongs to the *statement* that is about to be compiled, so it
4681        // may only be honoured by that statement's own top-level expression. Taking it here
4682        // is what enforces that: `f(x = 1)` sets it for the call, and the assignment inside
4683        // the argument list is a different expression — it must still leave its value on the
4684        // stack. Without this the argument vanished, and `call` then consumed the callee as
4685        // its argument (`TypeError: undefined is not a function` from `f(x = 1)` inside any
4686        // function).
4687        self.discard_root = std::mem::take(&mut self.state().discard_value);
4688        let saved = self.cur().cur_pos;
4689        // Only the node kinds the reference calls `emit_source_pos` for record a position:
4690        // the operator a node exists for, and a variable *read*, which the reference
4691        // positions at the identifier itself (`case TOK_IDENT: … do_get_var:
4692        // emit_source_pos(s, source_ptr)`). Everything else — a literal, an object or array
4693        // start, a parenthesised group, an anonymous function expression — leaves the
4694        // previous position in place, because a table entry the reference never writes is
4695        // one we must not write either: the instruction that inherits a position (the
4696        // `using` epilogue, a template's `to_propkey`, a `super()` call) would otherwise
4697        // report a more recent token than the reference does.
4698        let pos = expr.op_pos.or(match &expr.kind {
4699            ExprKind::Ident(ident) => Some(ident.span.start),
4700            _ => None,
4701        });
4702        match pos {
4703            Some(pos) => self.state().cur_pos = Some(pos),
4704            // A node the reference records nothing for: its own instructions stay
4705            // unpositioned, so they inherit whatever was written last — which is what an
4706            // `emit_source_pos`-less stretch of the reference's bytecode does. Keeping the
4707            // enclosing position instead would blame them on a token the reference has not
4708            // reached yet: a spread's `iterator_open` reports the expression it follows, and
4709            // a template's `to_propkey` the interpolation.
4710            None => self.state().cur_pos = None,
4711        }
4712        // Note a direct `eval` call before compiling it, because the *whole* function
4713        // is affected: an eval can name any binding the function declares, so every one
4714        // of them has to live in a cell for a closure it creates to capture it.
4715        self.note_direct_eval(expr);
4716        let result = self.expr_inner(expr);
4717        self.discard_root = false;
4718        self.state().cur_pos = saved;
4719        result
4720    }
4721
4722    /// Record which bindings are in scope at a direct `eval` call.
4723    ///
4724    /// Ordinary name lookup happens at compile time; a direct `eval` bypasses that and
4725    /// resolves names from a string at run time, so the only chance to pin down *which*
4726    /// slot a name means is here. Visibility is the lexical rule: a binding counts when
4727    /// its block is the current block, an enclosing one, or the function scope.
4728    fn materialize_eval_sites(&mut self) {
4729        let pending = std::mem::take(&mut self.state().pending_eval_sites);
4730        for (span, site_block, in_params, private, arguments_allowed) in pending {
4731            self.resolve_eval_site(span, site_block, in_params, private, arguments_allowed);
4732        }
4733    }
4734
4735    /// Resolve the bindings visible at one `eval` call.
4736    fn resolve_eval_site(
4737        &mut self,
4738        span: Span,
4739        site_block: u64,
4740        site_in_params: bool,
4741        private_names: Vec<EvalPrivate>,
4742        arguments_allowed: bool,
4743    ) {
4744        /// How near a binding is: function distance first, then block depth, then the
4745        /// later declaration (which shadows the earlier one in the same block).
4746        type ScopePriority = (usize, usize, std::cmp::Reverse<u32>);
4747
4748        // `(sort key, binding)`, where a smaller key wins. The whole scope chain is
4749        // walked, innermost function first: a direct `eval` sees every enclosing
4750        // function's bindings, and none of them can be resolved at run time because the
4751        // runtime only has names to go on.
4752        let mut bindings: Vec<(ScopePriority, EvalVisible)> = Vec::new();
4753        let deepest = self.stack.len() - 1;
4754        for (level, state) in self.stack.iter().enumerate().rev() {
4755            let owner = (deepest - level) as u32;
4756            // The innermost function's block is the one the call sat in, which is not
4757            // the block the compiler is in now; the enclosing functions are still at
4758            // the point where this one was created.
4759            let here = if level == deepest {
4760                site_block
4761            } else {
4762                state.current_block
4763            };
4764            // The chain of live blocks, innermost first, with a depth for each. The walk
4765            // stops at `NO_PARENT`, which is a sentinel rather than `0` because a real
4766            // block can start at source offset zero.
4767            let mut live: Vec<(u64, usize)> = vec![(here, 0)];
4768            let mut block = here;
4769            while let Some(parent) = state
4770                .blocks
4771                .iter()
4772                .find(|candidate| candidate.key == block)
4773                .map(|candidate| candidate.parent)
4774                .filter(|parent| *parent != NO_PARENT)
4775                .filter(|parent| parent != &block)
4776            {
4777                live.push((parent, live.len()));
4778                block = parent;
4779            }
4780            let depth_of = |key: u64| {
4781                live.iter()
4782                    .find(|(candidate, _)| *candidate == key)
4783                    .map(|(_, depth)| *depth)
4784                    // The function scope is the outermost depth there is. A binding of a
4785                    // block this site is not inside lands here too, which pushes it
4786                    // behind every live one — the right answer: it is out of scope.
4787                    .unwrap_or(live.len())
4788            };
4789            for (index, arg) in state.args.iter().enumerate() {
4790                bindings.push((
4791                    (owner as usize, live.len(), std::cmp::Reverse(index as u32)),
4792                    EvalVisible {
4793                        name: arg.name.clone(),
4794                        is_arg: true,
4795                        index: index as u32,
4796                        owner,
4797                    },
4798                ));
4799            }
4800            // A parameter list cannot see the body, so a body `var` is not a binding the
4801            // eval can name: `(a = eval("var c = 1"), p = () => c) => { var c = 2 }` must
4802            // not let that eval write the body's `c`.
4803            let hides_body = if level == deepest {
4804                site_in_params
4805            } else {
4806                state.created_in_params
4807            };
4808            for (index, var) in state.vars.iter().enumerate() {
4809                let block = state
4810                    .var_block
4811                    .get(index)
4812                    .copied()
4813                    .unwrap_or(FUNCTION_SCOPE);
4814                if hides_body && block == FUNCTION_SCOPE && !visible_in_params(var) {
4815                    continue;
4816                }
4817                bindings.push((
4818                    (
4819                        owner as usize,
4820                        depth_of(block),
4821                        std::cmp::Reverse(index as u32),
4822                    ),
4823                    EvalVisible {
4824                        name: var.name.clone(),
4825                        is_arg: false,
4826                        index: index as u32,
4827                        owner,
4828                    },
4829                ));
4830            }
4831        }
4832        // Innermost function first, then innermost block, then the later declaration
4833        // (which shadows the earlier one within a block).
4834        bindings.sort_by_key(|(priority, _)| *priority);
4835        let bindings = bindings.into_iter().map(|(_, visible)| visible).collect();
4836        self.state().eval_sites.push(EvalSite {
4837            line: span.start.line,
4838            column: span.start.column,
4839            bindings,
4840            private_names,
4841            arguments_allowed,
4842        });
4843    }
4844
4845    /// The private names visible from the compiler's current position, innermost last.
4846    ///
4847    /// A direct `eval` inherits these because private names are lexically scoped
4848    /// (§15.10.2). Flattened with the **first** occurrence winning as the scopes are walked
4849    /// outermost-first, so a nested class's `#x` shadows an outer class's — the same
4850    /// shadowing `ClassPlan::find` gives a use site inside the body.
4851    fn visible_private_names(&self) -> Vec<EvalPrivate> {
4852        let mut out: Vec<EvalPrivate> = Vec::new();
4853        for scope in &self.private_scopes {
4854            for (name, use_) in scope {
4855                if out.iter().any(|entry| &entry.name == name) {
4856                    continue;
4857                }
4858                out.push(EvalPrivate {
4859                    name: name.clone(),
4860                    kind: match use_.kind {
4861                        PrivateKind::Field => EvalPrivateKind::Field,
4862                        PrivateKind::Method => EvalPrivateKind::Method,
4863                        PrivateKind::Getter => EvalPrivateKind::Getter,
4864                        PrivateKind::Setter => EvalPrivateKind::Setter,
4865                    },
4866                    setter: use_.setter.clone(),
4867                });
4868            }
4869        }
4870        out
4871    }
4872
4873    /// Whether `expr` is `eval(...)` — the direct form, which sees the caller's scope.
4874    ///
4875    /// `(0, eval)(…)` and `f.call(null, …)` are *indirect* and get no caller scope; only
4876    /// a bare identifier callee counts.
4877    /// Record everything a direct `eval` call site has to tell the runtime.
4878    ///
4879    /// Called from both places a call can be compiled: [`Compiler::expr`] for an ordinary
4880    /// one, and [`Compiler::expr_if_tail_call`] for a `return eval(…)`, which skips `expr`
4881    /// entirely. Missing the tail-call path is not hypothetical — it is why
4882    /// `class C { #m; f() { return eval("this.#m") } }` still failed after the private
4883    /// names were otherwise wired through.
4884    fn note_direct_eval(&mut self, expr: &Expr) {
4885        if !Self::is_direct_eval(expr) {
4886            return;
4887        }
4888        // Every enclosing function is affected too: the eval sees the whole scope chain,
4889        // and a closure it creates can capture a binding of any of them.
4890        // `for (let i …) { f() }` where `f` contains the eval still needs `i` in a cell,
4891        // because the closure the eval builds outlives the loop iteration.
4892        for state in &mut self.stack {
4893            state.has_direct_eval = true;
4894        }
4895        let block = self.cur().current_block;
4896        let in_params = self.cur().in_params;
4897        // The private names are snapshotted **here**, at the call site, not when the sites
4898        // are materialised: materialisation happens once the whole function is compiled, by
4899        // which point every class scope has been popped and the answer would always be
4900        // empty.
4901        let private = self.visible_private_names();
4902        // An arrow has no `arguments` of its own and inherits the restriction from the
4903        // nearest real function: `x = () => { () => eval('arguments') }` is still a
4904        // class field initializer's arrow, and still has no `arguments` to see.
4905        let arguments_allowed = !self
4906            .stack
4907            .iter()
4908            .rev()
4909            .find(|state| !state.is_arrow)
4910            .is_some_and(|state| state.no_arguments_binding);
4911        self.state().pending_eval_sites.push((
4912            expr.span,
4913            block,
4914            in_params,
4915            private,
4916            arguments_allowed,
4917        ));
4918    }
4919
4920    fn is_direct_eval(expr: &Expr) -> bool {
4921        matches!(
4922            &expr.kind,
4923            ExprKind::Call { callee, .. }
4924                if matches!(&callee.unparen().kind, ExprKind::Ident(name) if name.name == "eval")
4925        )
4926    }
4927
4928    fn expr_inner(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
4929        match &expr.kind {
4930            ExprKind::Number(value) => self.push_number(*value),
4931            ExprKind::Bool(true) => self.emit(Opcode::PushTrue, &[]),
4932            ExprKind::Bool(false) => self.emit(Opcode::PushFalse, &[]),
4933            ExprKind::Null => self.emit(Opcode::Null, &[]),
4934            ExprKind::String(text) => self.push_string(text),
4935            ExprKind::BigInt { digits, radix } => self.push_bigint(digits, *radix),
4936            ExprKind::Ident(name) => self.emit_var(VarAction::Get, &name.name),
4937            ExprKind::This => self.this_expression(),
4938            ExprKind::NewTarget => self.new_target_expression(),
4939            ExprKind::Paren(inner) => self.expr(inner)?,
4940            ExprKind::Binary { op, left, right } => {
4941                self.expr(left)?;
4942                self.expr(right)?;
4943                self.emit(binary_opcode(*op), &[]);
4944            }
4945            ExprKind::Logical { op, left, right } => self.logical(*op, left, right)?,
4946            ExprKind::Unary {
4947                op: UnaryOp::Minus,
4948                argument,
4949            } if matches!(argument.unparen().kind, ExprKind::Number(_)) => {
4950                let ExprKind::Number(value) = argument.unparen().kind else {
4951                    unreachable!("matched above")
4952                };
4953                // The reference folds a negative literal only when the negation is
4954                // exact in the integer range: `-1` becomes `push_minus1` and
4955                // `-1.5e3` becomes `push_i16 -1500`, but `-0` and `-2.5` keep a
4956                // runtime `neg`. Folding `-0` would lose the sign — `1/-0` is
4957                // `-Infinity`, not `Infinity` — and folding a fraction would change
4958                // which instruction the reference emits.
4959                let negated = -value;
4960                // `-2147483648` is deliberately excluded: its magnitude is one past
4961                // `i32::MAX`, so the reference sends it through the constant pool and
4962                // negates at run time instead.
4963                if value > 0.0
4964                    && negated == negated.trunc()
4965                    && negated >= -(i32::MAX as f64)
4966                    && negated < 0.0
4967                {
4968                    self.push_number(negated);
4969                } else {
4970                    self.push_number(value);
4971                    self.emit(Opcode::Neg, &[]);
4972                }
4973            }
4974            ExprKind::Unary { op, argument } => self.unary(*op, argument)?,
4975            ExprKind::Conditional { test, cons, alt } => {
4976                let else_label = self.new_label();
4977                let end_label = self.new_label();
4978                self.expr(test)?;
4979                self.emit_jump(Opcode::IfFalse, else_label, &[]);
4980                self.expr(cons)?;
4981                self.emit_jump(Opcode::Goto, end_label, &[]);
4982                self.place_label(else_label);
4983                self.expr(alt)?;
4984                self.place_label(end_label);
4985            }
4986            ExprKind::Assign { op, target, value } => {
4987                let discard = std::mem::take(&mut self.discard_root);
4988                self.assign(*op, target, value, discard)?
4989            }
4990            ExprKind::Update {
4991                op,
4992                argument,
4993                prefix,
4994            } => self.update(*op, argument, *prefix)?,
4995            ExprKind::Sequence(items) => {
4996                for (index, item) in items.iter().enumerate() {
4997                    self.expr(item)?;
4998                    if index + 1 != items.len() {
4999                        self.emit(Opcode::Drop, &[]);
5000                    }
5001                }
5002            }
5003            ExprKind::Call { .. } => self.chain_link_top(expr)?,
5004            ExprKind::Member { .. } => self.chain_link_top(expr)?,
5005            ExprKind::OptionalChain(inner) => self.optional_chain(inner)?,
5006            ExprKind::Array { elements } => self.array_literal(elements, expr.span)?,
5007            ExprKind::Object(properties) => self.object_literal(properties, expr.span)?,
5008            ExprKind::Template(template) => self.template_literal(template)?,
5009            ExprKind::TaggedTemplate { tag, quasi } => self.tagged_template(tag, quasi)?,
5010            ExprKind::New { callee, arguments } => {
5011                // `new C(args)` compiles to `C; dup; args…; call_constructor n`.
5012                // The `dup` is not redundant: `call_constructor` takes the
5013                // constructor twice, once as the target and once as `new.target`,
5014                // which is what makes `new.target === C` inside the body.
5015                self.expr(callee)?;
5016                self.emit(Opcode::Dup, &[]);
5017                let args = arguments.as_deref().unwrap_or(&[]);
5018                if Self::has_spread(args) {
5019                    // `C C array`: the duplicated callee is already both the target
5020                    // and `new.target`, so no reordering is needed before `apply 1`.
5021                    self.argument_array(args)?;
5022                    self.emit(Opcode::Apply, &[Op::Int(1)]);
5023                    return Ok(());
5024                }
5025                for argument in args {
5026                    self.expr(argument)?;
5027                }
5028                self.emit(Opcode::CallConstructor, &[Op::Int(args.len() as i32)]);
5029            }
5030            ExprKind::Class(class) => self.class_definition(class, true)?,
5031            ExprKind::SuperCall(arguments) => self.super_call(arguments)?,
5032            ExprKind::Yield { argument, delegate } => {
5033                self.yield_expression(argument.as_deref(), *delegate)?
5034            }
5035            ExprKind::Await(argument) => self.await_expression(argument)?,
5036            ExprKind::RegExp { pattern, flags } => {
5037                // A literal is compiled *here*, at parse time, not when the line runs. The
5038                // spec is explicit that an invalid pattern is an early error (§12.9.4:
5039                // "/ RegularExpressionLiteral /u — it is a Syntax Error if … the pattern does
5040                // not conform"), so `print(1); /\p{Nope}/u;` must not print anything. This
5041                // also validates `\p{…}` names: 163 conformance cases are patterns that have
5042                // to be rejected before any code runs.
5043                //
5044                // This is the whole reason the engine lives in its own crate rather than
5045                // inside `quickjs-pure`: the compiler could not depend on the interpreter
5046                // (`pure` depends on `compile`), but both need this.
5047                // The lexer already rejected an unknown or repeated flag, so an unparsable
5048                // flag string here would be a bug in the lexer rather than in the script;
5049                // fall back to the default flags instead of inventing a second message.
5050                let flags_parsed = quickjs_regexp::Flags::parse(flags).unwrap_or_default();
5051                let parsed = quickjs_regexp::parse(pattern, flags_parsed).map_err(|error| {
5052                    SyntaxError::new(
5053                        format!("invalid regular expression: {}", error.message),
5054                        expr.span,
5055                    )
5056                })?;
5057                // The tree is thrown away and rebuilt when the literal first runs: keeping it
5058                // would mean serialising the syntax tree into the function's constant pool,
5059                // and a literal is created once per evaluation of its expression anyway.
5060                let _ = parsed;
5061                // The pattern and its flags travel as two string constants; `regexp` builds
5062                // the object. A dedicated opcode (rather than a call to the constructor) is
5063                // what the reference does too, so that a literal never goes through the
5064                // public `RegExp` function and its string-coercion rules.
5065                self.push_string(&Wtf8::new(pattern));
5066                self.push_string(&Wtf8::new(flags));
5067                self.emit(Opcode::Regexp, &[]);
5068            }
5069            ExprKind::Arrow(func) => {
5070                let function = self.compile_function(func)?;
5071                let index = self.push_constant(Constant::Function(Box::new(function)));
5072                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5073            }
5074            ExprKind::Function(func) => {
5075                let function = self.compile_function_with_name(func, true)?;
5076                let index = self.push_constant(Constant::Function(Box::new(function)));
5077                self.emit(Opcode::Fclosure, &[Op::Const(index)]);
5078            }
5079            // `import.meta`: the host fills a per-module object at link time.
5080            ExprKind::ImportMeta => {
5081                self.emit(Opcode::SpecialObject, &[Op::Int(6)]);
5082            }
5083            // `import("x")` compiles to a two-slot push followed by one opcode: the
5084            // specifier, then the options object. Both are evaluated, in that order, because
5085            // §13.3.10.1 numbers them that way and their side effects are observable — the
5086            // absent second argument is a literal `undefined`, which evaluates to nothing.
5087            ExprKind::ImportCall(specifier, options) => {
5088                self.expr(specifier)?;
5089                match options {
5090                    Some(options) => self.expr(options)?,
5091                    None => {
5092                        self.emit(Opcode::Undefined, &[]);
5093                    }
5094                }
5095                self.emit(Opcode::Import, &[]);
5096            }
5097            ExprKind::PrivateIn { name, object } => {
5098                // `#x in o`: the object, then the binding, then one opcode which decides what
5099                // to do with the second operand. A field's binding holds a symbol and the
5100                // answer is an own-property test; a method's holds a function and the answer
5101                // is a brand check — both live in `private_in`, so the compiler emits the
5102                // same instruction for either.
5103                self.expr(object)?;
5104                self.emit_var(VarAction::Get, &format!("#{}", name.name));
5105                self.emit(Opcode::PrivateIn, &[]);
5106            }
5107            _ => {
5108                return Err(SyntaxError::new(
5109                    "this expression form is not supported by the compiler yet",
5110                    expr.span,
5111                ));
5112            }
5113        }
5114        Ok(())
5115    }
5116
5117    /// Build one array holding the evaluated call arguments, which is how a call
5118    /// containing a spread is compiled: the reference does the same, building the
5119    /// list on the stack and handing it to `apply`.
5120    fn argument_array(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
5121        let elements: Vec<Option<ArrayElement>> = arguments
5122            .iter()
5123            .map(|argument| match &argument.unparen().kind {
5124                ExprKind::Spread(inner) => Some(ArrayElement::Spread(inner.clone())),
5125                _ => Some(ArrayElement::Expr(Box::new(argument.clone()))),
5126            })
5127            .collect();
5128        self.array_literal(&elements, Span::default())
5129    }
5130
5131    /// Whether any argument is a spread, which is what selects the `apply` form.
5132    fn has_spread(arguments: &[Expr]) -> bool {
5133        arguments
5134            .iter()
5135            .any(|argument| matches!(argument.unparen().kind, ExprKind::Spread(_)))
5136    }
5137
5138    /// Compile `a${x}b`.
5139    ///
5140    /// A template is a `+` chain built left to right: the leading chunk (or an empty
5141    /// string when the template starts with a substitution), then for each
5142    /// substitution its value, `to_propkey` and `add`, then the following chunk when
5143    /// it is not empty. `to_propkey` is what makes a number or object substitute the
5144    /// way `ToString` would while leaving the result a string for `add` to
5145    /// concatenate.
5146    ///
5147    /// The chunk is an atom rather than a constant-pool string, because a non-empty
5148    /// chunk always lands where a value is pushed and `push_atom_value` is the
5149    /// instruction the reference uses for it; the empty first chunk has its own
5150    /// zero-byte form.
5151    fn template_literal(&mut self, template: &TemplateLiteral) -> Result<(), SyntaxError> {
5152        let first = template.quasis.first();
5153        match first.and_then(|quasi| quasi.cooked.clone()) {
5154            Some(text) if !text.is_empty() => {
5155                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5156            }
5157            // Either the template begins with a substitution, or the chunk is
5158            // empty — in both cases the chain needs a string to start from.
5159            _ => self.emit(Opcode::PushEmptyString, &[]),
5160        }
5161        for (index, expression) in template.expressions.iter().enumerate() {
5162            self.expr(expression)?;
5163            self.emit(Opcode::ToPropkey, &[]);
5164            self.emit(Opcode::Add, &[]);
5165            if let Some(text) = template
5166                .quasis
5167                .get(index + 1)
5168                .and_then(|quasi| quasi.cooked.clone())
5169                && !text.is_empty()
5170            {
5171                self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(&text))]);
5172                self.emit(Opcode::Add, &[]);
5173            }
5174        }
5175        Ok(())
5176    }
5177
5178    /// Compile an object literal.
5179    ///
5180    /// The object is built in place: `object` pushes it, and each property leaves it
5181    /// on the stack with one field more, so no temporary is needed and later
5182    /// properties can overwrite earlier ones.
5183    ///
5184    /// The instruction depends on *how* the property was written, not on what kind
5185    /// of value it holds:
5186    ///
5187    /// | source | instruction |
5188    /// |---|---|
5189    /// | `{ a: v }` | `define_field a` |
5190    /// | `{ __proto__: v }` | `set_proto` |
5191    /// | `{ [k]: v }` | `to_propkey` … `define_array_el` + `drop` |
5192    /// | `{ m() {} }` | `define_method m,4` |
5193    /// | `{ get m() {} }` / `{ set m(v) {} }` | `define_method m,5` / `,6` |
5194    /// | `{ [k]() {} }` | `define_method_computed 4` |
5195    /// | `{ ...v }` | `null` … `copy_data_properties 6` + two `drop`s |
5196    ///
5197    /// A computed *method* skips `to_propkey`: `define_method_computed` converts the
5198    /// key itself, which is why the trailing `drop` is absent there too.
5199    /// `tag`…``: a call whose first argument is the call site's template object.
5200    ///
5201    /// The template object is a frozen array of the cooked chunks with a frozen `raw`
5202    /// array beside it, so `String.raw` can read the source text back. It is a constant
5203    /// because its contents never change; the reference builds one per call site and
5204    /// reuses it, while this builds one per evaluation, which only `tag` code that
5205    /// compares template objects across calls could tell apart.
5206    /// A fresh template site id. See [`Constant::Template`].
5207    fn tagged_template(&mut self, tag: &Expr, quasi: &TemplateLiteral) -> Result<(), SyntaxError> {
5208        let cooked = quasi
5209            .quasis
5210            .iter()
5211            .map(|chunk| chunk.cooked.clone())
5212            .collect();
5213        let raw = quasi.quasis.iter().map(|chunk| chunk.raw.clone()).collect();
5214        let index = self.push_constant(Constant::Template {
5215            site: next_template_site(),
5216            cooked,
5217            raw,
5218        });
5219        let count = quasi.expressions.len() + 1;
5220        // `o.m`…`` passes `o` as `this`, exactly as `o.m(…)` does.
5221        if let ExprKind::Member {
5222            object, property, ..
5223        } = &tag.unparen().kind
5224        {
5225            self.expr(object)?;
5226            match property {
5227                MemberProp::Ident(name) => {
5228                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
5229                }
5230                MemberProp::Computed(key) => {
5231                    self.expr(key)?;
5232                    self.emit(Opcode::GetArrayEl2, &[]);
5233                }
5234                MemberProp::Private(name) => {
5235                    let binding = format!("#{}", name.name);
5236                    let (kind, _) = self.private_use(&binding, tag.span)?;
5237                    self.private_callee(&binding, kind)?;
5238                }
5239            }
5240            self.emit(Opcode::PushConst, &[Op::Const(index)]);
5241            for expression in &quasi.expressions {
5242                self.expr(expression)?;
5243            }
5244            self.emit(Opcode::CallMethod, &[Op::Int(count as i32)]);
5245            return Ok(());
5246        }
5247        self.expr(tag)?;
5248        self.emit(Opcode::PushConst, &[Op::Const(index)]);
5249        for expression in &quasi.expressions {
5250            self.expr(expression)?;
5251        }
5252        self.emit(Opcode::Call, &[Op::Int(count as i32)]);
5253        Ok(())
5254    }
5255
5256    fn object_literal(
5257        &mut self,
5258        properties: &[ObjectProperty],
5259        span: Span,
5260    ) -> Result<(), SyntaxError> {
5261        self.emit(Opcode::Object, &[]);
5262        for property in properties {
5263            match property {
5264                ObjectProperty::Spread(value) => {
5265                    // `copy_data_properties` takes the target, the source and an
5266                    // exclusion list; a literal `null` means "exclude nothing".
5267                    // Flag bit 1 copies symbols, bits 2/5 pick the source and the
5268                    // exclusion list by stack offset.
5269                    self.expr(spread_argument(value))?;
5270                    self.emit(Opcode::Null, &[]);
5271                    self.emit(Opcode::CopyDataProperties, &[Op::Int(COPY_ALL_PROPERTIES)]);
5272                    self.emit(Opcode::Drop, &[]);
5273                    self.emit(Opcode::Drop, &[]);
5274                }
5275                ObjectProperty::Property {
5276                    key,
5277                    value,
5278                    kind,
5279                    shorthand,
5280                    span: property_span,
5281                } => match key {
5282                    PropName::Computed(key_expr) => {
5283                        self.expr(key_expr)?;
5284                        match kind {
5285                            PropertyKind::Value => {
5286                                self.emit(Opcode::ToPropkey, &[]);
5287                                self.expr(value)?;
5288                                self.set_name_if_anonymous_computed(value);
5289                                self.emit(Opcode::DefineArrayEl, &[]);
5290                                // `define_array_el` leaves the object and the key;
5291                                // the key is no longer needed.
5292                                self.emit(Opcode::Drop, &[]);
5293                            }
5294                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5295                                self.emit_method_function(value)?;
5296                                self.emit(
5297                                    Opcode::DefineMethodComputed,
5298                                    &[Op::Int(define_method_flags(*kind))],
5299                                );
5300                            }
5301                        }
5302                    }
5303                    PropName::Literal(key) => {
5304                        let name = self.property_key_text(key, *property_span)?;
5305                        match kind {
5306                            PropertyKind::Method | PropertyKind::Get | PropertyKind::Set => {
5307                                self.emit_method_function(value)?;
5308                                self.emit(
5309                                    Opcode::DefineMethod,
5310                                    &[
5311                                        Op::Atom(Atom::from_wtf8(&name)),
5312                                        Op::Int(define_method_flags(*kind)),
5313                                    ],
5314                                );
5315                            }
5316                            PropertyKind::Value => {
5317                                self.expr(value)?;
5318                                // `{__proto__: x}` sets the prototype instead of
5319                                // creating a property; the shorthand `{__proto__}`
5320                                // is an ordinary property and does not.
5321                                if name == "__proto__" && !shorthand {
5322                                    self.emit(Opcode::SetProto, &[]);
5323                                } else {
5324                                    self.set_name_if_anonymous(value, &name);
5325                                    self.emit(
5326                                        Opcode::DefineField,
5327                                        &[Op::Atom(Atom::from_wtf8(&name))],
5328                                    );
5329                                }
5330                            }
5331                        }
5332                    }
5333                    PropName::Private(_) => {
5334                        return Err(SyntaxError::new(
5335                            "private names are not valid in object literals",
5336                            *property_span,
5337                        ));
5338                    }
5339                },
5340            }
5341        }
5342        let _ = span;
5343        Ok(())
5344    }
5345
5346    /// Emit the function a method/accessor property defines.
5347    fn emit_method_function(&mut self, value: &Expr) -> Result<(), SyntaxError> {
5348        self.expr(value)
5349    }
5350
5351    /// The name a literal property key contributes.
5352    ///
5353    /// String keys are used as written. A numeric key is converted the way
5354    /// `ToString` would convert it, because the atom is made from that spelling:
5355    /// `{ 1e2: x }` and `{ 0x10: x }` both become `define_field 100` / `16`.
5356    fn property_key_text(&self, key: &PropKey, span: Span) -> Result<Wtf8, SyntaxError> {
5357        match key {
5358            PropKey::Str(text) => Ok(text.clone()),
5359            PropKey::Num(value) => numeric_key_text(*value, span).map(Wtf8::new),
5360        }
5361    }
5362
5363    /// Compile an optional chain.
5364    ///
5365    /// `?.` short-circuits the *whole remaining spine*, not just its own link:
5366    /// `a?.b.c` yields `undefined` when `a` is null, it does not read `.c` of
5367    /// `undefined`. So the chain is compiled with one end label and every guard
5368    /// jumps to it. The parser hands us the extent of that spine as an
5369    /// [`ExprKind::OptionalChain`] wrapper around the outermost link, which is
5370    /// exactly the scope the label has to cover.
5371    fn optional_chain(&mut self, inner: &Expr) -> Result<(), SyntaxError> {
5372        let end = self.new_label();
5373        self.chain_link(inner, end)?;
5374        self.place_label(end);
5375        Ok(())
5376    }
5377
5378    /// A member access or call reached from outside any optional chain.
5379    ///
5380    /// Such a link cannot contain a `?.` — if it did, the parser would have wrapped
5381    /// it in [`ExprKind::OptionalChain`] — so there is no guard and no label; one is
5382    /// still created because [`Self::chain_link`] takes it, and placing it at the
5383    /// end is a no-op that keeps a single code path.
5384    fn chain_link_top(&mut self, expr: &Expr) -> Result<(), SyntaxError> {
5385        let end = self.new_label();
5386        self.chain_link(expr, end)?;
5387        self.place_label(end);
5388        Ok(())
5389    }
5390
5391    /// One link of a chain, where `end` is the label a `?.` guard jumps to.
5392    fn chain_link(&mut self, expr: &Expr, end: Label) -> Result<(), SyntaxError> {
5393        match &expr.kind {
5394            ExprKind::Member {
5395                object,
5396                property,
5397                optional,
5398            } => {
5399                // `super.x` is not a lookup on a value: it starts at the home object's
5400                // prototype and keeps `this` as the receiver, so it cannot go through
5401                // `chain_link` and the ordinary field read.
5402                if matches!(object.unparen().kind, ExprKind::SuperProp) {
5403                    self.super_base();
5404                    match property {
5405                        MemberProp::Ident(name) => self.emit(
5406                            Opcode::PushAtomValue,
5407                            &[Op::Atom(Atom::from_text(&name.name))],
5408                        ),
5409                        MemberProp::Computed(index) => self.expr(index)?,
5410                        MemberProp::Private(_) => {
5411                            return Err(SyntaxError::new(
5412                                "private fields are not supported by the compiler yet",
5413                                expr.span,
5414                            ));
5415                        }
5416                    }
5417                    self.emit(Opcode::GetSuperValue, &[]);
5418                    return Ok(());
5419                }
5420                self.chain_link(object, end)?;
5421                if *optional {
5422                    self.optional_guard(end);
5423                }
5424                match property {
5425                    // `.length` has its own opcode. The reference emits it for every
5426                    // object, not just arrays, so a name-based rule is right and
5427                    // cheaper than the generic field read.
5428                    MemberProp::Ident(name) if name.name == "length" => {
5429                        self.emit(Opcode::GetLength, &[]);
5430                    }
5431                    MemberProp::Ident(name) => {
5432                        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text(&name.name))]);
5433                    }
5434                    MemberProp::Computed(index) => {
5435                        self.expr(index)?;
5436                        self.emit(Opcode::GetArrayEl, &[]);
5437                    }
5438                    MemberProp::Private(name) => {
5439                        // The binding comes from the class scope, so a read from outside the
5440                        // class cannot name it at all. `?.` checks the object, not the field:
5441                        // `o?.#x` guards on `o` being nullish.
5442                        let binding = format!("#{}", name.name);
5443                        let (kind, _) = self.private_use(&binding, expr.span)?;
5444                        self.private_load(&binding, kind, expr.span)?;
5445                    }
5446                }
5447                Ok(())
5448            }
5449            ExprKind::Call {
5450                callee,
5451                arguments,
5452                optional,
5453            } => {
5454                // `o.m(args)` has to pass `o` as `this`, which a plain `call`
5455                // cannot: it reads the function and then calls it with no
5456                // receiver at all. The reference's answer is to keep the object
5457                // under the function value — `get_field2` reads a field and leaves
5458                // its base in place — and to use `call_method`, which takes the
5459                // receiver from the stack. Missing this does not just cost an
5460                // instruction, it loses the `this` binding.
5461                if let ExprKind::Member {
5462                    object,
5463                    property,
5464                    optional: member_optional,
5465                } = &callee.unparen().kind
5466                {
5467                    // `super.m()` reads the method off the home object's prototype but
5468                    // calls it with `this`, so the receiver goes under the read instead of
5469                    // being replaced by it.
5470                    if matches!(object.unparen().kind, ExprKind::SuperProp) {
5471                        self.super_base();
5472                        match property {
5473                            MemberProp::Ident(name) => self.emit(
5474                                Opcode::PushAtomValue,
5475                                &[Op::Atom(Atom::from_text(&name.name))],
5476                            ),
5477                            MemberProp::Computed(index) => self.expr(index)?,
5478                            MemberProp::Private(_) => {
5479                                return Err(SyntaxError::new(
5480                                    "private fields are not supported by the compiler yet",
5481                                    expr.span,
5482                                ));
5483                            }
5484                        }
5485                        // The two-output form would drop the receiver; this one replaces
5486                        // the prototype and the key, leaving `this` underneath.
5487                        self.emit(Opcode::GetArrayEl, &[]);
5488                        if Self::has_spread(arguments) {
5489                            self.argument_array(arguments)?;
5490                            self.emit(Opcode::Perm3, &[]);
5491                            self.emit(Opcode::Apply, &[Op::Int(0)]);
5492                            return Ok(());
5493                        }
5494                        for argument in arguments {
5495                            self.expr(argument)?;
5496                        }
5497                        self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5498                        return Ok(());
5499                    }
5500                    self.chain_link(object, end)?;
5501                    if *member_optional {
5502                        self.optional_guard(end);
5503                    }
5504                    match property {
5505                        MemberProp::Ident(name) => {
5506                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5507                        }
5508                        MemberProp::Computed(index) => {
5509                            self.expr(index)?;
5510                            // The key is not needed after the read, so this is the
5511                            // two-output form: object, value.
5512                            self.emit(Opcode::GetArrayEl2, &[]);
5513                        }
5514                        MemberProp::Private(name) => {
5515                            // The receiver is already under the callee, which is exactly the
5516                            // shape `call_method` and `apply` want — so nothing is dropped.
5517                            let binding = format!("#{}", name.name);
5518                            let (kind, _) = self.private_use(&binding, expr.span)?;
5519                            self.private_callee(&binding, kind)?;
5520                        }
5521                    }
5522                    if Self::has_spread(arguments) {
5523                        // Stack is `obj func`; the array goes on top, then `perm3`
5524                        // reorders to the `func this array` that `apply` wants.
5525                        self.argument_array(arguments)?;
5526                        self.emit(Opcode::Perm3, &[]);
5527                        self.emit(Opcode::Apply, &[Op::Int(0)]);
5528                        return Ok(());
5529                    }
5530                    for argument in arguments {
5531                        self.expr(argument)?;
5532                    }
5533                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5534                    return Ok(());
5535                }
5536                // `(a?.b)()` keeps `a` as the receiver: the reference reads the method
5537                // with `get_field2` so the base stays under it, and on the short-circuit
5538                // path pushes an extra `undefined` as a placeholder receiver — the call
5539                // then throws, which is what calling a missing optional chain should do.
5540                if let ExprKind::OptionalChain(inner) = &callee.unparen().kind
5541                    && let ExprKind::Member {
5542                        object,
5543                        property,
5544                        optional: member_optional,
5545                    } = &inner.unparen().kind
5546                {
5547                    let call = self.new_label();
5548                    // A guard target of its own: the outer `end` skips the whole
5549                    // expression, and a short-circuited receiver still has to reach the
5550                    // call so that calling it throws.
5551                    let short = self.new_label();
5552                    self.chain_link(object, end)?;
5553                    if *member_optional {
5554                        self.optional_guard(short);
5555                    }
5556                    match property {
5557                        MemberProp::Ident(name) => {
5558                            self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5559                        }
5560                        MemberProp::Computed(index) => {
5561                            self.expr(index)?;
5562                            self.emit(Opcode::GetArrayEl2, &[]);
5563                        }
5564                        MemberProp::Private(name) => {
5565                            let binding = format!("#{}", name.name);
5566                            let (kind, _) = self.private_use(&binding, expr.span)?;
5567                            self.private_callee(&binding, kind)?;
5568                        }
5569                    }
5570                    self.emit_jump(Opcode::Goto, call, &[]);
5571                    self.place_label(short);
5572                    self.emit(Opcode::Undefined, &[]);
5573                    self.place_label(call);
5574                    if Self::has_spread(arguments) {
5575                        self.argument_array(arguments)?;
5576                        self.emit(Opcode::Perm3, &[]);
5577                        self.emit(Opcode::Apply, &[Op::Int(0)]);
5578                        return Ok(());
5579                    }
5580                    for argument in arguments {
5581                        self.expr(argument)?;
5582                    }
5583                    self.emit(Opcode::CallMethod, &[Op::Int(arguments.len() as i32)]);
5584                    return Ok(());
5585                }
5586                self.chain_link(callee, end)?;
5587                if *optional {
5588                    self.optional_guard(end);
5589                }
5590                if Self::has_spread(arguments) {
5591                    // `func array -> func undefined array`, which is the plain-call
5592                    // form of `apply`: the receiver is `undefined`.
5593                    self.argument_array(arguments)?;
5594                    self.emit(Opcode::Undefined, &[]);
5595                    self.emit(Opcode::Swap, &[]);
5596                    self.emit(Opcode::Apply, &[Op::Int(0)]);
5597                    return Ok(());
5598                }
5599                for argument in arguments {
5600                    self.expr(argument)?;
5601                }
5602                self.emit(Opcode::Call, &[Op::Int(arguments.len() as i32)]);
5603                Ok(())
5604            }
5605            _ => self.expr(expr),
5606        }
5607    }
5608
5609    /// Compile `expr` as a tail call when it is one, reporting whether it was.
5610    ///
5611    /// `tail_call` reuses the current frame instead of pushing a new one, so a
5612    /// tail-recursive function runs in constant stack space. It also has to be the
5613    /// *last* thing the function does, which is why only a `return` reaches here.
5614    fn expr_if_tail_call(&mut self, expr: &Expr) -> Result<bool, SyntaxError> {
5615        let ExprKind::Call {
5616            callee,
5617            arguments,
5618            optional: false,
5619        } = &expr.unparen().kind
5620        else {
5621            return Ok(false);
5622        };
5623        // A spread call has no tail form: `tail_call` takes its arguments one at a time off
5624        // the stack, while `f(...xs)` builds an array and goes through `apply`. Compiling it
5625        // as an ordinary call costs the one frame the optimisation was saving and keeps the
5626        // semantics — the alternative was reaching the spread expression below and failing
5627        // with "this expression form is not supported", which is how `return super.m(...a)`
5628        // stopped compiling. Checked before anything is emitted, because the decision cannot
5629        // be taken back once `super_base` or a `get_field2` is on the stack.
5630        if Self::has_spread(arguments) {
5631            return Ok(false);
5632        }
5633        let end = self.new_label();
5634        if let ExprKind::Member {
5635            object,
5636            property,
5637            optional: false,
5638        } = &callee.unparen().kind
5639        {
5640            // `super.m()` in tail position is still an ordinary method call with `this`
5641            // as the receiver; only the read of the method differs.
5642            if matches!(object.unparen().kind, ExprKind::SuperProp) {
5643                self.super_base();
5644                match property {
5645                    MemberProp::Ident(name) => self.emit(
5646                        Opcode::PushAtomValue,
5647                        &[Op::Atom(Atom::from_text(&name.name))],
5648                    ),
5649                    MemberProp::Computed(index) => self.expr(index)?,
5650                    MemberProp::Private(_) => return Ok(false),
5651                }
5652                self.emit(Opcode::GetArrayEl, &[]);
5653                for argument in arguments {
5654                    self.expr(argument)?;
5655                }
5656                self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5657                self.place_label(end);
5658                return Ok(true);
5659            }
5660            self.chain_link(object, end)?;
5661            match property {
5662                MemberProp::Ident(name) => {
5663                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))])
5664                }
5665                MemberProp::Computed(index) => {
5666                    self.expr(index)?;
5667                    self.emit(Opcode::GetArrayEl2, &[]);
5668                }
5669                MemberProp::Private(_) => return Ok(false),
5670            }
5671            for argument in arguments {
5672                self.expr(argument)?;
5673            }
5674            self.emit(Opcode::TailCallMethod, &[Op::Int(arguments.len() as i32)]);
5675            self.place_label(end);
5676            return Ok(true);
5677        }
5678        self.chain_link(callee, end)?;
5679        for argument in arguments {
5680            self.expr(argument)?;
5681        }
5682        self.emit(Opcode::TailCall, &[Op::Int(arguments.len() as i32)]);
5683        self.place_label(end);
5684        Ok(true)
5685    }
5686
5687    /// The `?.` guard: keep the value if it is neither null nor undefined,
5688    /// otherwise replace it with `undefined` and leave the whole chain.
5689    fn optional_guard(&mut self, end: Label) {
5690        let cont = self.new_label();
5691        self.emit(Opcode::Dup, &[]);
5692        self.emit(Opcode::IsUndefinedOrNull, &[]);
5693        self.emit_jump(Opcode::IfFalse, cont, &[]);
5694        self.emit(Opcode::Drop, &[]);
5695        self.emit(Opcode::Undefined, &[]);
5696        self.emit_jump(Opcode::Goto, end, &[]);
5697        self.place_label(cont);
5698    }
5699
5700    fn push_number(&mut self, value: f64) {
5701        // `push_N` / `push_i8` / `push_i32` cover small integers; everything else
5702        // goes into the constant pool.
5703        if value == value.trunc() && value.abs() <= i32::MAX as f64 {
5704            let int = value as i32;
5705            if (-1..=7).contains(&int) {
5706                self.emit(Opcode::PushI32, &[Op::Int(int)]);
5707                return;
5708            }
5709            if (-128..=127).contains(&int) {
5710                self.emit(Opcode::PushI8, &[Op::Int(int)]);
5711                return;
5712            }
5713            if (-32768..=32767).contains(&int) {
5714                self.emit(Opcode::PushI16, &[Op::Int(int)]);
5715                return;
5716            }
5717            self.emit(Opcode::PushI32, &[Op::Int(int)]);
5718            return;
5719        }
5720        let index = self.push_constant(Constant::Number(value));
5721        self.emit(Opcode::PushConst, &[Op::Const(index)]);
5722    }
5723
5724    /// Push a `BigInt` literal.
5725    ///
5726    /// A value that fits an `i32` uses the immediate form, which is what the reference
5727    /// emits too; anything larger goes into the constant pool, because the operand of
5728    /// `push_bigint` is only four bytes wide.
5729    fn push_bigint(&mut self, digits: &str, radix: u32) {
5730        if radix == 10
5731            && let Ok(value) = digits.parse::<i64>()
5732            && (i32::MIN as i64..=i32::MAX as i64).contains(&value)
5733        {
5734            self.emit(Opcode::PushBigintI32, &[Op::Int(value as i32)]);
5735            return;
5736        }
5737        let index = self.push_constant(Constant::BigInt {
5738            digits: digits.to_string(),
5739            radix,
5740        });
5741        self.emit(Opcode::PushConst, &[Op::Const(index)]);
5742    }
5743
5744    fn push_string(&mut self, text: &Wtf8) {
5745        if text.is_empty() {
5746            self.emit(Opcode::PushEmptyString, &[]);
5747            return;
5748        }
5749        self.emit(Opcode::PushAtomValue, &[Op::Atom(Atom::from_wtf8(text))]);
5750    }
5751
5752    /// Name an anonymous function from the binding it is assigned to.
5753    ///
5754    /// `var f = function(){}` produces a function whose `name` is `f`, which the
5755    /// runtime cannot know without being told: the function object is created
5756    /// before the store. `set_name` carries the name across.
5757    fn set_name_if_anonymous(&mut self, value: &Expr, name: &Wtf8) {
5758        if !value.is_anonymous_function_definition() {
5759            return;
5760        }
5761        // A class cannot use `set_name`, because its static field initialisers have already
5762        // run by the time the store happens and they can see `this.name`:
5763        // `var E = class { static f = this.name }` has to answer `"E"`. The reference patches
5764        // the `define_class` instruction's name operand instead, which is why
5765        // `set_class_name` is a compile-time marker with no runtime effect
5766        // (`class-name-static-initializer-anonymous`).
5767        if matches!(value.unparen().kind, ExprKind::Class(_)) {
5768            if let Some(index) = self.last_define_class() {
5769                let atom = Atom::from_wtf8(name);
5770                if let Some(Insn::Fixed { operands, .. }) = self.state().insns.get_mut(index) {
5771                    // `define_class <atom> <flags>`: the name is operand 0.
5772                    operands[0] = Op::Atom(atom);
5773                }
5774            }
5775            return;
5776        }
5777        self.emit(Opcode::SetName, &[Op::Atom(Atom::from_wtf8(name))]);
5778    }
5779
5780    /// The index of the most recent `define_class` in this function's instruction stream.
5781    ///
5782    /// A backwards scan, because everything the class body emitted for the *enclosing*
5783    /// function is still there after it — the static initialiser's call, the class
5784    /// binding's store, `leave_scope` — and only the `define_class` carries the name.
5785    fn last_define_class(&self) -> Option<usize> {
5786        self.cur().insns.iter().rposition(|insn| {
5787            matches!(
5788                insn,
5789                Insn::Fixed {
5790                    op: Opcode::DefineClass,
5791                    ..
5792                }
5793            )
5794        })
5795    }
5796
5797    /// The same, for a computed key: the name comes from the value on the stack
5798    /// rather than from an atom, so a different instruction carries it.
5799    fn set_name_if_anonymous_computed(&mut self, value: &Expr) {
5800        if value.is_anonymous_function_definition() {
5801            self.emit(Opcode::SetNameComputed, &[]);
5802        }
5803    }
5804
5805    /// Compile a function body that exists only in the compiler's head — a class's
5806    /// implicit constructor or its field initialiser.
5807    ///
5808    /// Everything structural is the same as a written function: a fresh `FnState`, its
5809    /// own body block, and resolution while the frame is still on the stack. Only the
5810    /// statements differ.
5811    fn compile_synthetic_function(
5812        &mut self,
5813        name: &str,
5814        strict: bool,
5815        span: Span,
5816        body: impl FnOnce(&mut Self) -> Result<(), SyntaxError>,
5817    ) -> Result<CompiledFunction, SyntaxError> {
5818        let mut state = FnState::new(name.to_string(), FunctionKind::Normal);
5819        state.span = Some((span.start.offset as usize, span.end.offset as usize));
5820        state.strict = strict;
5821        state.created_in_block = self.cur().current_block;
5822        state.with_names = self.cur().with_names.clone();
5823        state.line = span.start.line;
5824        state.column = span.start.column;
5825        let depth = self.stack.len();
5826        self.stack.push(state);
5827        let body_key = span.start.offset as u64;
5828        self.push_block(body_key, NO_PARENT);
5829        self.state().body_block = body_key;
5830        let result = (|| {
5831            self.emit_scope_enter(body_key);
5832            body(self)?;
5833            if self.end_is_reachable() {
5834                self.emit(Opcode::ReturnUndef, &[]);
5835            }
5836            Ok(())
5837        })();
5838        if result.is_err() {
5839            self.stack.truncate(depth);
5840            return result.map(|()| unreachable!());
5841        }
5842        Ok(self.finish_current())
5843    }
5844
5845    /// The implicit return of a class constructor.
5846    ///
5847    /// A constructor that falls off the end initialises its instance fields first, and a
5848    /// derived one returns `this` — which is what makes `new D()` the object `super()`
5849    /// built rather than `undefined`.
5850    fn emit_class_constructor_tail(&mut self) {
5851        match self.cur().ctor_kind {
5852            CtorKind::None => self.emit(Opcode::ReturnUndef, &[]),
5853            // Nothing to install: a base constructor did it in its prologue and a derived
5854            // one at each `super()` site, which is where `this` first exists.
5855            CtorKind::Base => self.emit(Opcode::ReturnUndef, &[]),
5856            CtorKind::Derived => {
5857                // `get_loc_check` rather than `get_loc`: reaching the end without ever
5858                // running `super()` is a ReferenceError, not `undefined`.
5859                self.emit_var(VarAction::Get, "this");
5860                self.emit(Opcode::Return, &[]);
5861            }
5862        }
5863    }
5864
5865    /// `yield expr` / `yield* expr`.
5866    ///
5867    /// The suspension itself is one instruction: the value is on the stack, `yield` hands
5868    /// it to the caller and parks the frame. On resume the stack holds the value the
5869    /// caller passed *and* a "magic" number saying which method resumed it — `next`
5870    /// passes `0`, `return` passes `1`, `throw` passes `2` — so the emitted
5871    /// `if_false <continue>` asks whether this was an ordinary `next`:
5872    ///
5873    /// * `next(v)` → the magic is falsy, jump over the `return_async` and `drop` `v`.
5874    /// * `return(v)`/`throw(e)` → fall into `return_async`, which finishes the generator
5875    ///   and uses the value sitting under the magic number.
5876    ///
5877    /// A `throw` never reaches here: the interpreter unwinds instead (see
5878    /// `Interp::resume_generator`), so the `return_async` arm only ever carries `return`.
5879    fn yield_expression(
5880        &mut self,
5881        argument: Option<&Expr>,
5882        delegate: bool,
5883    ) -> Result<(), SyntaxError> {
5884        if delegate {
5885            return self.yield_star(argument);
5886        }
5887        // `AsyncGeneratorYield` settles the value *before* suspending, and `AsyncGenerator`
5888        // does the same for the `return(v)` that can resume it — which is why an async
5889        // generator's `yield` is `await; yield; (…); await; return_async` and a synchronous
5890        // generator's is just `yield`.
5891        let is_async = self.cur().kind == FunctionKind::AsyncGenerator;
5892        match argument {
5893            Some(value) => self.expr(value)?,
5894            None => self.emit(Opcode::Undefined, &[]),
5895        }
5896        if is_async {
5897            self.emit(Opcode::Await, &[]);
5898            self.state().has_await = true;
5899        }
5900        self.emit(Opcode::Yield, &[]);
5901        let resume = self.new_label();
5902        self.emit_jump(Opcode::IfFalse, resume, &[]);
5903        // `return(v)` resumed us. It is a `return` from the *body's* point of view, so it
5904        // runs the same cleanup chain: without it, `it.return()` inside `try { yield }`
5905        // finished the generator and never ran the `finally`.
5906        if is_async {
5907            self.emit(Opcode::Await, &[]);
5908        }
5909        self.emit_unwind_for_return(true);
5910        self.emit(Opcode::ReturnAsync, &[]);
5911        self.place_label(resume);
5912        // Nothing is emitted here: the value the caller passed to `next` *is* the value
5913        // of the `yield` expression, so `var x = yield 1` stores it and `yield 1;` drops
5914        // it through the ordinary expression-statement discard.
5915        Ok(())
5916    }
5917
5918    /// `yield* iterable`.
5919    ///
5920    /// The shape is the reference's, and it is a fall-through chain rather than a
5921    /// decision tree: drive the inner iterator, forward each value with `yield_star`, and
5922    /// on resume decide what the caller asked for — `next` keeps looping, `return` closes
5923    /// the inner iterator and finishes, `throw` forwards the exception into it and
5924    /// continues only if it has a `throw` method.
5925    ///
5926    /// The stack is `iter next catch value` throughout, `catch` being the offset
5927    /// `for_of_start` pushed; the `nip`s at the end uncover the value that is returned.
5928    fn yield_star(&mut self, argument: Option<&Expr>) -> Result<(), SyntaxError> {
5929        match argument {
5930            Some(value) => self.expr(value)?,
5931            // The parser rejects a bare `yield*`, so this is unreachable in practice.
5932            None => return Err(SyntaxError::new("yield* needs an operand", Span::default())),
5933        }
5934        // `for await of` is the same protocol as `for of` with two differences that matter
5935        // here: the iterator comes from `@@asyncIterator` with a `@@iterator` fallback, and
5936        // every `next()` result is a promise the delegate has to await.
5937        let is_async = self.cur().kind.is_async();
5938        self.emit(
5939            if is_async {
5940                Opcode::ForAwaitOfStart
5941            } else {
5942                Opcode::ForOfStart
5943            },
5944            &[],
5945        );
5946        self.emit(Opcode::Drop, &[]);
5947        self.emit(Opcode::Undefined, &[]);
5948        self.emit(Opcode::Undefined, &[]);
5949        let next = self.new_label();
5950        let resume = self.new_label();
5951        let finished = self.new_label();
5952        let rethrow = self.new_label();
5953        let throw_no_method = self.new_label();
5954        let done = self.new_label();
5955        self.place_label(next);
5956        self.emit(Opcode::IteratorNext, &[]);
5957        if is_async {
5958            self.emit(Opcode::Await, &[]);
5959            self.state().has_await = true;
5960        }
5961        self.emit(Opcode::IteratorCheckObject, &[]);
5962        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
5963        self.emit_jump(Opcode::IfTrue, done, &[]);
5964        // The suspension. `resume` is both the label the return path jumps back to in order
5965        // to yield one more value and where the caller's answer arrives, as the value
5966        // followed by the magic number.
5967        //
5968        // The two forms differ in what they hand the suspension: `yield_star` takes the
5969        // result object itself, `async_yield_star` takes `.value`, because an async
5970        // generator awaits and re-wraps whatever it yields.
5971        self.place_label(resume);
5972        if is_async {
5973            self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
5974            self.emit(Opcode::AsyncYieldStar, &[]);
5975        } else {
5976            self.emit(Opcode::YieldStar, &[]);
5977        }
5978        self.emit(Opcode::Dup, &[]);
5979        self.emit_jump(Opcode::IfTrue, rethrow, &[]);
5980        self.emit(Opcode::Drop, &[]);
5981        self.emit_jump(Opcode::Goto, next, &[]);
5982
5983        // `return(v)` / `throw(e)`: `2 === magic` tells them apart.
5984        self.place_label(rethrow);
5985        self.emit(Opcode::PushI32, &[Op::Int(2)]);
5986        self.emit(Opcode::StrictEq, &[]);
5987        self.emit_jump(Opcode::IfTrue, throw_no_method, &[]);
5988        // A `return` closes the inner iterator; if it had none, the delegate simply
5989        // finishes with the requested value. In an async generator both the call and its
5990        // result are awaited, because the inner `return` may itself be async.
5991        if is_async {
5992            self.emit(Opcode::Await, &[]);
5993        }
5994        self.emit(Opcode::IteratorCall, &[Op::Int(0)]);
5995        self.emit_jump(Opcode::IfTrue, finished, &[]);
5996        if is_async {
5997            self.emit(Opcode::Await, &[]);
5998        }
5999        self.emit(Opcode::IteratorCheckObject, &[]);
6000        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6001        self.emit_jump(Opcode::IfFalse, resume, &[]);
6002        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6003        self.place_label(finished);
6004        self.emit(Opcode::Nip, &[]);
6005        self.emit(Opcode::Nip, &[]);
6006        self.emit(Opcode::Nip, &[]);
6007        // This is the delegate finishing on the caller's `return(v)`, so it is a `return`
6008        // from the body's point of view: `emit_return(s, TRUE)` in the reference, which
6009        // awaits the value in an async generator and then runs the same `finally`/iterator
6010        // unwinding a written `return` would. Skipping the unwinding made
6011        // `try { yield* xs } finally { … }` return early and leave the `finally` unrun.
6012        if is_async {
6013            self.emit(Opcode::Await, &[]);
6014        }
6015        self.emit_unwind_for_return(true);
6016        self.emit(Opcode::ReturnAsync, &[]);
6017
6018        // `throw(e)`: forward it into the inner iterator.
6019        self.place_label(throw_no_method);
6020        self.emit(Opcode::IteratorCall, &[Op::Int(1)]);
6021        let no_throw = self.new_label();
6022        self.emit_jump(Opcode::IfTrue, no_throw, &[]);
6023        if is_async {
6024            self.emit(Opcode::Await, &[]);
6025        }
6026        self.emit(Opcode::IteratorCheckObject, &[]);
6027        self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text("done"))]);
6028        self.emit_jump(Opcode::IfFalse, resume, &[]);
6029        self.emit_jump(Opcode::Goto, done, &[]);
6030        // No `throw` method: close the iterator, then report the spec's TypeError. The
6031        // `if_true` before the `await` is the reference's shape — the flag it consumes is
6032        // what `iterator_call` leaves behind, and a close that *did* find no `return`
6033        // method has nothing to await.
6034        self.place_label(no_throw);
6035        self.emit(Opcode::IteratorCall, &[Op::Int(2)]);
6036        let no_close = self.new_label();
6037        self.emit_jump(Opcode::IfTrue, no_close, &[]);
6038        if is_async {
6039            self.emit(Opcode::Await, &[]);
6040        }
6041        self.place_label(no_close);
6042        self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(4)]);
6043
6044        // The inner iterator finished: the delegate's value is the `yield*` expression's
6045        // value, so it is left on the stack for whatever consumes it.
6046        self.place_label(done);
6047        self.emit(Opcode::GetField, &[Op::Atom(Atom::from_text("value"))]);
6048        self.emit(Opcode::Nip, &[]);
6049        self.emit(Opcode::Nip, &[]);
6050        self.emit(Opcode::Nip, &[]);
6051        Ok(())
6052    }
6053
6054    /// `await expr`: exactly one instruction.
6055    ///
6056    /// No resume-magic branch follows it. The reference's `await` leaves a single value
6057    /// on the stack and completion is signalled by the `return_async` at the end of the
6058    /// body; an `if_false`/`return_async` pair here would be an instruction sequence the
6059    /// reference never emits, and a `for await` loop — which reaches `await` through the
6060    /// same opcode — would then spill a value the loop's unpacking does not expect.
6061    fn await_expression(&mut self, argument: &Expr) -> Result<(), SyntaxError> {
6062        self.expr(argument)?;
6063        self.emit(Opcode::Await, &[]);
6064        self.state().has_await = true;
6065        Ok(())
6066    }
6067
6068    /// The `super` base: the receiver followed by the home object's prototype.
6069    ///
6070    /// Everything `super` does needs both. A *read* starts at the prototype but reports
6071    /// to the receiver (so a getter sees `this`), and a *call* reads the method off the
6072    /// prototype but calls it with the receiver.
6073    fn super_base(&mut self) {
6074        self.this_expression();
6075        self.home_object();
6076        self.emit(Opcode::GetSuper, &[]);
6077    }
6078
6079    /// `[[HomeObject]]` as `super` sees it.
6080    ///
6081    /// A method, a constructor and a field initialiser each carry one — `set_home_object`
6082    /// put it there — so for them the special object *is* the answer. An arrow and a
6083    /// static block have none: they read the enclosing function's, which has to be
6084    /// materialised into a local, exactly as `this` is for an arrow.
6085    ///
6086    /// The name matches what the reference stores, so the disassembly agrees; it is not a
6087    /// name any program can write.
6088    fn home_object(&mut self) {
6089        if !self.cur().is_arrow {
6090            self.emit(Opcode::SpecialObject, &[Op::Int(4)]);
6091            return;
6092        }
6093        if let Some(target) = self.enclosing_function() {
6094            self.state_at(target).needs_home_object_local = true;
6095            self.declare_at(target, HOME_OBJECT);
6096        }
6097        self.emit_var(VarAction::Get, HOME_OBJECT);
6098    }
6099
6100    /// `super(args)`: construct the parent class and adopt the result as `this`.
6101    ///
6102    /// The parent is the prototype of the constructor that is running, which is exactly
6103    /// what `extends` set up. `new.target` is passed through unchanged so that
6104    /// `new.target` inside the parent is the class actually being constructed.
6105    fn super_call(&mut self, arguments: &[Expr]) -> Result<(), SyntaxError> {
6106        self.active_func_expression();
6107        self.emit(Opcode::GetSuper, &[]);
6108        self.new_target_expression();
6109        if Self::has_spread(arguments) {
6110            self.argument_array(arguments)?;
6111            self.emit(Opcode::Apply, &[Op::Int(1)]);
6112        } else {
6113            for argument in arguments {
6114                self.expr(argument)?;
6115            }
6116            self.emit(Opcode::CallConstructor, &[Op::Int(arguments.len() as i32)]);
6117        }
6118        // The value stays on the stack: `super()` is an expression, and a derived
6119        // constructor's `this` may only be initialised once.
6120        self.emit(Opcode::Dup, &[]);
6121        self.emit_var(VarAction::PutInitChecked, "this");
6122        // Instance fields are installed here, not at the top of the body: a derived
6123        // constructor has no `this` to install them on until `super()` returns. The
6124        // reference emits the same call at every `super()` site.
6125        self.call_field_initialiser();
6126        Ok(())
6127    }
6128
6129    /// `this` as a local, which every class constructor and field initialiser needs.
6130    ///
6131    /// The reference materialises the receiver into a local rather than reading
6132    /// `push_this` inline, because `super()` in a derived constructor *replaces* `this`
6133    /// and a field initialiser has to see the final value.
6134    fn begin_this_local(&mut self) {
6135        self.declare_hidden_local("this", VarKind::Normal);
6136        self.emit(Opcode::PushThis, &[]);
6137        self.emit_var(VarAction::Put, "this");
6138        // The store is already at the top of the body, so `provide_this_local` has
6139        // nothing left to prepend. Without this the initialiser ended up with
6140        // `push_this; put_loc0 this` twice whenever the class also held a field
6141        // initialiser whose body read `this` through an arrow.
6142        self.state().has_this_prologue = true;
6143    }
6144
6145    /// Compile a constructor the class wrote.
6146    ///
6147    /// The flags have to be in place before the body is compiled, but
6148    /// `compile_function_with_name` creates its own state — so the caller's state is
6149    /// marked instead and the new one inherits it. That is the same trick the parameter
6150    /// prologue uses, and it keeps one code path for both.
6151    fn compile_class_constructor(
6152        &mut self,
6153        func: &ast::Function,
6154        has_heritage: bool,
6155    ) -> Result<CompiledFunction, SyntaxError> {
6156        let saved = self.cur().ctor_kind;
6157        self.state().class_ctor_pending = Some(if has_heritage {
6158            CtorKind::Derived
6159        } else {
6160            CtorKind::Base
6161        });
6162        let result = self.compile_function_with_name(func, false);
6163        self.state().ctor_kind = saved;
6164        self.state().class_ctor_pending = None;
6165        result
6166    }
6167
6168    /// The constructor a class gets when it does not declare one.
6169    ///
6170    /// A base class's is empty; a derived class's forwards every argument to the parent
6171    /// and is expressed by `init_ctor`, which also keeps `new.target`. Both run the
6172    /// instance field initialiser afterwards when the class has fields, which is why the
6173    /// initialiser is captured rather than inlined.
6174    fn compile_implicit_constructor(
6175        &mut self,
6176        class: &Class,
6177        has_heritage: bool,
6178    ) -> Result<CompiledFunction, SyntaxError> {
6179        self.compile_synthetic_function(
6180            "",
6181            true,
6182            Span::new(class.body_end, class.body_end),
6183            |compiler| {
6184                if has_heritage {
6185                    // A derived constructor's `this` does not exist until `super()` returns,
6186                    // so it starts in the dead zone and `init_ctor` fills it.
6187                    compiler.declare("this", VarDef::lexical("this"));
6188                    compiler.emit(
6189                        Opcode::SetLocUninitialized,
6190                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6191                    );
6192                    compiler.emit(Opcode::InitCtor, &[]);
6193                    compiler.emit(
6194                        Opcode::PutLocCheckInit,
6195                        &[Op::Slot(Slot::Loc(compiler.cur().vars.len() as u32 - 1))],
6196                    );
6197                } else {
6198                    compiler.begin_this_local();
6199                    compiler.emit(Opcode::CheckCtor, &[]);
6200                }
6201                compiler.call_field_initialiser();
6202                // A derived constructor returns `this`, the object `super()` built. Without
6203                // this the implicit constructor fell through to `return_undef`, and `new B()`
6204                // handed back the empty object `construct` had made instead of the one the
6205                // parent constructor initialised.
6206                if has_heritage {
6207                    compiler.emit_var(VarAction::Get, "this");
6208                    compiler.emit(Opcode::Return, &[]);
6209                }
6210                Ok(())
6211            },
6212        )
6213    }
6214
6215    /// Emit the call to `<class_fields_init>`, guarded by an `undefined` test.
6216    ///
6217    /// A class with no instance fields leaves the binding `undefined`, and calling it
6218    /// would throw; the reference emits the same guard rather than branching at compile
6219    /// time because a class can be extended by a subclass whose fields still have to run.
6220    fn call_field_initialiser(&mut self) {
6221        let skip = self.new_label();
6222        self.emit_var(VarAction::Get, "<class_fields_init>");
6223        self.emit(Opcode::Dup, &[]);
6224        self.emit_jump(Opcode::IfFalse, skip, &[]);
6225        self.emit_var(VarAction::Get, "this");
6226        self.emit(Opcode::Swap, &[]);
6227        self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6228        self.place_label(skip);
6229        self.emit(Opcode::Drop, &[]);
6230    }
6231
6232    /// The function that defines one class's fields on `this`, and runs its static blocks.
6233    ///
6234    /// `define_field` rather than `put_field`: a field is an own property created
6235    /// without consulting a setter on the prototype, so `class C { set x(v){} }` with an
6236    /// `x = 1` field must not call the setter.
6237    ///
6238    /// One function serves the whole class: it is called once per instance (or once, for
6239    /// the static half) and walks the members in source order. Static blocks are compiled
6240    /// into the same function because they *are* part of the same sequence — `static a =
6241    /// 1; static { }` and `static { this.a = 1 }; static a = 2` leave `a` holding
6242    /// different values, so the two kinds cannot be split apart.
6243    fn compile_field_initialiser(
6244        &mut self,
6245        items: &[StaticInitItem<'_>],
6246        span: Span,
6247        instance: bool,
6248        add_brand: bool,
6249    ) -> Result<CompiledFunction, SyntaxError> {
6250        self.compile_synthetic_function("", true, span, |compiler| {
6251            // A field initialiser and a static block are not functions, so neither has an
6252            // `arguments` of its own; see `FnState::no_arguments_binding`.
6253            let current = compiler.stack.len() - 1;
6254            compiler.stack[current].no_arguments_binding = true;
6255            if instance {
6256                // An instance initialiser always carries a `<home_object>` local, because the
6257                // brand block below reads it — even when that block turns out to be dead. The
6258                // reference has the same artefact, and the store is visible in its dump.
6259                let current = compiler.stack.len() - 1;
6260                compiler.stack[current].needs_home_object_local = true;
6261            }
6262            compiler.begin_this_local();
6263            if instance {
6264                // `this` gets the brand the prototype created, before any field is defined —
6265                // which is what makes `#m()` usable from inside a field initialiser.
6266                //
6267                // The reference always emits `push_false; if_false L; this; home; add_brand;
6268                // L:` and patches the `push_false` to `push_true` from the class parse when
6269                // the class has private methods; either way the branch folds, but the *mark*
6270                // it leaves (a `goto`) is what keeps the `put_loc`/`get_loc` pair around the
6271                // `this` local from being fused into a `set_loc`.
6272                let skip = compiler.new_label();
6273                if add_brand {
6274                    compiler.emit(Opcode::PushTrue, &[]);
6275                } else {
6276                    compiler.emit(Opcode::PushFalse, &[]);
6277                }
6278                compiler.emit_jump(Opcode::IfFalse, skip, &[]);
6279                compiler.emit_var(VarAction::Get, "this");
6280                compiler.emit_var(VarAction::Get, HOME_OBJECT);
6281                compiler.emit(Opcode::AddBrand, &[]);
6282                compiler.place_label(skip);
6283            }
6284            for item in items {
6285                match item {
6286                    StaticInitItem::Field(key, value) => {
6287                        // A private field is *defined*, not assigned: `define_private_field`
6288                        // reads `obj symbol value`, and its point is that it fails on a
6289                        // receiver that is not this class's — which `put_field` would not.
6290                        //
6291                        // The three shapes are the reference's: `define_field <atom>` for a
6292                        // static name, `define_array_el` for a key that is only known at run
6293                        // time (`obj key value`), `define_private_field` for `#x`, and a
6294                        // computed key is read from its binding rather than recomputed.
6295                        compiler.emit_var(VarAction::Get, "this");
6296                        match key {
6297                            FieldKey::Private(binding) | FieldKey::Computed(binding) => {
6298                                compiler.emit_var(VarAction::Get, binding);
6299                            }
6300                            FieldKey::Literal(_) => {}
6301                        }
6302                        match value {
6303                            Some(value) => {
6304                                compiler.expr(value)?;
6305                                // A field initialiser is a `NamedEvaluation` target:
6306                                // `x = function(){}` names the function `"x"`, and a private
6307                                // field keeps its `#` (`static #f = () => 1` is named
6308                                // `"#f"` (elements/static-field-anonymous-function-name).
6309                                match key {
6310                                    FieldKey::Literal(literal) => {
6311                                        let text = compiler.property_key_text(literal, span)?;
6312                                        compiler.set_name_if_anonymous(value, &text);
6313                                    }
6314                                    FieldKey::Private(binding) => {
6315                                        compiler.set_name_if_anonymous(value, &Wtf8::new(binding));
6316                                    }
6317                                    // The key is a value on the stack, and `set_name_computed`
6318                                    // is exactly the instruction for that.
6319                                    FieldKey::Computed(_) => {
6320                                        compiler.set_name_if_anonymous_computed(value);
6321                                    }
6322                                }
6323                            }
6324                            None => compiler.emit(Opcode::Undefined, &[]),
6325                        }
6326                        match key {
6327                            FieldKey::Literal(literal) => {
6328                                let text = compiler.property_key_text(literal, span)?;
6329                                compiler
6330                                    .emit(Opcode::DefineField, &[Op::Atom(Atom::from_wtf8(&text))]);
6331                            }
6332                            FieldKey::Computed(_) => {
6333                                compiler.emit(Opcode::DefineArrayEl, &[]);
6334                                // `define_array_el` leaves `obj key`; the key is consumed by
6335                                // the copy the pattern machinery wants, so both go.
6336                                compiler.emit(Opcode::Drop, &[]);
6337                            }
6338                            FieldKey::Private(_) => {
6339                                compiler.emit(Opcode::DefinePrivateField, &[]);
6340                            }
6341                        }
6342                        compiler.emit(Opcode::Drop, &[]);
6343                    }
6344                    StaticInitItem::Block { body, body_start } => {
6345                        let block = compiler.compile_static_block(body, *body_start)?;
6346                        let index = compiler.push_constant(Constant::Function(Box::new(block)));
6347                        // `this fclosure`, so `call_method` finds the receiver below the
6348                        // callee: the block runs with `this` bound to the class.
6349                        compiler.emit(Opcode::Fclosure, &[Op::Const(index)]);
6350                        compiler.emit_var(VarAction::Get, "this");
6351                        compiler.emit(Opcode::Swap, &[]);
6352                        compiler.emit(Opcode::CallMethod, &[Op::Int(0)]);
6353                        // Nothing the block evaluates is wanted; its effects are the point.
6354                        compiler.emit(Opcode::Drop, &[]);
6355                    }
6356                }
6357            }
6358            Ok(())
6359        })
6360    }
6361
6362    /// Compile a `static { … }` body into the function the class calls for it.
6363    ///
6364    /// Shaped like an arrow, because that is the one function form with no `this`,
6365    /// `new.target` or `arguments` of its own: all three reach the enclosing static
6366    /// initialiser, and through it the class. `arguments` never gets that far — the parser
6367    /// rejects the reference — but `this` and `super` both depend on it.
6368    ///
6369    /// The body is hoisted like a function body's, because the reference parses it as one:
6370    /// `var` inside a block is a local of the block's function, not of whatever encloses
6371    /// the class.
6372    fn compile_static_block(
6373        &mut self,
6374        body: &[Stmt],
6375        body_start: Position,
6376    ) -> Result<CompiledFunction, SyntaxError> {
6377        let mut state = FnState::new(String::new(), FunctionKind::Normal);
6378        // Class bodies are strict, so a static block is too.
6379        state.strict = true;
6380        // The one property that makes this an arrow: nothing of its own to bind `this` to,
6381        // so `this` and `super` come from the initialiser that calls it.
6382        state.is_arrow = true;
6383        state.created_in_block = self.cur().current_block;
6384        state.with_names = self.cur().with_names.clone();
6385        state.line = body_start.line;
6386        state.column = body_start.column;
6387        let depth = self.stack.len();
6388        self.stack.push(state);
6389        let body_key = body_start.offset as u64;
6390        self.push_block(body_key, NO_PARENT);
6391        self.state().body_block = body_key;
6392        let result = (|| {
6393            self.hoist(body, body_key)?;
6394            self.emit_scope_enter(body_key);
6395            for statement in body {
6396                self.stmt(statement)?;
6397            }
6398            if self.end_is_reachable() {
6399                self.emit(Opcode::ReturnUndef, &[]);
6400            }
6401            Ok(())
6402        })();
6403        if result.is_err() {
6404            self.stack.truncate(depth);
6405            return result.map(|()| unreachable!());
6406        }
6407        Ok(self.finish_current())
6408    }
6409
6410    /// Compile a class, leaving the constructor on the stack when `keep`.
6411    ///
6412    /// The shape follows the reference: the class body is its own scope holding the
6413    /// class's *inner* name as a `const` — which is what lets a method refer to the
6414    /// class by name — plus a `<class_fields_init>` binding for the initialiser function.
6415    /// `define_class` turns `parent ctor` into `ctor proto`, then the members are defined
6416    /// on the top of the stack: the prototype for instance members, the constructor
6417    /// itself for `static` ones, which is why a static member costs an extra `swap`.
6418    fn class_definition(&mut self, class: &Class, keep: bool) -> Result<(), SyntaxError> {
6419        let parent_block = self.cur().current_block;
6420        let key = class.span.start.offset as u64;
6421        self.push_block(key, parent_block);
6422        let name = class.name.as_ref().map(|ident| ident.name.clone());
6423        // The class's own name is bound inside the body, so `class E { static F(){ return E } }`
6424        // resolves `E` without a global lookup. An *unnamed* class expression has no such
6425        // binding, and `define_class` is handed the empty name.
6426        if let Some(name) = &name {
6427            self.declare(name, VarDef::constant(name.clone()));
6428        }
6429        self.emit_scope_enter(key);
6430
6431        // The heritage clause is evaluated outside the class's own scope: it cannot see
6432        // the class binding it is about to initialise.
6433        let saved_block = self.cur().current_block;
6434        self.state().current_block = parent_block;
6435        match &class.super_class {
6436            Some(parent) => self.expr(parent)?,
6437            None => self.emit(Opcode::Undefined, &[]),
6438        }
6439        self.state().current_block = saved_block;
6440        let has_heritage = class.super_class.is_some();
6441
6442        // `<class_fields_init>` is declared *after* the heritage, so its dead-zone mark
6443        // lands after the heritage's code — which is where the reference puts it, because it
6444        // calls `define_var(..., JS_VAR_DEF_CONST)` at that point rather than at class entry.
6445        // Declaring it before `emit_scope_enter` instead put both marks at the class entry,
6446        // and `block_vars_reversed` prints a block's bindings backwards, so the two lines
6447        // came out in the opposite order from the reference's.
6448        //
6449        // `const`, as in `define_var(..., JS_VAR_DEF_CONST)`: the binding is filled exactly
6450        // once, through `put_var_init`/`scope_put_var_init` — the *initialising* store, which
6451        // a const accepts — so the old comment's worry ("a const would refuse the second
6452        // store") did not apply: there is no second store.
6453        // Every `#name` the class declares gets a `const` binding in the class scope, and so
6454        // does every computed field key. That is how the reference does it
6455        // (`add_private_class_field` → `add_scope_var` with `is_lexical`/`is_const`), and it is
6456        // what makes a private name resolve like any other class-scope variable — including
6457        // through a nested function's closure — while remaining invisible outside.
6458        //
6459        // All of them are declared *before* `<class_fields_init>`, in member order, because
6460        // that is when the reference's parser creates them.
6461        let plan = ClassPlan::build(class);
6462        // The body's private names are visible from here to the end of the class, and shadow
6463        // any outer class's of the same spelling. Pushed *before* the constructor is compiled
6464        // — it is compiled first because `define_class` consumes it, but its body can name
6465        // `#x` like any other member's.
6466        self.private_scopes.push(plan.uses.clone());
6467        let mut class_slots: Vec<u32> = Vec::with_capacity(plan.bindings.len());
6468        for binding in &plan.bindings {
6469            class_slots.push(self.declare(binding, VarDef::constant(binding.clone())));
6470        }
6471        let fci = self.declare(
6472            "<class_fields_init>",
6473            VarDef::constant("<class_fields_init>"),
6474        );
6475        // Dead-zone marks in reverse slot order, which is how `enter_scope` emits a scope's
6476        // lexical bindings — so `<class_fields_init>` (the highest) is marked first and the
6477        // members' bindings follow in reverse.
6478        self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(fci))]);
6479        for slot in class_slots.iter().rev() {
6480            self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(*slot))]);
6481        }
6482
6483        // The constructor is compiled before `define_class` because that instruction
6484        // consumes it; a class without one gets the implicit version.
6485        let constructor = class.elements.iter().find_map(|element| match element {
6486            ClassElement::Method {
6487                kind: MethodKind::Constructor,
6488                func,
6489                ..
6490            } => Some(&**func),
6491            _ => None,
6492        });
6493        // A constructor is compiled differently from a method: it owns `this`. The flags
6494        // go on the *enclosing* state because a constructor is a nested function and
6495        // `compile_function_with_name` starts a fresh one.
6496        let ctor = match constructor {
6497            Some(func) => self.compile_class_constructor(func, has_heritage)?,
6498            None => self.compile_implicit_constructor(class, has_heritage)?,
6499        };
6500        // A closure, not the bare constant: the constructor captures
6501        // `<class_fields_init>`, which is only filled after `define_class` has run, so it
6502        // has to hold the cell rather than a copy of its value.
6503        //
6504        // The pool slot is left unassigned for now, because the reference gives the
6505        // constructor the *last* index of the members' range: `js_parse_class` emits a
6506        // `push_const` whose operand is patched at the end of the class parse, after every
6507        // method has taken a slot. Emitting the members first and the constant second is how
6508        // the numbering comes out the same; the instruction itself stays where it is.
6509        let ctor_insn = self.cur().insns.len();
6510        self.emit(Opcode::Fclosure, &[Op::Const(CTOR_INDEX_PLACEHOLDER)]);
6511        let flags = if has_heritage { 1 } else { 0 };
6512        self.emit(
6513            Opcode::DefineClass,
6514            &[
6515                Op::Atom(Atom::from_text(name.as_deref().unwrap_or(""))),
6516                Op::Int(flags),
6517            ],
6518        );
6519
6520        // Instance fields and static fields are two different functions: the first runs
6521        // per instance from the constructor, the second runs once, here.
6522        let mut instance_fields: Vec<StaticInitItem<'_>> = Vec::new();
6523        let mut static_items: Vec<StaticInitItem<'_>> = Vec::new();
6524        for (index, element) in class.elements.iter().enumerate() {
6525            match element {
6526                ClassElement::Method {
6527                    key: member_key,
6528                    is_static,
6529                    kind,
6530                    func,
6531                    span,
6532                } => {
6533                    if *kind == MethodKind::Constructor {
6534                        continue;
6535                    }
6536                    // `static(x)` is a *method* named `static`, not a static method; the
6537                    // parser already decided which by putting it in `kind`.
6538                    if *is_static {
6539                        self.emit(Opcode::Swap, &[]);
6540                    }
6541                    // A computed key is evaluated *here*, before the method's closure
6542                    // exists, and stays under it: `define_method_computed` pops
6543                    // `function, key, object`, so the stack has to read
6544                    // `[class, prototype, key, function]`. Evaluating the key after the
6545                    // `fclosure` and swapping the two put the prototype *below* the
6546                    // closure, which defined the method on the function and lost the
6547                    // prototype: `class C { [k]() {} }` left `C` undefined. The order is
6548                    // also the spec's — a class body evaluates every element's name before
6549                    // that element's function.
6550                    if let PropName::Computed(key) = member_key {
6551                        self.expr(key)?;
6552                    }
6553                    let function = self.compile_function_with_name(func, true)?;
6554                    let index = self.push_constant(Constant::Function(Box::new(function)));
6555                    self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6556                    match member_key {
6557                        // A private method is not a property of the prototype: it is a
6558                        // closure in the class scope, which is why nothing outside can reach
6559                        // it and why a use site has to brand-check. `set_name` gives the
6560                        // function its `name` (`#m`), which an accessor does not get — the
6561                        // reference leaves that commented out.
6562                        PropName::Private(ident) => {
6563                            let name = format!("#{}", ident.name);
6564                            // `set_home_object` first: the brand check reads the function's
6565                            // home object, and for a method that is the prototype.
6566                            self.emit(Opcode::SetHomeObject, &[]);
6567                            let binding = if *kind == MethodKind::Set {
6568                                format!("{name}<set>")
6569                            } else {
6570                                name.clone()
6571                            };
6572                            if *kind == MethodKind::Method {
6573                                self.emit(Opcode::SetName, &[Op::Atom(Atom::from_text(&name))]);
6574                            }
6575                            self.emit_var(VarAction::PutInit, &binding);
6576                        }
6577                        PropName::Computed(_) => {
6578                            self.emit(
6579                                Opcode::DefineMethodComputed,
6580                                &[Op::Int(class_method_flags(*kind))],
6581                            );
6582                        }
6583                        PropName::Literal(literal) => {
6584                            let text = self.property_key_text(literal, *span)?;
6585                            self.emit(
6586                                Opcode::DefineMethod,
6587                                &[
6588                                    Op::Atom(Atom::from_wtf8(&text)),
6589                                    Op::Int(class_method_flags(*kind)),
6590                                ],
6591                            );
6592                        }
6593                    }
6594                    if *is_static {
6595                        self.emit(Opcode::Swap, &[]);
6596                    }
6597                }
6598                ClassElement::Field {
6599                    key: field_key,
6600                    is_static,
6601                    value,
6602                    ..
6603                } => {
6604                    // A private field's *symbol* is created here, at the member, and stored
6605                    // in its binding: the field's property is keyed by it, so it has to exist
6606                    // before any initialiser runs, and a fresh one per class body is what
6607                    // makes two classes that both write `#x` independent.
6608                    //
6609                    // A computed key is evaluated once, here, and `to_propkey`'d once — a key
6610                    // whose `toString` has a side effect must not run again per instance.
6611                    let key = match field_key {
6612                        PropName::Private(ident) => {
6613                            let binding = format!("#{}", ident.name);
6614                            if *is_static {
6615                                self.emit(Opcode::Swap, &[]);
6616                            }
6617                            self.emit(
6618                                Opcode::PrivateSymbol,
6619                                &[Op::Atom(Atom::from_text(&binding))],
6620                            );
6621                            self.emit_var(VarAction::PutInit, &binding);
6622                            if *is_static {
6623                                self.emit(Opcode::Swap, &[]);
6624                            }
6625                            FieldKey::Private(binding)
6626                        }
6627                        PropName::Computed(expression) => {
6628                            let binding = plan
6629                                .computed
6630                                .get(&index)
6631                                .cloned()
6632                                .expect("every computed key got a binding");
6633                            if *is_static {
6634                                self.emit(Opcode::Swap, &[]);
6635                            }
6636                            self.expr(expression)?;
6637                            self.emit(Opcode::ToPropkey, &[]);
6638                            self.emit_var(VarAction::PutInit, &binding);
6639                            if *is_static {
6640                                self.emit(Opcode::Swap, &[]);
6641                            }
6642                            FieldKey::Computed(binding)
6643                        }
6644                        PropName::Literal(literal) => FieldKey::Literal(literal),
6645                    };
6646                    if *is_static {
6647                        static_items.push(StaticInitItem::Field(key, value.as_deref()));
6648                    } else {
6649                        instance_fields.push(StaticInitItem::Field(key, value.as_deref()));
6650                    }
6651                }
6652                ClassElement::StaticBlock {
6653                    body, body_start, ..
6654                } => static_items.push(StaticInitItem::Block {
6655                    body,
6656                    body_start: *body_start,
6657                }),
6658            }
6659        }
6660
6661        // Now that every member has its slot, the constructor can have the next one and the
6662        // `fclosure` above can name it.
6663        let ctor_index = self.push_constant(Constant::Function(Box::new(ctor)));
6664        match self.state().insns.get_mut(ctor_insn) {
6665            Some(Insn::Fixed { operands, .. }) => {
6666                operands[0] = Op::Const(ctor_index);
6667            }
6668            // `emit` always pushes exactly one `Insn::Fixed`, so this cannot happen; failing
6669            // loudly beats emitting a `fclosure` of slot 4294967295.
6670            _ => {
6671                return Err(SyntaxError::new(
6672                    "the class constructor's fclosure went missing",
6673                    class.span,
6674                ));
6675            }
6676        }
6677
6678        // The instance brand: a symbol created once on the prototype, which every instance
6679        // then carries. `add_brand(obj, home)` reads `home` for the symbol (creating it the
6680        // first time) and adds it to `obj` — here `obj` is `null`, so only the prototype's
6681        // copy is created. The prototype is on top of the stack at this point.
6682        if plan.instance_brand {
6683            self.emit(Opcode::Dup, &[]);
6684            self.emit(Opcode::Null, &[]);
6685            self.emit(Opcode::Swap, &[]);
6686            self.emit(Opcode::AddBrand, &[]);
6687        }
6688
6689        // `<class_fields_init>` holds the instance initialiser, or `undefined` when the
6690        // class has no instance fields. The constructor calls it only when it is defined.
6691        //
6692        // A class with private *methods* but no fields still needs one, because adding the
6693        // brand to each new instance is the initialiser's job.
6694        if instance_fields.is_empty() && !plan.instance_brand {
6695            self.emit(Opcode::Undefined, &[]);
6696        } else {
6697            let initialiser = self.compile_field_initialiser(
6698                &instance_fields,
6699                class.span,
6700                true,
6701                plan.instance_brand,
6702            )?;
6703            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6704            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6705            // `set_home_object` reads `obj func`, so the prototype stays where it is.
6706            self.emit(Opcode::SetHomeObject, &[]);
6707        }
6708        self.emit_var(VarAction::PutInit, "<class_fields_init>");
6709        // The prototype has done its job: every instance member is defined on it. What
6710        // is left under it is the constructor.
6711        self.emit(Opcode::Drop, &[]);
6712
6713        // The static brand, for `static #m() {}`: same opcode, but the home object is the
6714        // constructor itself, so the symbol lands on the class and the class carries it.
6715        if plan.static_brand {
6716            self.emit(Opcode::Dup, &[]);
6717            self.emit(Opcode::Dup, &[]);
6718            self.emit(Opcode::AddBrand, &[]);
6719        }
6720
6721        // The class binding is initialised *before* static fields run, so a static field
6722        // can refer to the class by name (`static y = S.x`).
6723        // `set_loc` leaves the constructor on the stack, which is what the static field
6724        // call and the outer store both consume.
6725        //
6726        // Only when there *is* such a binding: an anonymous class expression declares no
6727        // class-scope name, and asking for one by the empty string resolved to nothing —
6728        // which made `var x = class {}` assign `undefined` and put a bogus global store in
6729        // the instruction stream.
6730        if let Some(name) = &name {
6731            self.emit_var(VarAction::SetInit, name);
6732        }
6733        if !static_items.is_empty() {
6734            // The static half has no brand prologue of its own: the constructor got its
6735            // brand above, before this runs.
6736            let initialiser =
6737                self.compile_field_initialiser(&static_items, class.span, false, false)?;
6738            let index = self.push_constant(Constant::Function(Box::new(initialiser)));
6739            self.emit(Opcode::Dup, &[]);
6740            self.emit(Opcode::Fclosure, &[Op::Const(index)]);
6741            self.emit(Opcode::SetHomeObject, &[]);
6742            self.emit(Opcode::CallMethod, &[Op::Int(0)]);
6743            self.emit(Opcode::Drop, &[]);
6744        }
6745        // The body is over, and with it this class's private names.
6746        let _ = self.private_scopes.pop();
6747        self.emit_scope_leave(key);
6748        self.state().current_block = parent_block;
6749        if keep {
6750            // A class *expression* is its own value; the class-scope binding was only
6751            // ever an alias for it.
6752            return Ok(());
6753        }
6754        // A declaration stores into the binding the enclosing statement declared.
6755        self.emit_var(VarAction::PutInit, &name.unwrap_or_default());
6756        Ok(())
6757    }
6758
6759    fn push_this(&mut self) {
6760        self.emit(Opcode::PushThis, &[]);
6761    }
6762
6763    /// `this`, which an arrow does not have of its own.
6764    ///
6765    /// The reference gives the enclosing function a local named `this`, initialised from
6766    /// `push_this` at the top of its body, and the arrow then reads it as a captured
6767    /// variable. That is why `(() => this)()` inside `f` yields `f`'s receiver even when
6768    /// the arrow is called with none.
6769    fn this_expression(&mut self) {
6770        // In a class constructor `this` is a local: a derived constructor only gets one
6771        // when `super()` returns, and reading the raw receiver would give the *outer*
6772        // one instead.
6773        if self.cur().ctor_kind != CtorKind::None {
6774            self.emit_var(VarAction::Get, "this");
6775            return;
6776        }
6777        if !self.cur().is_arrow {
6778            self.push_this();
6779            return;
6780        }
6781        // An arrow at the **top level** of a script or module has no enclosing function,
6782        // but it still inherits `this` — the script's or module's own. Falling through to
6783        // `emit_var(Get, "this")` without a target made that a *global* lookup, so
6784        // `var f = () => typeof this` at top level reported
6785        // `ReferenceError: 'this' is not defined` instead of `"object"`
6786        // (`Set/prototype/forEach/this-arg-explicit-cannot-override-lexical-this-arrow`
6787        // is the test262 case that reaches it, through a native `forEach`).
6788        //
6789        // The script state is the bottom of the stack, so it is the fallback target. Its
6790        // own `provide_this_local` then prepends the `push_this` the arrow reads.
6791        let target = self.enclosing_function().unwrap_or(0);
6792        self.state_at(target).needs_this_local = true;
6793        self.declare_at(target, "this");
6794        self.emit_var(VarAction::Get, "this");
6795    }
6796
6797    /// `new.target`, which an arrow likewise does not own.
6798    fn new_target_expression(&mut self) {
6799        if !self.cur().is_arrow {
6800            self.emit(Opcode::SpecialObject, &[Op::Int(3)]);
6801            return;
6802        }
6803        if let Some(target) = self.enclosing_function() {
6804            self.state_at(target).needs_new_target_local = true;
6805            self.declare_at(target, NEW_TARGET);
6806        }
6807        self.emit_var(VarAction::Get, NEW_TARGET);
6808    }
6809
6810    /// `this.active_func`: the function `super()` resolves against.
6811    ///
6812    /// In a constructor or a method that is the function being run, so the special object
6813    /// answers directly. In an arrow it is whatever the enclosing function saw, read out of
6814    /// a closure variable — see [`FnState::needs_active_func_local`].
6815    fn active_func_expression(&mut self) {
6816        if !self.cur().is_arrow {
6817            self.emit(Opcode::SpecialObject, &[Op::Int(2)]);
6818            return;
6819        }
6820        if let Some(target) = self.enclosing_function() {
6821            self.state_at(target).needs_active_func_local = true;
6822            self.declare_at(target, ACTIVE_FUNC);
6823        }
6824        self.emit_var(VarAction::Get, ACTIVE_FUNC);
6825    }
6826
6827    /// Give the function a local `<active_func>`, for an arrow inside it to capture.
6828    fn provide_active_func_local(&mut self) {
6829        let current = self.stack.len() - 1;
6830        if !self.stack[current].needs_active_func_local {
6831            return;
6832        }
6833        if !self.stack[current]
6834            .vars
6835            .iter()
6836            .any(|var| var.name == ACTIVE_FUNC)
6837        {
6838            self.declare_hidden_local(ACTIVE_FUNC, VarKind::Normal);
6839        }
6840        self.prepend_initialiser(
6841            ACTIVE_FUNC,
6842            Insn::Fixed {
6843                op: Opcode::SpecialObject,
6844                operands: vec![Op::Int(2)],
6845            },
6846        );
6847    }
6848
6849    /// Give the function a local `new.target`, for an arrow inside it to capture.
6850    fn provide_new_target_local(&mut self) {
6851        let current = self.stack.len() - 1;
6852        if !self.stack[current].needs_new_target_local {
6853            return;
6854        }
6855        if !self.stack[current]
6856            .vars
6857            .iter()
6858            .any(|var| var.name == NEW_TARGET)
6859        {
6860            self.declare_hidden_local(NEW_TARGET, VarKind::Normal);
6861        }
6862        self.prepend_initialiser(
6863            NEW_TARGET,
6864            Insn::Fixed {
6865                op: Opcode::SpecialObject,
6866                operands: vec![Op::Int(3)],
6867            },
6868        );
6869    }
6870
6871    /// `arguments` reached from an arrow, which likewise belongs to the enclosing
6872    /// function.
6873    fn ensure_enclosing_arguments(&mut self) {
6874        // An arrow created in a parameter list needs the *parameter* scope's
6875        // `arguments`, not the body's: the two are separate bindings and the arrow was
6876        // born before the body existed.
6877        let from_params = self.cur().created_in_params;
6878        if let Some(target) = self.enclosing_function() {
6879            self.state_at(target).needs_arguments_local = true;
6880            if from_params {
6881                self.state_at(target).needs_param_arguments = true;
6882                // Declare it now, not at the enclosing function's `finish_current`: the
6883                // arrow resolves its own `arguments` before that runs, and a binding that
6884                // does not exist yet resolves as a global.
6885                declare_param_var_at(&mut self.stack[target], "arguments");
6886            }
6887            self.declare_at(target, "arguments");
6888        }
6889    }
6890
6891    /// The innermost enclosing frame that is a real function — an arrow inherits from it
6892    /// rather than starting a scope of its own.
6893    /// The innermost enclosing frame that can own a lexical binding an arrow reads —
6894    /// a real function, or a **script** top level.
6895    ///
6896    /// A script is in the list because an `eval` body is compiled as one and an arrow
6897    /// written in eval'd code still has to find the caller's `new.target`, `this.active_func`
6898    /// and `[[HomeObject]]`. Excluding it made `eval("() => new.target")` compile the read as
6899    /// a *global* lookup of `new.target`, which no frame provides — so it raised
6900    /// `ReferenceError` instead of answering the caller's value
6901    /// (`arrow-body-direct-eval-err-contains-newtarget`).
6902    fn enclosing_function(&self) -> Option<usize> {
6903        (0..self.stack.len())
6904            .rev()
6905            .find(|index| !self.stack[*index].is_arrow)
6906    }
6907
6908    fn state_at(&mut self, index: usize) -> &mut FnState {
6909        &mut self.stack[index]
6910    }
6911
6912    /// Declare a `var` binding directly in a specific frame.
6913    fn declare_at(&mut self, index: usize, name: &str) {
6914        let state = &mut self.stack[index];
6915        if state.vars.iter().any(|var| var.name == name) {
6916            return;
6917        }
6918        state.var_block.push(FUNCTION_SCOPE);
6919        state.vars.push(VarDef::var(name));
6920    }
6921
6922    /// Prepend `<value-producing insn>; put <name>` to the body, which is how a binding
6923    /// the reference calls a `special_object` gets initialised on entry.
6924    fn prepend_initialiser(&mut self, name: &str, producer: Insn) {
6925        let current = self.stack.len() - 1;
6926        let init = [
6927            producer,
6928            Insn::Var {
6929                action: VarAction::Put,
6930                name: name.to_string(),
6931                block: 0,
6932                // A prologue initialiser runs before the body proper, but it is body
6933                // code: `this` and `arguments` are provided for it, not by it.
6934                in_params: false,
6935            },
6936        ];
6937        let inserted = init.len();
6938        for (index, instruction) in init.into_iter().enumerate() {
6939            self.stack[current].insns.insert(index, instruction);
6940        }
6941        for placed in self.stack[current].labels.iter_mut().flatten() {
6942            *placed += inserted;
6943        }
6944        self.stack[current].label_since_insn = true;
6945    }
6946
6947    fn push_constant(&mut self, constant: Constant) -> u32 {
6948        let state = self.state();
6949        let index = state.cpool.len() as u32;
6950        state.cpool.push(constant);
6951        index
6952    }
6953
6954    /// Compile `a && b`, `a || b`, `a ?? b`.
6955    ///
6956    /// A run of the *same* operator shares one end label, so `a || b || c` tests
6957    /// `a` once and jumps past everything when it is truthy, instead of falling
6958    /// into `b`'s test. The parser builds such a run left-associated —
6959    /// `((a || b) || c)` — so the operands are collected off the left spine.
6960    ///
6961    /// A *different* operator starts its own chain: `(a || b) && c` keeps the inner
6962    /// `||`'s label, because the inner chain really does end before `&&` begins.
6963    fn logical(&mut self, op: LogicalOp, left: &Expr, right: &Expr) -> Result<(), SyntaxError> {
6964        let mut operands = Vec::new();
6965        collect_same_operator(op, left, &mut operands);
6966        operands.push(right);
6967
6968        let end = self.new_label();
6969        // Every operand but the last decides whether the chain stops here.
6970        let last = operands.pop().expect("the right operand is always present");
6971        for operand in operands {
6972            self.expr(operand)?;
6973            self.emit(Opcode::Dup, &[]);
6974            match op {
6975                LogicalOp::And => self.emit_jump(Opcode::IfFalse, end, &[]),
6976                LogicalOp::Or => self.emit_jump(Opcode::IfTrue, end, &[]),
6977                // `??` cannot reuse the truthiness jumps: `0 ?? b` is `0` while
6978                // `0 || b` is `b`. The dedicated test keeps the value unless it is
6979                // null-ish, so the jump is taken on `false`.
6980                LogicalOp::Coalesce => {
6981                    self.emit(Opcode::IsUndefinedOrNull, &[]);
6982                    self.emit_jump(Opcode::IfFalse, end, &[]);
6983                }
6984            }
6985            self.emit(Opcode::Drop, &[]);
6986        }
6987        self.expr(last)?;
6988        self.place_label(end);
6989        Ok(())
6990    }
6991
6992    fn unary(&mut self, op: UnaryOp, argument: &Expr) -> Result<(), SyntaxError> {
6993        match op {
6994            UnaryOp::Typeof => {
6995                // `typeof x` must not throw on an undeclared name.
6996                if let ExprKind::Ident(name) = &argument.kind {
6997                    self.emit_var(VarAction::GetUndef, &name.name);
6998                } else {
6999                    self.expr(argument)?;
7000                }
7001                self.emit(Opcode::Typeof, &[]);
7002            }
7003            UnaryOp::Delete => {
7004                // `delete obj.prop` really deletes, and answers whether it could.
7005                // Deleting a *binding* is always `false`: a local, an argument and a
7006                // declared global are all non-configurable, which the reference encodes
7007                // as a constant `push_false` rather than a runtime check. Only a
7008                // property access has anything to do at run time.
7009                // `delete super.x` is not a delete at all: the spec refuses it, and the
7010                // reference encodes the refusal as a `throw_error`. The receiver and the
7011                // key are still evaluated first, which is what keeps the evaluation order
7012                // of the operand intact.
7013                // `delete z?.b.c` answers `true` when the chain short-circuits: there is
7014                // nothing to delete, and a failed delete is not the same as a skipped
7015                // one. The reference emits the guards so they land on a `drop; push_true`
7016                // tail, which is what this reproduces.
7017                if let ExprKind::OptionalChain(inner) = &argument.unparen().kind
7018                    && let ExprKind::Member {
7019                        object, property, ..
7020                    } = &inner.unparen().kind
7021                {
7022                    let end = self.new_label();
7023                    let done = self.new_label();
7024                    self.chain_link(object, end)?;
7025                    match property {
7026                        MemberProp::Ident(name) => self.emit(
7027                            Opcode::PushAtomValue,
7028                            &[Op::Atom(Atom::from_text(&name.name))],
7029                        ),
7030                        MemberProp::Computed(index) => self.expr(index)?,
7031                        MemberProp::Private(_) => {
7032                            return Err(SyntaxError::new(
7033                                "deleting a private field is not allowed",
7034                                argument.span,
7035                            ));
7036                        }
7037                    }
7038                    self.emit(Opcode::Delete, &[]);
7039                    self.emit_jump(Opcode::Goto, done, &[]);
7040                    self.place_label(end);
7041                    self.emit(Opcode::Drop, &[]);
7042                    self.emit(Opcode::PushTrue, &[]);
7043                    self.place_label(done);
7044                    return Ok(());
7045                }
7046                if let ExprKind::Member { object, .. } = &argument.unparen().kind
7047                    && matches!(object.unparen().kind, ExprKind::SuperProp)
7048                {
7049                    self.super_base();
7050                    self.emit(Opcode::ThrowError, &[Op::Atom(Atom::Null), Op::Int(3)]);
7051                    return Ok(());
7052                }
7053                // Parentheses are transparent to `delete`: `(x)` is still a Reference to
7054                // the binding `x`, so `delete (x)` answers `false` exactly as `delete x`
7055                // does, and `delete (a().b)` still evaluates `a()`. Matching on the
7056                // unparenthesised operand is what keeps both — matching on `argument.kind`
7057                // sent every parenthesised form to the "not a Reference" arm, which cost
7058                // `delete(__variable) === false` in test262's `S12.2_A2`.
7059                match &argument.unparen().kind {
7060                    ExprKind::Member {
7061                        object, property, ..
7062                    } => {
7063                        self.expr(object)?;
7064                        match property {
7065                            MemberProp::Ident(name) => {
7066                                self.emit(
7067                                    Opcode::PushAtomValue,
7068                                    &[Op::Atom(Atom::from_text(&name.name))],
7069                                );
7070                            }
7071                            MemberProp::Computed(index) => self.expr(index)?,
7072                            MemberProp::Private(_) => {
7073                                return Err(SyntaxError::new(
7074                                    "deleting a private field is not allowed",
7075                                    argument.span,
7076                                ));
7077                            }
7078                        }
7079                        self.emit(Opcode::Delete, &[]);
7080                    }
7081                    ExprKind::Ident(name) => {
7082                        self.delete_ident(&name.name);
7083                    }
7084                    // §13.5.1.2 step 2: an operand that is **not** a Reference Record
7085                    // answers `true` — there is nothing to delete, and "nothing needed
7086                    // deleting" is success. `delete !0`, `delete (1 + 2)` and
7087                    // `delete typeof 0` are all `true`, and the operand is still evaluated
7088                    // (which is why it is `Drop`ed rather than skipped:
7089                    // `delete f()` must call `f`).
7090                    //
7091                    // Answering `false` here is the C reference's old behaviour and was
7092                    // wrong in an observable way: test262's
7093                    // `dynamic-import/assignment-expression/logical-and-expr` builds a
7094                    // specifier out of `delete void typeof +-~! 0 && b`, and a `false` left
7095                    // half turned the whole `&&` into `false`, so the import asked for a
7096                    // module named "false".
7097                    _ => {
7098                        self.expr(argument)?;
7099                        self.emit(Opcode::Drop, &[]);
7100                        self.emit(Opcode::PushTrue, &[]);
7101                    }
7102                }
7103            }
7104            UnaryOp::Void => {
7105                self.expr(argument)?;
7106                self.emit(Opcode::Drop, &[]);
7107                self.emit(Opcode::Undefined, &[]);
7108            }
7109            UnaryOp::Minus => {
7110                self.expr(argument)?;
7111                self.emit(Opcode::Neg, &[]);
7112            }
7113            UnaryOp::Plus => {
7114                self.expr(argument)?;
7115                self.emit(Opcode::Plus, &[]);
7116            }
7117            UnaryOp::Not => {
7118                self.expr(argument)?;
7119                self.emit(Opcode::Lnot, &[]);
7120            }
7121            UnaryOp::BitNot => {
7122                self.expr(argument)?;
7123                self.emit(Opcode::Not, &[]);
7124            }
7125        }
7126        Ok(())
7127    }
7128
7129    /// A store to `name` while a `with` may capture it.
7130    ///
7131    /// The reference is resolved **first**, before the right-hand side runs. That order is
7132    /// the whole point: in `x = (delete env.x, 0)` the resolution has already decided that
7133    /// `x` is `env`'s property, so `PutValue` then finds it gone and strict code throws
7134    /// `ReferenceError` (`set-mutable-binding-binding-deleted-with-typed-array-in-
7135    /// proto-chain-strict-mode`). The ordinary path evaluates the right-hand side before
7136    /// the guard runs, which put the guard *after* the mutation.
7137    ///
7138    /// Shapes mirror [`Compiler::assign_ident_plain`] and the member arms of
7139    /// [`Compiler::assign`], with `dup; with_get_var` in place of `get_field2` and
7140    /// `with_put_var` in place of `put_field` — the same stack effects, but each half also
7141    /// asks the `HasProperty` that `GetBindingValue`/`SetMutableBinding` require.
7142    fn with_assign(
7143        &mut self,
7144        with_local: &str,
7145        name: &Ident,
7146        op: AssignOp,
7147        value: &Expr,
7148        keep: bool,
7149    ) -> Result<(), SyntaxError> {
7150        let atom = Atom::from_text(&name.name);
7151        self.state().cur_pos = Some(name.span.start);
7152        match op {
7153            AssignOp::Assign => {
7154                self.expr(value)?;
7155                self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7156                if keep {
7157                    self.emit(Opcode::Dup, &[]);
7158                }
7159                self.state().no_value = !keep;
7160                self.emit_var(VarAction::Get, with_local);
7161                self.emit(Opcode::Swap, &[]);
7162                self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7163            }
7164            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7165                let (keep_label, end) = (self.new_label(), self.new_label());
7166                self.emit_var(VarAction::Get, with_local);
7167                self.emit(Opcode::Dup, &[]);
7168                self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7169                // `obj value` — the object stays underneath for the store.
7170                self.emit(Opcode::Dup, &[]);
7171                self.emit_logical_test(op);
7172                self.emit_jump(logical_jump(op), keep_label, &[]);
7173                self.emit(Opcode::Drop, &[]);
7174                self.expr(value)?;
7175                self.emit(Opcode::Insert2, &[]);
7176                self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7177                self.emit_jump(Opcode::Goto, end, &[]);
7178                self.place_label(keep_label);
7179                self.emit(Opcode::Nip, &[]);
7180                self.place_label(end);
7181            }
7182            _ => {
7183                self.emit_var(VarAction::Get, with_local);
7184                self.emit(Opcode::Dup, &[]);
7185                self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7186                self.expr(value)?;
7187                self.state().cur_pos = Some(name.span.start);
7188                self.emit(compound_opcode(op), &[]);
7189                self.state().no_value = !keep;
7190                if keep {
7191                    self.emit(Opcode::Insert2, &[]);
7192                }
7193                self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7194            }
7195        }
7196        Ok(())
7197    }
7198
7199    /// `x++` / `++x` while a `with` may capture `x`, with one resolution for both halves.
7200    fn with_update(
7201        &mut self,
7202        with_local: &str,
7203        name: &Ident,
7204        op: UpdateOp,
7205        prefix: bool,
7206    ) -> Result<(), SyntaxError> {
7207        let instruction = match (op, prefix) {
7208            (UpdateOp::Increment, true) => Opcode::Inc,
7209            (UpdateOp::Increment, false) => Opcode::PostInc,
7210            (UpdateOp::Decrement, true) => Opcode::Dec,
7211            (UpdateOp::Decrement, false) => Opcode::PostDec,
7212        };
7213        let atom = Atom::from_text(&name.name);
7214        self.state().cur_pos = Some(name.span.start);
7215        self.emit_var(VarAction::Get, with_local);
7216        self.emit(Opcode::Dup, &[]);
7217        self.emit(Opcode::WithGetVar, &[Op::Atom(atom.clone())]);
7218        self.emit(instruction, &[]);
7219        self.emit(
7220            if prefix {
7221                Opcode::Insert2
7222            } else {
7223                Opcode::Perm3
7224            },
7225            &[],
7226        );
7227        self.emit(Opcode::WithPutVar, &[Op::Atom(atom)]);
7228        Ok(())
7229    }
7230
7231    /// A store to a plain identifier, with no `with` in the way.
7232    fn assign_ident_plain(
7233        &mut self,
7234        op: AssignOp,
7235        name: &Ident,
7236        value: &Expr,
7237        discard: bool,
7238    ) -> Result<(), SyntaxError> {
7239        // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7240        // about, so it is set only when this assignment *is* that expression.
7241        let keep = !discard;
7242        // A *simple* store is blamed on the identifier, not on the `=`: a
7243        // strict-mode `not_def = 1` raises when the name is written, which the
7244        // reference reports at the name's column. A compound store is blamed on
7245        // the operator instead (`a += poisoned` raises inside `ToPrimitive`,
7246        // which the reference reports at the `+=`), so only the simple case
7247        // moves the position.
7248        let saved = self.cur().cur_pos;
7249        let name_pos = Some(name.span.start);
7250        if matches!(op, AssignOp::Assign) {
7251            self.state().cur_pos = name_pos;
7252        }
7253        // A *compound* store reads the binding before it combines, and that read
7254        // is blamed on the identifier: `not_def += 2` fails while reading
7255        // `not_def`, so the position is the name's, not the `+=`'s. The
7256        // combination that follows is blamed on the operator, which is why
7257        // `cur_pos` is put back to the operator position before it is emitted.
7258        self.state().cur_pos = name_pos;
7259        match op {
7260            AssignOp::Assign => {
7261                self.expr(value)?;
7262                self.set_name_if_anonymous(value, &Wtf8::new(&name.name));
7263                // A discarded store to a *slot* consumes its value, so no copy
7264                // is needed. A global store goes through `put_var`, which the
7265                // reference always pairs with a `dup` — matching it keeps the
7266                // bytecode identical. Getting this wrong is not only an extra
7267                // instruction: a stray copy gives the peephole a chance to fold
7268                // the store into an unrelated later read.
7269                let slot = self.is_slot(&name.name);
7270                if keep || !slot {
7271                    self.emit(Opcode::Dup, &[]);
7272                }
7273                self.state().no_value = !keep && slot;
7274                self.emit_var(VarAction::Put, &name.name);
7275            }
7276            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7277                let end = self.new_label();
7278                self.emit_var(VarAction::Get, &name.name);
7279                self.state().cur_pos = saved;
7280                self.emit(Opcode::Dup, &[]);
7281                self.emit_logical_test(op);
7282                self.emit_jump(logical_jump(op), end, &[]);
7283                self.emit(Opcode::Drop, &[]);
7284                self.expr(value)?;
7285                self.emit(Opcode::Dup, &[]);
7286                self.emit_var(VarAction::Put, &name.name);
7287                self.place_label(end);
7288            }
7289            _ => {
7290                self.emit_var(VarAction::Get, &name.name);
7291                self.expr(value)?;
7292                self.state().cur_pos = saved;
7293                self.emit(compound_opcode(op), &[]);
7294                self.emit(Opcode::Dup, &[]);
7295                self.emit_var(VarAction::Put, &name.name);
7296            }
7297        }
7298        self.state().cur_pos = saved;
7299        Ok(())
7300    }
7301
7302    /// Compile an assignment.
7303    ///
7304    /// Three operator families, three shapes:
7305    ///
7306    /// * **plain** `=` — evaluate, store. A member needs `insert2`/`insert3` when
7307    ///   the value is kept, because `put_field`/`put_array_el` consume both the
7308    ///   object and the value: `insert2` is `obj a -> a obj a`, so the store sees
7309    ///   the pair it wants and leaves a copy on top.
7310    /// * **compound** `+=` … — read the place, apply the operator, store. A member
7311    ///   reads through `get_field2`/`get_array_el3`, which leave the object (and
7312    ///   index) underneath the value precisely so the store can follow.
7313    /// * **logical** `||=`, `&&=`, `??=` — read, test, and only then evaluate the
7314    ///   right-hand side. The test *keeps* the current value and skips the store
7315    ///   entirely, which is the whole point: `a ||= b` must not evaluate `b` when
7316    ///   `a` is already truthy.
7317    fn assign(
7318        &mut self,
7319        op: AssignOp,
7320        target: &Pattern,
7321        value: &Expr,
7322        discard: bool,
7323    ) -> Result<(), SyntaxError> {
7324        // `discard` was taken by [`Compiler::expr`] for the expression the statement asked
7325        // about, so it is set only when this assignment *is* that expression.
7326        let keep = !discard;
7327        match &target.kind {
7328            PatternKind::Ident(name) => {
7329                // Any store to a name a `with` may capture resolves the reference first and
7330                // keeps that resolution for both halves — see [`Compiler::with_assign`].
7331                // Plain `=` needs it just as much as `+=`: `x = (delete env.x, 0)` must
7332                // resolve `x` before the right-hand side deletes it.
7333                let plain_name = name.name.clone();
7334                if !self.visible_with_names(&plain_name).is_empty() {
7335                    return self.with_reference(
7336                        &plain_name,
7337                        &mut |compiler, with_local| {
7338                            compiler.with_assign(with_local, name, op, value, !discard)
7339                        },
7340                        &mut |compiler| compiler.assign_ident_plain(op, name, value, discard),
7341                    );
7342                }
7343                self.assign_ident_plain(op, name, value, discard)
7344            }
7345            PatternKind::Member(member) => {
7346                // `super.x = v` is not a store through a value: it starts at the home
7347                // object's prototype but writes to `this`, so it goes through
7348                // `put_super_value` rather than `put_field`. The receiver, prototype, key
7349                // and value are handed over together.
7350                if matches!(member.object.unparen().kind, ExprKind::SuperProp) {
7351                    return self.assign_super(member, op, value);
7352                }
7353                // A store is blamed on the selector punctuator (`.` or `[`), the same
7354                // token a load is blamed on — the reference records `put_field obj.a`
7355                // at the `.`, so a setter that throws reports that column and not the
7356                // `=` of the assignment it sits in. The inner expressions restore their
7357                // own positions, so the selector's sticks for the store instructions.
7358                let saved = self.cur().cur_pos;
7359                self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7360                self.expr(&member.object)?;
7361                match &member.property {
7362                    MemberProp::Ident(property) => {
7363                        let atom = Atom::from_text(&property.name);
7364                        match op {
7365                            AssignOp::Assign => {
7366                                self.expr(value)?;
7367                                // `put_field` consumes the object and the value, so
7368                                // without `insert2` nothing is left over for the
7369                                // statement to drop.
7370                                self.state().no_value = !keep;
7371                                if keep {
7372                                    self.emit(Opcode::Insert2, &[]);
7373                                }
7374                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7375                            }
7376                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7377                                // `get_field2` leaves the object under the value, so
7378                                // the keep path has an object to dispose of. The store
7379                                // path must jump *over* that cleanup: falling into it
7380                                // would `nip` a stack that only holds the value.
7381                                let (keep_label, end) = (self.new_label(), self.new_label());
7382                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7383                                self.emit(Opcode::Dup, &[]);
7384                                self.emit_logical_test(op);
7385                                self.emit_jump(logical_jump(op), keep_label, &[]);
7386                                self.emit(Opcode::Drop, &[]);
7387                                self.expr(value)?;
7388                                self.emit(Opcode::Insert2, &[]);
7389                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7390                                self.emit_jump(Opcode::Goto, end, &[]);
7391                                self.place_label(keep_label);
7392                                self.emit(Opcode::Nip, &[]);
7393                                self.place_label(end);
7394                            }
7395                            _ => {
7396                                self.emit(Opcode::GetField2, &[Op::Atom(atom.clone())]);
7397                                self.expr(value)?;
7398                                self.emit(compound_opcode(op), &[]);
7399                                self.state().no_value = !keep;
7400                                if keep {
7401                                    self.emit(Opcode::Insert2, &[]);
7402                                }
7403                                self.emit(Opcode::PutField, &[Op::Atom(atom.clone())]);
7404                            }
7405                        }
7406                    }
7407                    MemberProp::Computed(index) => {
7408                        self.expr(index)?;
7409                        match op {
7410                            AssignOp::Assign => {
7411                                self.expr(value)?;
7412                                self.state().no_value = !keep;
7413                                if keep {
7414                                    self.emit(Opcode::Insert3, &[]);
7415                                }
7416                                self.emit(Opcode::PutArrayEl, &[]);
7417                            }
7418                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7419                                let (keep_label, end) = (self.new_label(), self.new_label());
7420                                self.emit(Opcode::GetArrayEl3, &[]);
7421                                self.emit(Opcode::Dup, &[]);
7422                                self.emit_logical_test(op);
7423                                self.emit_jump(logical_jump(op), keep_label, &[]);
7424                                self.emit(Opcode::Drop, &[]);
7425                                self.expr(value)?;
7426                                self.emit(Opcode::Insert3, &[]);
7427                                self.emit(Opcode::PutArrayEl, &[]);
7428                                self.emit_jump(Opcode::Goto, end, &[]);
7429                                self.place_label(keep_label);
7430                                // Both the object and the index are left over.
7431                                self.emit(Opcode::Nip, &[]);
7432                                self.emit(Opcode::Nip, &[]);
7433                                self.place_label(end);
7434                            }
7435                            _ => {
7436                                self.emit(Opcode::GetArrayEl3, &[]);
7437                                self.expr(value)?;
7438                                self.emit(compound_opcode(op), &[]);
7439                                self.state().no_value = !keep;
7440                                if keep {
7441                                    self.emit(Opcode::Insert3, &[]);
7442                                }
7443                                self.emit(Opcode::PutArrayEl, &[]);
7444                            }
7445                        }
7446                    }
7447                    MemberProp::Private(name) => {
7448                        // `obj value` is on the stack, and every private store wants exactly
7449                        // that. A top-level private name cannot be assigned (the parser rejects
7450                        // `#x = 1`), so the only way here is `this.#x = …` inside the class.
7451                        //
7452                        // The reference emits `insert2` whether or not the value is wanted,
7453                        // so this does too: the copy left behind is the assignment expression's
7454                        // value, and a discarded one is simply never read.
7455                        let binding = format!("#{}", name.name);
7456                        let (kind, setter) = self.private_use(&binding, member.span)?;
7457                        match op {
7458                            AssignOp::Assign => {
7459                                self.expr(value)?;
7460                                if keep {
7461                                    self.emit(Opcode::Insert2, &[]);
7462                                }
7463                                self.private_store(&binding, kind, setter.as_deref())?;
7464                                self.state().no_value = !keep;
7465                            }
7466                            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7467                                let (keep_label, end) = (self.new_label(), self.new_label());
7468                                self.emit(Opcode::Dup, &[]);
7469                                self.private_load(&binding, kind, member.span)?;
7470                                self.emit(Opcode::Dup, &[]);
7471                                self.emit_logical_test(op);
7472                                self.emit_jump(logical_jump(op), keep_label, &[]);
7473                                self.emit(Opcode::Drop, &[]);
7474                                self.expr(value)?;
7475                                self.emit(Opcode::Insert2, &[]);
7476                                self.private_store(&binding, kind, setter.as_deref())?;
7477                                self.emit_jump(Opcode::Goto, end, &[]);
7478                                self.place_label(keep_label);
7479                                self.emit(Opcode::Nip, &[]);
7480                                self.place_label(end);
7481                            }
7482                            _ => {
7483                                self.emit(Opcode::Dup, &[]);
7484                                self.private_load(&binding, kind, member.span)?;
7485                                self.expr(value)?;
7486                                self.emit(compound_opcode(op), &[]);
7487                                self.emit(Opcode::Insert2, &[]);
7488                                self.private_store(&binding, kind, setter.as_deref())?;
7489                            }
7490                        }
7491                    }
7492                }
7493                self.state().cur_pos = saved;
7494                Ok(())
7495            }
7496            // A destructuring assignment: the right-hand side is the expression's own
7497            // value, so it is evaluated once and kept under the pattern's stores.
7498            PatternKind::Array { .. } | PatternKind::Object { .. } => {
7499                self.expr(value)?;
7500                if keep {
7501                    self.emit(Opcode::Dup, &[]);
7502                }
7503                self.destructure(target, None)?;
7504                self.state().no_value = !keep;
7505                Ok(())
7506            }
7507            _ => Err(SyntaxError::new(
7508                "this assignment target is not supported by the compiler yet",
7509                target.span,
7510            )),
7511        }
7512    }
7513
7514    /// `super.x = v`, `super[k] = v`, and their compound and logical forms.
7515    ///
7516    /// The stack has to carry four values — receiver, prototype, key, value — because
7517    /// `put_super_value` takes them together; the receiver is what makes a setter found on
7518    /// the prototype run with `this`, and the key has to survive until the store, which is
7519    /// why a compound form converts it to a property key once and `dup3`s rather than
7520    /// evaluating it twice.
7521    fn assign_super(
7522        &mut self,
7523        member: &MemberPattern,
7524        op: AssignOp,
7525        value: &Expr,
7526    ) -> Result<(), SyntaxError> {
7527        let saved = self.cur().cur_pos;
7528        self.state().cur_pos = member.op_pos.or(Some(member.span.start));
7529        self.super_base();
7530        match &member.property {
7531            MemberProp::Ident(property) => self.emit(
7532                Opcode::PushAtomValue,
7533                &[Op::Atom(Atom::from_text(&property.name))],
7534            ),
7535            MemberProp::Computed(index) => self.expr(index)?,
7536            MemberProp::Private(_) => {
7537                return Err(SyntaxError::new(
7538                    "private fields are not supported by the compiler yet",
7539                    member.span,
7540                ));
7541            }
7542        }
7543        match op {
7544            AssignOp::Assign => {
7545                // The key is only converted once, by `put_super_value` itself, so a
7546                // computed key's `toString` runs exactly once.
7547                self.expr(value)?;
7548                self.emit(Opcode::Insert4, &[]);
7549                self.emit(Opcode::PutSuperValue, &[]);
7550            }
7551            AssignOp::And | AssignOp::Or | AssignOp::Coalesce => {
7552                let (keep_label, end) = (self.new_label(), self.new_label());
7553                self.emit(Opcode::ToPropkey, &[]);
7554                self.emit(Opcode::Dup3, &[]);
7555                self.emit(Opcode::GetSuperValue, &[]);
7556                self.emit(Opcode::Dup, &[]);
7557                self.emit_logical_test(op);
7558                self.emit_jump(logical_jump(op), keep_label, &[]);
7559                self.emit(Opcode::Drop, &[]);
7560                self.expr(value)?;
7561                self.emit(Opcode::Insert4, &[]);
7562                self.emit(Opcode::PutSuperValue, &[]);
7563                self.emit_jump(Opcode::Goto, end, &[]);
7564                self.place_label(keep_label);
7565                // The prototype and the key are still under the value that was read.
7566                self.emit(Opcode::Nip, &[]);
7567                self.emit(Opcode::Nip, &[]);
7568                self.emit(Opcode::Nip, &[]);
7569                self.place_label(end);
7570            }
7571            _ => {
7572                self.emit(Opcode::ToPropkey, &[]);
7573                self.emit(Opcode::Dup3, &[]);
7574                self.emit(Opcode::GetSuperValue, &[]);
7575                self.expr(value)?;
7576                self.emit(compound_opcode(op), &[]);
7577                self.emit(Opcode::Insert4, &[]);
7578                self.emit(Opcode::PutSuperValue, &[]);
7579            }
7580        }
7581        // No `drop` here for a discarded value. `insert4` keeps a copy of the value, so it
7582        // is still on the stack when the store finishes, and the expression statement is
7583        // what disposes of it — the same arrangement as `put_field`, reached from the other
7584        // side: there the store consumes the value (`no_value`), here it leaves it
7585        // (`keep` already false, so nothing tells the statement otherwise).
7586        self.state().cur_pos = saved;
7587        Ok(())
7588    }
7589
7590    /// The test a logical assignment applies to the current value.
7591    ///
7592    /// `??=` needs a real opcode rather than a truthiness jump: `0 ??= b` must
7593    /// assign, while `0 ||= b` must not.
7594    fn emit_logical_test(&mut self, op: AssignOp) {
7595        if op == AssignOp::Coalesce {
7596            self.emit(Opcode::IsUndefinedOrNull, &[]);
7597        }
7598    }
7599
7600    /// The private name `#name` this use site resolves against.
7601    ///
7602    /// The parser has already rejected a name no enclosing class declares, so a miss here
7603    /// means the compiler lost track of a class scope — which is worth a real error rather
7604    /// than an `unwrap`.
7605    fn private_use(
7606        &self,
7607        binding: &str,
7608        span: Span,
7609    ) -> Result<(PrivateKind, Option<String>), SyntaxError> {
7610        ClassPlan::find(self, binding)
7611            .map(|use_| (use_.kind, use_.setter.clone()))
7612            .ok_or_else(|| {
7613                SyntaxError::new(
7614                    format!("the private name '{binding}' is out of scope here"),
7615                    span,
7616                )
7617            })
7618    }
7619
7620    /// `obj.#name` as a value: `obj` is on the stack, the value replaces it.
7621    ///
7622    /// The three readable kinds take three different instructions, because a private name
7623    /// holds three different things — a symbol, a method function, a getter function — and
7624    /// only the first one is a property read at all.
7625    fn private_load(
7626        &mut self,
7627        binding: &str,
7628        kind: PrivateKind,
7629        span: Span,
7630    ) -> Result<(), SyntaxError> {
7631        match kind {
7632            PrivateKind::Field => {
7633                self.emit_var(VarAction::Get, binding);
7634                self.emit(Opcode::GetPrivateField, &[]);
7635            }
7636            PrivateKind::Method => {
7637                self.emit_var(VarAction::Get, binding);
7638                self.emit(Opcode::CheckBrand, &[]);
7639                // `check_brand` reads `obj func` and leaves both; the method itself is what
7640                // `this.#m` evaluates to.
7641                self.emit(Opcode::Nip, &[]);
7642            }
7643            PrivateKind::Getter => {
7644                self.emit_var(VarAction::Get, binding);
7645                self.emit(Opcode::CheckBrand, &[]);
7646                self.emit(Opcode::CallMethod, &[Op::Int(0)]);
7647            }
7648            // `#a` is declared but never filled when only a setter exists, so reading it is
7649            // the same refusal as assigning to a `const`. The reference reports it with the
7650            // generic read-only wording and leaves the better message as a `XXX`.
7651            PrivateKind::Setter => self.emit(
7652                Opcode::ThrowError,
7653                &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7654            ),
7655        }
7656        let _ = span;
7657        Ok(())
7658    }
7659
7660    /// `obj.#name(...)`: like [`Self::private_load`], but the receiver stays under the callee.
7661    fn private_callee(&mut self, binding: &str, kind: PrivateKind) -> Result<(), SyntaxError> {
7662        match kind {
7663            // A method *is* the callee, so only the check goes in between.
7664            PrivateKind::Method => {
7665                self.emit_var(VarAction::Get, binding);
7666                self.emit(Opcode::CheckBrand, &[]);
7667            }
7668            _ => self.private_load(binding, kind, Span::default())?,
7669        }
7670        Ok(())
7671    }
7672
7673    /// The store half of `obj.#name = value`, with `obj value` on the stack and nothing
7674    /// wanted back.
7675    ///
7676    /// A getter/setter pair is a *method call*, not a property store: the reference reads
7677    /// the setter out of its own binding and calls it with the receiver, which is why the
7678    /// three `rot`/`swap` instructions below are needed. `insert2` at the call site is what
7679    /// keeps the assignment's value for an expression context.
7680    fn private_store(
7681        &mut self,
7682        binding: &str,
7683        kind: PrivateKind,
7684        setter: Option<&str>,
7685    ) -> Result<(), SyntaxError> {
7686        match kind {
7687            PrivateKind::Field => {
7688                self.emit_var(VarAction::Get, binding);
7689                self.emit(Opcode::PutPrivateField, &[]);
7690            }
7691            PrivateKind::Method | PrivateKind::Getter | PrivateKind::Setter => match setter {
7692                Some(setter) => {
7693                    self.emit_var(VarAction::Get, setter);
7694                    // `obj func value` -> `value obj func` for the check, and back again for
7695                    // the call, which wants `obj func arg`.
7696                    self.emit(Opcode::Swap, &[]);
7697                    self.emit(Opcode::Rot3r, &[]);
7698                    self.emit(Opcode::CheckBrand, &[]);
7699                    self.emit(Opcode::Rot3l, &[]);
7700                    self.emit(Opcode::CallMethod, &[Op::Int(1)]);
7701                    // The setter's return value is discarded; the assignment's own value is
7702                    // whatever the caller left underneath.
7703                    self.emit(Opcode::Drop, &[]);
7704                }
7705                None => self.emit(
7706                    Opcode::ThrowError,
7707                    &[Op::Atom(Atom::from_text(binding)), Op::Int(0)],
7708                ),
7709            },
7710        }
7711        Ok(())
7712    }
7713
7714    fn update(&mut self, op: UpdateOp, argument: &Expr, prefix: bool) -> Result<(), SyntaxError> {
7715        // `x++` inside a `with` is a read-modify-write of a *property*, so the object is
7716        // resolved once for both halves. See [`Compiler::with_reference`].
7717        let unparened = argument.unparen();
7718        if let ExprKind::Ident(ident) = &unparened.kind {
7719            let name = ident.name.clone();
7720            if !self.visible_with_names(&name).is_empty() {
7721                return self.with_reference(
7722                    &name,
7723                    &mut |compiler, with_local| compiler.with_update(with_local, ident, op, prefix),
7724                    &mut |compiler| compiler.update_plain(op, unparened, prefix),
7725                );
7726            }
7727        }
7728        self.update_plain(op, argument, prefix)
7729    }
7730
7731    fn update_plain(
7732        &mut self,
7733        op: UpdateOp,
7734        argument: &Expr,
7735        prefix: bool,
7736    ) -> Result<(), SyntaxError> {
7737        let instruction = match (op, prefix) {
7738            (UpdateOp::Increment, true) => Opcode::Inc,
7739            (UpdateOp::Increment, false) => Opcode::PostInc,
7740            (UpdateOp::Decrement, true) => Opcode::Dec,
7741            (UpdateOp::Decrement, false) => Opcode::PostDec,
7742        };
7743        // `(y)++` and `((o.x))++` are the same updates as the unparenthesised forms: §13.4
7744        // evaluates the operand as a `LeftHandSideExpression` and the parentheses around a
7745        // reference change nothing — they do not copy the value. Reading `argument.kind`
7746        // directly therefore rejected every parenthesised target with "increment of a
7747        // non-variable", which is not a thing the language has (`target-cover-id`).
7748        let argument = argument.unparen();
7749        if let ExprKind::Member {
7750            object,
7751            property,
7752            optional: _,
7753        } = &argument.kind
7754        {
7755            // `o.x++` needs the receiver twice, so the last link is read with the
7756            // `get_*2`/`get_*3` form that keeps it, and the update is written back
7757            // with `put_field`/`put_array_el`. The reordering in between is what puts
7758            // the old value below the receiver for a postfix update and the new one
7759            // above it for a prefix one:
7760            //
7761            //   `obj val` → `post_inc` → `obj old new` → `perm3` → `old obj new`
7762            //   `obj val` → `inc`      → `obj new new` → `insert2` → `new obj new`
7763            //
7764            // This mirrors the reference instruction for instruction.
7765            self.expr(object)?;
7766            match property {
7767                MemberProp::Ident(name) => {
7768                    self.emit(Opcode::GetField2, &[Op::Atom(Atom::from_text(&name.name))]);
7769                    self.emit(instruction, &[]);
7770                    self.emit(
7771                        if prefix {
7772                            Opcode::Insert2
7773                        } else {
7774                            Opcode::Perm3
7775                        },
7776                        &[],
7777                    );
7778                    self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text(&name.name))]);
7779                }
7780                MemberProp::Computed(index) => {
7781                    self.expr(index)?;
7782                    self.emit(Opcode::GetArrayEl3, &[]);
7783                    self.emit(instruction, &[]);
7784                    self.emit(
7785                        if prefix {
7786                            Opcode::Insert3
7787                        } else {
7788                            Opcode::Perm4
7789                        },
7790                        &[],
7791                    );
7792                    self.emit(Opcode::PutArrayEl, &[]);
7793                }
7794                MemberProp::Private(name) => {
7795                    // The receiver is duplicated and the read keeps it, exactly as `get_field2`
7796                    // does for a public field: `obj val` -> `post_inc` -> `obj old new` ->
7797                    // `perm3` -> `old obj new` -> store.
7798                    let binding = format!("#{}", name.name);
7799                    let (kind, setter) = self.private_use(&binding, argument.span)?;
7800                    self.emit(Opcode::Dup, &[]);
7801                    self.private_load(&binding, kind, argument.span)?;
7802                    self.emit(instruction, &[]);
7803                    self.emit(
7804                        if prefix {
7805                            Opcode::Insert2
7806                        } else {
7807                            Opcode::Perm3
7808                        },
7809                        &[],
7810                    );
7811                    self.private_store(&binding, kind, setter.as_deref())?;
7812                }
7813            }
7814            return Ok(());
7815        }
7816        let ExprKind::Ident(name) = &argument.kind else {
7817            return Err(SyntaxError::new(
7818                "increment of a non-variable is not supported by the compiler yet",
7819                argument.span,
7820            ));
7821        };
7822        // A discarded `i++` keeps the plain `get`/`post_inc`/`put` shape. The
7823        // reference's `inc_loc` folds those three into one, but it does so only in some
7824        // positions (a `for` update and not a bare statement, and never for a lexical
7825        // binding), so emitting it unconditionally would move *away* from its output.
7826        // The instruction is equivalent either way; matching the reference matters more
7827        // than saving two instructions.
7828        let _ = !std::mem::take(&mut self.state().discard_value);
7829        self.emit_var(VarAction::Get, &name.name);
7830        self.emit(instruction, &[]);
7831        if prefix {
7832            self.emit(Opcode::Dup, &[]);
7833        }
7834        self.emit_var(VarAction::Put, &name.name);
7835        Ok(())
7836    }
7837
7838    /// Compile an array literal.
7839    ///
7840    /// The reference splits this into three phases, and the split is load-bearing
7841    /// rather than an optimisation detail:
7842    ///
7843    /// 1. **A leading run of plain elements** becomes `array_from n`, which builds
7844    ///    the array in one instruction.
7845    /// 2. **Everything up to the first spread** is appended with explicit indices
7846    ///    (`define_field <index>`), because a hole has no element to pass to
7847    ///    `array_from`. A hole here is what makes `length` need fixing up: an
7848    ///    explicit index does not extend the array the way a pushed element does.
7849    /// 3. **From the first spread on** the index lives on the stack, so `append` and
7850    ///    `define_array_el` can consume it and `inc` advances it.
7851    ///
7852    /// So `[1,,3]` and `[1,2,3]` are not two spellings of one program: the hole
7853    /// forces phase 2, and `[...a]` forces phase 3.
7854    fn array_literal(
7855        &mut self,
7856        elements: &[Option<ArrayElement>],
7857        span: Span,
7858    ) -> Result<(), SyntaxError> {
7859        let _ = span;
7860        let mut index: u32 = 0;
7861        let mut cursor = 0usize;
7862
7863        // Phase 1: a leading run of plain elements, at most 32 of them.
7864        while let Some(Some(ArrayElement::Expr(element))) = elements.get(cursor) {
7865            if index >= 32 {
7866                break;
7867            }
7868            self.expr(element)?;
7869            index += 1;
7870            cursor += 1;
7871        }
7872        self.emit(Opcode::ArrayFrom, &[Op::Int(index as i32)]);
7873
7874        // Phase 2: explicit indices, up to the first spread.
7875        let mut need_length = false;
7876        while let Some(element) = elements.get(cursor) {
7877            if matches!(element, Some(ArrayElement::Spread(_))) {
7878                break;
7879            }
7880            need_length = true;
7881            if let Some(ArrayElement::Expr(expression)) = element {
7882                self.expr(expression)?;
7883                self.emit_define_index(index);
7884                need_length = false;
7885            }
7886            index += 1;
7887            cursor += 1;
7888        }
7889
7890        if cursor >= elements.len() {
7891            if need_length {
7892                // `define_field` cannot set `length`, which is not configurable.
7893                self.emit(Opcode::Dup, &[]);
7894                self.push_number(index as f64);
7895                self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7896            }
7897            return Ok(());
7898        }
7899
7900        // Phase 3: the index moves onto the stack for the spreading tail.
7901        //
7902        // `need_length` deliberately carries over from phase 2: a hole before the
7903        // first spread still has to be reflected in `length`, and only the final
7904        // check can do it because the array is not finished until the tail is
7905        // appended.
7906        self.push_number(index as f64);
7907        while let Some(element) = elements.get(cursor) {
7908            match element {
7909                Some(ArrayElement::Spread(expression)) => {
7910                    // `append` copies an iterable and leaves the next index behind,
7911                    // so no `inc` is needed here.
7912                    self.expr(spread_argument(expression))?;
7913                    self.emit(Opcode::Append, &[]);
7914                }
7915                None | Some(ArrayElement::Expr(_)) => {
7916                    need_length = true;
7917                    if let Some(ArrayElement::Expr(expression)) = element {
7918                        self.expr(expression)?;
7919                        self.emit(Opcode::DefineArrayEl, &[]);
7920                        need_length = false;
7921                    }
7922                    self.emit(Opcode::Inc, &[]);
7923                }
7924            }
7925            cursor += 1;
7926        }
7927        if need_length {
7928            self.emit(Opcode::Dup1, &[]);
7929            self.emit(Opcode::PutField, &[Op::Atom(Atom::from_text("length"))]);
7930        } else {
7931            self.emit(Opcode::Drop, &[]);
7932        }
7933        Ok(())
7934    }
7935
7936    /// `define_field` with an array-index atom, which is how phase 2 stores elements.
7937    fn emit_define_index(&mut self, index: u32) {
7938        self.emit(
7939            Opcode::DefineField,
7940            &[Op::Atom(Atom::from_text(&index.to_string()))],
7941        );
7942    }
7943
7944    // -- functions ---------------------------------------------------------
7945
7946    fn compile_function(&mut self, func: &ast::Function) -> Result<CompiledFunction, SyntaxError> {
7947        self.compile_function_with_name(func, false)
7948    }
7949
7950    /// Compile a function, recording whether it is a *named function expression*.
7951    ///
7952    /// `var f = function g(){ return g }` has to see `g` inside its own body, but `g`
7953    /// must not leak outside. The reference does that by declaring `g` as a local of
7954    /// the function itself and initialising it with `special_object 2` (the current
7955    /// function), which is why this has to be known at compile time.
7956    fn compile_function_with_name(
7957        &mut self,
7958        func: &ast::Function,
7959        is_expression: bool,
7960    ) -> Result<CompiledFunction, SyntaxError> {
7961        let kind = match (func.is_generator, func.is_async) {
7962            (false, false) => FunctionKind::Normal,
7963            (true, false) => FunctionKind::Generator,
7964            (false, true) => FunctionKind::Async,
7965            (true, true) => FunctionKind::AsyncGenerator,
7966        };
7967        let mut state = FnState::new(
7968            func.name
7969                .as_ref()
7970                .map(|n| n.name.clone())
7971                .unwrap_or_default(),
7972            kind,
7973        );
7974        // The function's own mode, recorded by the parser. Inheriting the enclosing
7975        // function's instead let a nested `"use strict"` directive be ignored, so the
7976        // body ran with sloppy `this`, sloppy `arguments` and no const checks.
7977        state.strict = func.strict;
7978        // A function defined inside a `with` block keeps seeing that object: the guard
7979        // chain names the enclosing `<with>` locals, which resolve outward into closure
7980        // variables exactly like any other captured binding.
7981        state.inherited_with_names = self.cur().with_names.len();
7982        state.with_names = self.cur().with_names.clone();
7983        state.is_arrow = func.is_arrow;
7984        state.created_in_block = self.cur().current_block;
7985        // A default anywhere in the parameter list is what gives the function two
7986        // variable environments. The reference decides this the same way: it scans the
7987        // parenthesis for a top-level `=`, so a destructured name without a default
7988        // stays a plain function-scope binding.
7989        state.in_params = false;
7990        // The reference scans the parenthesis for *any* `=`, including one nested inside
7991        // a pattern, so `function f({a = 1})` has parameter expressions even though the
7992        // parameter itself carries no initialiser.
7993        state.has_parameter_expressions = func.params.iter().any(pattern_has_default);
7994        // `IsSimpleParameterList`: no default, no rest, no destructuring. Unlike the
7995        // flag above this looks at the *shape* of each parameter, not just for `=`.
7996        state.simple_parameter_list = func
7997            .params
7998            .iter()
7999            .all(|pattern| matches!(pattern.kind, PatternKind::Ident(_)));
8000        // A function born inside a parameter list inherits the prohibition: it must not
8001        // see the body bindings of the function it was created in.
8002        state.created_in_params = self.cur().in_params || self.cur().created_in_params;
8003        // A class constructor knows what it is only because the class told it.
8004        if let Some(kind) = self.cur().class_ctor_pending {
8005            state.ctor_kind = kind;
8006        }
8007        // A named *expression* binds its own name; a declaration's name is already
8008        // bound in the enclosing scope.
8009        state.self_name = if is_expression && !func.is_arrow {
8010            func.name.as_ref().map(|n| n.name.clone())
8011        } else {
8012            None
8013        };
8014        // Keep the written range so `Function.prototype.toString` can answer with the
8015        // original text rather than `[native code]`.
8016        //
8017        // It starts at the *parameter list*, not at the function: §20.2.3.5 removes the
8018        // accessor and generator prefixes, and for a method it must not include the name
8019        // or a leading `static`. `params_span` is exactly that boundary.
8020        // A *method* keeps the old `[native code]` answer: its reported text is defined
8021        // by the method-definition grammar (no name, no `static`, no `get`/`set`, but
8022        // the comments in between kept verbatim), and reconstructing that from a byte
8023        // span got it wrong in more cases than it got right. A plain function and an
8024        // arrow are the shapes libraries actually introspect, and those are exact.
8025        // A method's reported text starts at its **key** — `m(){}`, `[expr](){}`,
8026        // `#f /* a */ ( /* b */ ) {}` — which is exactly where the parser put `span.start`,
8027        // so the same slice works for every form. (`Params_span` is the boundary that
8028        // excludes `static`/`async`/`get`, which the spec's method grammar also omits.)
8029        // `source_span` is set only where the reported text is not the function's own
8030        // range — a class's constructor reports the whole class definition.
8031        let reported = func.source_span.unwrap_or(func.span);
8032        state.span = Some((reported.start.offset as usize, reported.end.offset as usize));
8033        state.line = func.span.start.line;
8034        state.column = func.span.start.column;
8035        // A function body has no hidden `<ret>` local; the value comes back on
8036        // the stack. Only a script keeps one.
8037        // Parameters are positional, so even a pattern occupies one argument slot. A
8038        // simple name is that slot itself; anything else (a pattern, a default, a rest
8039        // parameter) takes an anonymous slot and is unpicked into locals at the top of
8040        // the body, which is the only way one argument can bind several names.
8041        let mut prologue: Vec<(usize, Pattern)> = Vec::new();
8042        // `.length` stops at the first parameter that can be substituted: a default
8043        // fills a missing argument in, and a rest parameter absorbs the rest.
8044        let mut defined_args = func.params.len() as u32;
8045        for (index, param) in func.params.iter().enumerate() {
8046            match simple_parameter(param) {
8047                Some(name) => state.args.push(VarDef::var(name.name.clone())),
8048                None => {
8049                    state.args.push(VarDef::var(ANONYMOUS_BINDING));
8050                    prologue.push((index, param.clone()));
8051                }
8052            }
8053        }
8054        // A default anywhere before the end also ends the count, which the loop above
8055        // only catches for the parameter that carries it; `(a, b = 1, c)` is arity 1.
8056        for (position, param) in func.params.iter().enumerate() {
8057            if matches!(
8058                param.kind,
8059                PatternKind::Assign { .. } | PatternKind::Rest(_)
8060            ) {
8061                defined_args = position as u32;
8062                break;
8063            }
8064        }
8065        state.defined_args = defined_args;
8066        state.param_prologue = prologue;
8067        let depth = self.stack.len();
8068        self.stack.push(state);
8069        let result = self.compile_function_body(func);
8070        if result.is_err() {
8071            // A failed compile must not leave its `FnState` behind. Every caller
8072            // reads `self.state()` as "the function being compiled", so a leftover
8073            // frame silently retargets all later bookkeeping at a dead function.
8074            self.stack.truncate(depth);
8075        }
8076        result
8077    }
8078
8079    /// The body of a function, with its frame already pushed.
8080    fn compile_function_body(
8081        &mut self,
8082        func: &ast::Function,
8083    ) -> Result<CompiledFunction, SyntaxError> {
8084        let body_key = func.params_span.end.offset as u64;
8085        // Where the body begins, in source order. The runtime needs this to tell a
8086        // closure created by a default expression from one the body creates — the two see
8087        // different variable environments — and a bytecode offset would not survive the
8088        // instruction shuffling that building the frame does. Positions are in source
8089        // order, so a comparison answers it.
8090        self.state().body_start = (func.params_span.end.line, func.params_span.end.column);
8091        self.push_block(body_key, NO_PARENT);
8092        self.state().body_block = body_key;
8093        // An arrow with an expression body has no statements; the expression is
8094        // its `return`. Building the statement here keeps one code path below, and
8095        // matters for correctness beyond convenience: returning early with the new
8096        // `FnState` still on the stack would leave the compiler looking at the
8097        // wrong function, which surfaces as an unrelated underflow later.
8098        let concise = match &func.body {
8099            js_parse::ast::FunctionBody::Expr(value) => Some(Stmt::new(
8100                StmtKind::Return(Some(Box::new((**value).clone()))),
8101                value.span,
8102            )),
8103            js_parse::ast::FunctionBody::Block(_) => None,
8104        };
8105        let body: &[Stmt] = match &concise {
8106            Some(stmt) => std::slice::from_ref(stmt),
8107            None => func
8108                .body
8109                .statements()
8110                .ok_or_else(|| SyntaxError::new("unsupported function body", func.span))?,
8111        };
8112        let prologue = std::mem::take(&mut self.state().param_prologue);
8113        let has_param_scope = self.cur().has_parameter_expressions;
8114        // The parameter scope's own bindings, declared in source order.
8115        //
8116        // With parameter expressions the list gets a variable environment of its own, and
8117        // every name it binds is a `let` there. That is what puts the *list* in the
8118        // temporal dead zone: `function f(a = a){}` reads an uninitialised `a` and throws,
8119        // and `function f(x = y, y){}` does the same, where a single shared environment
8120        // would answer `undefined` to both.
8121        if has_param_scope {
8122            let mut declared: Vec<String> = Vec::new();
8123            for param in &func.params {
8124                let mut names = Vec::new();
8125                param.bound_names(&mut names);
8126                for name in names {
8127                    if declared.contains(&name.name) {
8128                        continue;
8129                    }
8130                    declared.push(name.name.clone());
8131                    self.declare_param_binding(&name.name);
8132                }
8133            }
8134        }
8135        // A pattern parameter binds its names as function-scope locals, so they have to
8136        // exist — and be unpicked from the argument — before the body runs. With a
8137        // parameter scope these are the *second* environment: the pattern fills the
8138        // parameter's copy, and the body's binding is filled from it afterwards.
8139        for (_, pattern) in &prologue {
8140            let mut names = Vec::new();
8141            pattern.bound_names(&mut names);
8142            for name in names {
8143                self.declare_var(&name.name.clone(), VarDef::var(name.name.clone()));
8144            }
8145        }
8146        self.hoist(body, body_key)?;
8147        // A constructor's prologue is not a parameter unpacking but the `this` binding:
8148        // a base constructor takes the receiver, a derived one starts in the dead zone
8149        // because only `super()` may produce it.
8150        match self.cur().ctor_kind {
8151            CtorKind::None => {}
8152            CtorKind::Base => {
8153                self.begin_this_local();
8154                self.emit(Opcode::CheckCtor, &[]);
8155                // Instance fields are installed at the top of a base constructor's body,
8156                // before any statement — `class C { x = 1; constructor() { this.x } }` sees
8157                // `1`. This used to be emitted at the *tail*, which made every field read
8158                // `undefined` inside the constructor that declared it.
8159                self.call_field_initialiser();
8160            }
8161            CtorKind::Derived => {
8162                self.declare("this", VarDef::lexical("this"));
8163                let slot = self.cur().vars.len() as u32 - 1;
8164                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8165                self.emit(Opcode::CheckCtor, &[]);
8166            }
8167        }
8168        // Entering the parameter list: everything it binds starts in the dead zone.
8169        // The order is the reference's — it walks the scope chain, which is prepended, so
8170        // the bindings come out newest first.
8171        for name in self.param_binding_names().into_iter().rev() {
8172            if let Some(slot) = self.param_binding_slot(&name) {
8173                self.emit(Opcode::SetLocUninitialized, &[Op::Slot(Slot::Loc(slot))]);
8174            }
8175        }
8176        // The whole parameter list is one scope, and nothing in the body exists yet, so
8177        // every name it mentions resolves against the parameter bindings and outward.
8178        self.state().in_params = has_param_scope;
8179        for (index, param) in func.params.iter().enumerate() {
8180            if let Some(pattern) = prologue_pattern(&prologue, index) {
8181                // A destructuring parameter *initialises* its bindings: with a parameter
8182                // scope they are the list's own `let`s, which is why the stores skip the
8183                // dead-zone check, and why the reference reads their properties with
8184                // `get_field2` — a `let` needs no reference.
8185                let kind = if has_param_scope {
8186                    VarDeclKind::Let
8187                } else {
8188                    VarDeclKind::Var
8189                };
8190                match &pattern.kind {
8191                    // `...rest` collects what is left rather than reading one slot.
8192                    PatternKind::Rest(inner) => {
8193                        self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8194                        self.destructure(inner, Some(kind))?;
8195                    }
8196                    _ => {
8197                        self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8198                        self.destructure(pattern, Some(kind))?;
8199                    }
8200                }
8201                continue;
8202            }
8203            // A plain name binds straight from its argument slot. With a parameter scope
8204            // the slot is also copied into the parameter binding, which is what a later
8205            // default (or a closure made among the defaults) reads.
8206            let Some(name) = simple_parameter(param) else {
8207                continue;
8208            };
8209            let target = self.param_binding_slot(&name.name);
8210            if matches!(param.kind, PatternKind::Rest(_)) {
8211                self.emit(Opcode::Rest, &[Op::Int(index as i32)]);
8212                if let Some(slot) = target {
8213                    self.emit(Opcode::SetLoc, &[Op::Slot(Slot::Loc(slot))]);
8214                }
8215                // `put_arg` rather than `set_arg`: the array is the last thing on the
8216                // stack and nothing keeps it. Named by hand because a name in the
8217                // parameter list resolves to the parameter binding, and this store has to
8218                // reach the *argument* — that is what the body reads.
8219                self.emit(Opcode::PutArg, &[Op::Slot(Slot::Arg(index as u32))]);
8220                continue;
8221            }
8222            if let PatternKind::Assign { default, .. } = &param.kind {
8223                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8224                let has_value = self.new_label();
8225                self.emit(Opcode::Dup, &[]);
8226                self.emit(Opcode::IsUndefined, &[]);
8227                self.emit_jump(Opcode::IfFalse, has_value, &[]);
8228                self.emit(Opcode::Drop, &[]);
8229                self.expr(default)?;
8230                self.set_name_if_anonymous(default, &Wtf8::new(&name.name));
8231                // The argument slot keeps the substituted value, because the *body* reads
8232                // the slot rather than the parameter binding — so this store is named
8233                // explicitly, like the rest parameter's.
8234                self.emit(Opcode::SetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8235                self.place_label(has_value);
8236                if let Some(slot) = target {
8237                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8238                }
8239                continue;
8240            }
8241            if let Some(slot) = target {
8242                self.emit(Opcode::GetArg, &[Op::Slot(Slot::Arg(index as u32))]);
8243                self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(slot))]);
8244            }
8245        }
8246        // Copy the parameter scope into the body. A plain parameter needs nothing: the
8247        // body reads its argument slot, and the list kept the two in step. A name a
8248        // pattern bound has no argument slot of its own, so the body gets a `var` filled
8249        // from the parameter's copy — and *that* is why an assignment inside a default
8250        // does not reach the body.
8251        if has_param_scope {
8252            for (_, pattern) in &prologue {
8253                let mut names = Vec::new();
8254                pattern.bound_names(&mut names);
8255                for name in names {
8256                    let Some(slot) = self.param_binding_slot(&name.name) else {
8257                        continue;
8258                    };
8259                    let Some(body) = self.body_var_slot(&name.name) else {
8260                        continue;
8261                    };
8262                    self.emit(Opcode::GetLocCheck, &[Op::Slot(Slot::Loc(slot))]);
8263                    self.emit(Opcode::PutLoc, &[Op::Slot(Slot::Loc(body))]);
8264                }
8265            }
8266        }
8267        // The parameter list is over; from here on a direct `eval` belongs to the body.
8268        self.state().in_params = false;
8269        // Entering the body's own scope comes *after* the parameter list: the body's
8270        // `let`s are not in existence while the defaults run, and the reference emits
8271        // their `set_loc_uninitialized` only once the parameters are bound.
8272        self.emit_scope_enter(body_key);
8273        // A generator starts suspended: `initial_yield` parks the body so that creating one
8274        // runs no body code until the first `next()`.
8275        //
8276        // It comes *after* the parameter unpacking, not before, because a parameter
8277        // initialiser is not body code — `function* g(a = sideEffect())` must run
8278        // `sideEffect()` when `g` is *called*. Emitting `initial_yield` first parked the
8279        // defaults too, so `function* g(a = (() => { throw new Error })())` did not throw
8280        // until the first `next()` and 29 test262 cases that check for a synchronous throw
8281        // saw none at all.
8282        //
8283        // An async function does **not** get one. Its body runs synchronously up to the
8284        // first `await` — `async function f(){ log.push("a"); await 0 }` records `a`
8285        // before its caller's next statement — so an `initial_yield` here would park the
8286        // body before it started, which is not fixable at run time: the suspension looks
8287        // exactly like a real `await`.
8288        if self.cur().kind.is_generator() {
8289            self.emit(Opcode::InitialYield, &[]);
8290        }
8291        // Through `stmts`: the body is a block, and a `using` declaration in it is a
8292        // disposal region.
8293        self.stmts(body)?;
8294        // The implicit return only exists if control can actually get here: an
8295        // infinite loop never falls off the end.
8296        if self.end_is_reachable() {
8297            if self.cur().is_suspending() {
8298                // Falling off the end finishes the generator with `undefined`, and the
8299                // value is what tells the resume machinery "completed" rather than
8300                // "suspended".
8301                self.emit(Opcode::Undefined, &[]);
8302                self.emit(Opcode::ReturnAsync, &[]);
8303            } else {
8304                self.emit_class_constructor_tail();
8305            }
8306        }
8307        // Resolution runs while this function is still on the stack: capturing a
8308        // variable from an enclosing function means reaching into that
8309        // function's state, which requires the whole chain to be present.
8310        Ok(self.finish_current())
8311    }
8312
8313    /// Put every binding of a function that contains a direct `eval` into a cell.
8314    ///
8315    /// A direct eval can name any binding in scope, and any closure it creates has to
8316    /// keep sharing that binding after the function returns — `for (let i …)
8317    /// eval("push(() => i)")` collects one closure per iteration and each must read its
8318    /// own `i`. A copy in a side table would freeze the value, so the binding has to be
8319    /// a cell. Doing this unconditionally for such functions is the cheap, honest
8320    /// answer: the alternative is knowing at compile time which names a string will
8321    /// mention.
8322    fn capture_everything_for_eval(&mut self) {
8323        let current = self.stack.len() - 1;
8324        if !self.stack[current].has_direct_eval {
8325            return;
8326        }
8327        for arg in &mut self.stack[current].args {
8328            arg.is_captured = true;
8329        }
8330        for var in &mut self.stack[current].vars {
8331            var.is_captured = true;
8332        }
8333    }
8334
8335    /// Whether the current position in the instruction stream can be reached.
8336    ///
8337    /// A walk over the control-flow graph, using labels as instruction indices.
8338    /// The reference does the same thing to decide whether an implicit
8339    /// `return_undef` is needed.
8340    fn end_is_reachable(&self) -> bool {
8341        let state = self.cur();
8342        reachable_instructions(state, state.insns.len())[state.insns.len()]
8343    }
8344
8345    /// Resolve and assemble the function on top of the compiler stack, then pop
8346    /// it.
8347    fn finish_current(&mut self) -> CompiledFunction {
8348        self.provide_param_arguments();
8349        self.provide_arguments();
8350        self.provide_this_local();
8351        self.provide_new_target_local();
8352        self.provide_home_object_local();
8353        self.provide_active_func_local();
8354        self.provide_self_name();
8355        self.materialize_eval_sites();
8356        self.capture_everything_for_eval();
8357        let (mut resolved, resolved_pos) = resolve(&mut self.stack);
8358        // Captured bindings need a reference cell; the count goes in the header so
8359        // the runtime knows how many cells to allocate on entry.
8360        let current = self.stack.len() - 1;
8361        let captured = self.stack[current]
8362            .args
8363            .iter()
8364            .filter(|a| a.is_captured)
8365            .count()
8366            + self.stack[current]
8367                .vars
8368                .iter()
8369                .filter(|v| v.is_captured)
8370                .count();
8371        self.stack[current].var_ref_count = captured as u32;
8372        // The scope chain is only final now that every binding is known.
8373        rebuild_scope_chain(&mut self.stack[current]);
8374        let (code, stack_size, positions) =
8375            assemble(&mut resolved, &resolved_pos, &mut self.stack[current]);
8376        let _ = &mut resolved;
8377        let mut state = self.stack.pop().expect("a function is being compiled");
8378        CompiledFunction {
8379            name: state.name,
8380            kind: state.kind,
8381            strict: state.strict,
8382            is_derived_constructor: matches!(state.ctor_kind, CtorKind::Derived),
8383            is_arrow: state.is_arrow,
8384            has_parameter_expressions: state.has_parameter_expressions,
8385            simple_parameter_list: state.simple_parameter_list,
8386            body_start: state.body_start,
8387            args: state.args,
8388            defined_args: state.defined_args,
8389            vars: state.vars,
8390            closure_vars: state.closure_vars,
8391            cpool: state.cpool,
8392            atoms: state.atoms,
8393            code,
8394            stack_size,
8395            var_ref_count: state.var_ref_count,
8396            positions,
8397            source: self.function_source(state.span, state.line, state.column),
8398            line: state.line,
8399            column: state.column,
8400            filename: None,
8401            eval_sites: state.eval_sites,
8402            module: state.module.take().map(Box::new),
8403        }
8404    }
8405}
8406
8407/// Assign each binding a scope level and rebuild the scope chains.
8408///
8409/// Levels are numbered in the order the blocks appear, with 0 reserved for the
8410/// function scope where `var` and hoisted functions live. Every binding outside
8411/// level 0 gets a `scope_next` link to the next binding visible from the same
8412/// point, so walking a block's chain enumerates exactly the bindings live there.
8413///
8414/// The links cannot be filled in while hoisting: `{ let a } let b` needs `a` to
8415/// point at `b`, which is declared later in the source but earlier in the chain.
8416fn rebuild_scope_chain(state: &mut FnState) {
8417    // Block key -> level. Level 0 is the function scope, keyed by the sentinel so a
8418    // real block that happens to start at offset zero keeps its own level instead of
8419    // being merged into the function scope.
8420    let mut levels: Vec<u64> = vec![FUNCTION_SCOPE];
8421    for block in &state.blocks {
8422        if !levels.contains(&block.key) {
8423            levels.push(block.key);
8424        }
8425    }
8426    let level_of = |key: u64| -> usize { levels.iter().position(|k| *k == key).unwrap_or(0) };
8427    let parent_level = |level: usize| -> usize {
8428        if level == 0 {
8429            return 0;
8430        }
8431        let key = levels[level];
8432        let parent = state
8433            .blocks
8434            .iter()
8435            .find(|b| b.key == key)
8436            .map(|b| b.parent)
8437            .unwrap_or(FUNCTION_SCOPE);
8438        level_of(parent)
8439    };
8440
8441    // Own bindings per level, in declaration order.
8442    let mut own: Vec<Vec<usize>> = vec![Vec::new(); levels.len()];
8443    let keys: Vec<u64> = (0..state.vars.len())
8444        .map(|index| {
8445            state
8446                .var_block
8447                .get(index)
8448                .copied()
8449                .unwrap_or(FUNCTION_SCOPE)
8450        })
8451        .collect();
8452    for (index, key) in keys.into_iter().enumerate() {
8453        // The parameter scope is not a block: it is a level of its own with no parent,
8454        // assigned below. Letting it land in level 0 would chain the body's bindings onto
8455        // it, which the reference does not do — the two environments are siblings.
8456        if key == PARAM_SCOPE {
8457            continue;
8458        }
8459        let level = level_of(key);
8460        state.vars[index].scope_level = level as u32;
8461        // A `catch` parameter is part of the runtime scope chain even though it is
8462        // not lexical: the handler's own bindings chain on to it, which is why the
8463        // reference prints `let y [next:1]` with `e` at 1.
8464        if state.vars[index].is_lexical || state.vars[index].kind == crate::bytecode::VarKind::Catch
8465        {
8466            own[level].push(index);
8467        }
8468    }
8469
8470    // A scope's chain is its own bindings in reverse declaration order followed
8471    // by the enclosing scope's chain.
8472    let mut head = vec![-1i32; levels.len()];
8473    for level in 0..levels.len() {
8474        let inherited = if level == 0 {
8475            -1
8476        } else {
8477            head[parent_level(level)]
8478        };
8479        let chain: Vec<usize> = own[level].iter().rev().copied().collect();
8480        head[level] = chain.first().map_or(inherited, |first| *first as i32);
8481        for (position, &index) in chain.iter().enumerate() {
8482            let next = chain
8483                .get(position + 1)
8484                .map_or(inherited, |next| *next as i32);
8485            state.vars[index].scope_next = if next < 0 { None } else { Some(next) };
8486        }
8487    }
8488    state.block_heads = head;
8489
8490    // The parameter list is a scope of its own, and it has no parent: the reference pops
8491    // it before the body exists, so its chain ends in `ARG_SCOPE_END` (`-2`) rather than
8492    // the `-1` a block uses. A level past every real block keeps it out of the walk above
8493    // — nothing but the dump reads it — and the links run newest-to-oldest through the
8494    // bindings themselves, which is the order `set_loc_uninitialized` walks.
8495    let param_level = levels.len() as u32;
8496    let mut previous: Option<usize> = None;
8497    for index in 0..state.vars.len() {
8498        if state.var_block.get(index).copied() != Some(PARAM_SCOPE) || !state.vars[index].is_lexical
8499        {
8500            continue;
8501        }
8502        state.vars[index].scope_level = param_level;
8503        state.vars[index].scope_next = Some(previous.map_or(-2, |previous| previous as i32));
8504        previous = Some(index);
8505    }
8506}
8507
8508/// This is where names become slots and where the temporal dead zone shows up in
8509/// the instruction stream: a read of a `let`/`const` binding compiles to
8510/// `get_loc_check`, which throws if the binding is still uninitialised.
8511///
8512/// The peephole pass from the reference implementation is applied at the end,
8513/// for the same reason it is applied to resolved bytecode there: the patterns are
8514/// stated in terms of `put_loc`/`set_loc` pairs, which only exist after
8515/// resolution. Deleted instructions stay in the list as `None` so that label
8516/// indices remain valid; [`Assembler`] maps them to byte offsets.
8517/// A resolved instruction and the source position it came from.
8518type ResolvedInsn = Option<(Opcode, Vec<Op>)>;
8519
8520/// A resolved instruction paired with its position, which is what `assemble` consumes.
8521type PositionedInsn = (Opcode, Vec<Op>);
8522
8523fn resolve(stack: &mut [FnState]) -> (Vec<ResolvedInsn>, Vec<Option<Position>>) {
8524    let current = stack.len() - 1;
8525    // Dead-code elimination, on the symbolic form where labels are still
8526    // instruction indices. A `break` inside a loop leaves the trailing `goto`
8527    // unreachable, and a `return` leaves everything after it unreachable; the
8528    // reference drops both. Doing it here means the emitter never has to think
8529    // about reachability.
8530    strip_empty_gosubs(stack, current);
8531    eliminate_dead_code(stack, current);
8532    let insns = std::mem::take(&mut stack[current].insns);
8533    // One entry per instruction, carried alongside: `insn_pos` is index-aligned with
8534    // `insns`, and every arm below pushes exactly one instruction, so the positions
8535    // stay aligned with `out`.
8536    let positions = std::mem::take(&mut stack[current].insn_pos);
8537    let mut out: Vec<Option<(Opcode, Vec<Op>)>> = Vec::with_capacity(insns.len());
8538    let mut out_pos: Vec<Option<Position>> = Vec::with_capacity(insns.len());
8539    for (index, insn) in insns.iter().enumerate() {
8540        let pos = positions.get(index).copied().flatten();
8541        out_pos.push(pos);
8542        match insn {
8543            Insn::Fixed { op, operands } => {
8544                let operands = operands
8545                    .iter()
8546                    .map(|operand| match operand {
8547                        Op::Atom(atom) => {
8548                            Op::AtomId(intern_atom_value(&mut stack[current], atom.clone()))
8549                        }
8550                        other => other.clone(),
8551                    })
8552                    .collect();
8553                out.push(Some((*op, operands)));
8554            }
8555            Insn::Var {
8556                action,
8557                name,
8558                block,
8559                in_params,
8560            } => {
8561                // Both reads and writes in the parameter list address the parameter
8562                // scope. That is what puts the list in the temporal dead zone — a read of
8563                // a later parameter is `get_loc_check` on an uninitialised slot — and it
8564                // is also what keeps an assignment made inside a default away from the
8565                // body, which sees a separate environment.
8566                let slot = resolve_slot(stack, current, name, *block, *in_params);
8567                // A store to the name of a named function expression is special: the
8568                // reference drops it in sloppy mode and throws in strict mode, because
8569                // the binding is immutable but only *checked* when the body is strict.
8570                // The same rule applies when the name is reached through a closure:
8571                // `var f = function myfunc() { (() => { myfunc = 1 })() }` has to drop
8572                // the store in the arrow too, not just in the function that owns the
8573                // binding. Reaching the owner means walking the chain of closure
8574                // entries, which is what `self_name_binding` does.
8575                let self_name = matches!(action, VarAction::Put | VarAction::Set)
8576                    .then(|| {
8577                        // A local of this function is the common case and needs no
8578                        // chain walk; only an access that resolves elsewhere can be
8579                        // pointing at an enclosing function's name binding.
8580                        if let Slot::Loc(index) = slot {
8581                            stack[current]
8582                                .vars
8583                                .get(index as usize)
8584                                .filter(|var| var.kind == VarKind::FunctionName)
8585                                .map(|var| var.is_const)
8586                        } else {
8587                            self_name_binding(stack, current, name, *block)
8588                        }
8589                    })
8590                    .flatten();
8591                if let Some(is_const) = self_name {
8592                    out.push(Some(if is_const {
8593                        (
8594                            Opcode::ThrowError,
8595                            vec![
8596                                Op::AtomId(intern_atom(&mut stack[current], name)),
8597                                Op::Int(0),
8598                            ],
8599                        )
8600                    } else {
8601                        (Opcode::Drop, Vec::new())
8602                    }));
8603                    continue;
8604                }
8605                out.push(Some(variable_instruction(stack, current, *action, slot)));
8606            }
8607            Insn::CloseCaptured { name, block } => {
8608                // The block matters: a loop variable is scoped to the `for` head's own
8609                // block, so resolving it against block 0 would miss it entirely and
8610                // silently emit nothing.
8611                let slot = resolve_slot(stack, current, name, *block, false);
8612                // Only a local with a reference cell has anything to close. A global
8613                // or a never-captured local resolves to no instruction at all, which
8614                // keeps the bytecode identical to the reference's.
8615                if let Slot::Loc(index) = slot
8616                    && stack[current]
8617                        .vars
8618                        .get(index as usize)
8619                        .is_some_and(|v| v.is_captured)
8620                {
8621                    out.push(Some((Opcode::CloseLoc, vec![Op::Slot(slot)])));
8622                } else {
8623                    out.push(None);
8624                }
8625            }
8626            Insn::DeleteVar { name } => {
8627                // A binding — a local, an argument, or a declared global — cannot be
8628                // deleted, and the reference encodes that as a constant `push_false`.
8629                // Only an implicit global needs the runtime lookup.
8630                if matches!(
8631                    resolve_slot(stack, current, name, 0, false),
8632                    Slot::Global(_)
8633                ) {
8634                    let atom = intern_atom(&mut stack[current], name);
8635                    out.push(Some((Opcode::DeleteVar, vec![Op::AtomId(atom)])));
8636                } else {
8637                    out.push(Some((Opcode::PushFalse, Vec::new())));
8638                }
8639            }
8640            Insn::Dead => out.push(None),
8641        }
8642    }
8643    // Which label (if any) sits on each instruction, so the jump patterns can
8644    // tell whether they would cross a jump target.
8645    let mut label_at: Vec<Option<u32>> = vec![None; out.len() + 1];
8646    for (id, placed) in stack[current].labels.iter().enumerate() {
8647        if let Some(index) = *placed
8648            && index < label_at.len()
8649            && label_at[index].is_none()
8650        {
8651            label_at[index] = Some(id as u32);
8652        }
8653    }
8654    if std::env::var_os("QJS_DEBUG").is_some() {
8655        eprintln!("--- peephole entry ---");
8656        for (i, e) in out.iter().enumerate() {
8657            eprintln!("{i}: {e:?}");
8658        }
8659        eprintln!("label_at: {label_at:?}");
8660    }
8661    peephole(&mut out, &label_at, &stack[current].labels);
8662    (out, out_pos)
8663}
8664
8665/// Find where `name` lives, capturing it in an enclosing function when needed.
8666///
8667/// The search runs outward through the enclosing functions' states, which are
8668/// still on the compiler stack while a nested function is resolved. Finding the
8669/// name in an enclosing function is what creates a closure reference, and every
8670/// function in between has to forward it — a function can only reach its own
8671/// parent's frame.
8672///
8673/// A name declared nowhere is a global. The reference does *not* look it up by
8674/// name from the inner function: the top-level function gets one `[global]`
8675/// entry and every nested function gets a `[global_ref<n>]` pointing at its
8676/// parent's entry, which is why `function f(){ g(); }` shows `[global_ref0]`
8677/// rather than `[global]`.
8678/// The lexical blocks enclosing `block`, innermost first.
8679fn block_chain(state: &FnState, block: u64) -> Vec<u64> {
8680    let mut chain = Vec::new();
8681    let mut current = Some(block);
8682    while let Some(key) = current {
8683        // `NO_PARENT` is not a block, so the walk ends here. Stopping on the sentinel
8684        // explicitly (rather than on "no block with this key") is what keeps a block
8685        // that happens to sit at offset zero from being mistaken for the terminator.
8686        if key == NO_PARENT || chain.contains(&key) {
8687            break;
8688        }
8689        chain.push(key);
8690        current = state.blocks.iter().find(|b| b.key == key).map(|b| b.parent);
8691    }
8692    chain
8693}
8694
8695/// The `const`-ness of a named function expression's own name, if `name` resolves to one.
8696///
8697/// The binding may be several functions away: an arrow nested in `function myfunc`
8698/// reaches `myfunc` through a chain of closure entries, so finding out *what* it names
8699/// means following `Ref` entries down and then reading the owning function's var table.
8700fn self_name_binding(stack: &[FnState], current: usize, name: &str, block: u64) -> Option<bool> {
8701    let state = stack.get(current)?;
8702    // A parameter shadows everything and is never a function-expression name.
8703    if state.args.iter().any(|arg| arg.name == name) {
8704        return None;
8705    }
8706    // A local of this very function: the answer is in its var table.
8707    if let Some(index) = local_slot_index(state, name, block) {
8708        let var = state.vars.get(index)?;
8709        return (var.kind == VarKind::FunctionName).then_some(var.is_const);
8710    }
8711    // Otherwise the name lives further out, and the closure entry says how to get
8712    // there. `Local` names the owner's slot directly; `Ref` names the next level's
8713    // closure entry, so the walk continues downwards.
8714    let mut level = current;
8715    let mut index = state
8716        .closure_vars
8717        .iter()
8718        .position(|closure| closure.name == name)?;
8719    loop {
8720        let state = stack.get(level)?;
8721        let closure = state.closure_vars.get(index)?;
8722        match closure.closure_type {
8723            ClosureType::Local => {
8724                let owner = stack.get(level.checked_sub(1)?)?;
8725                let var = owner.vars.get(closure.var_idx as usize)?;
8726                return (var.kind == VarKind::FunctionName).then_some(var.is_const);
8727            }
8728            ClosureType::Arg => return None,
8729            ClosureType::Ref => {
8730                level -= 1;
8731                index = closure.var_idx as usize;
8732            }
8733            // A global is never a function-expression name.
8734            ClosureType::Global
8735            | ClosureType::GlobalDecl
8736            | ClosureType::GlobalRef
8737            | ClosureType::ModuleDecl
8738            | ClosureType::ModuleImport => return None,
8739        }
8740    }
8741}
8742
8743/// The index of `name`'s binding in `state`, looked up the way [`resolve_slot`] does.
8744fn local_slot_index(state: &FnState, name: &str, block: u64) -> Option<usize> {
8745    block_chain(state, block).into_iter().find_map(|scope| {
8746        state.vars.iter().enumerate().find_map(|(index, var)| {
8747            (var.name == name && state.var_block.get(index).copied() == Some(scope))
8748                .then_some(index)
8749        })
8750    })
8751}
8752
8753/// Declare `name` as a binding of `state`'s parameter scope, returning its slot.
8754fn declare_param_var_at(state: &mut FnState, name: &str) -> u32 {
8755    if let Some(index) = state.vars.iter().enumerate().position(|(index, var)| {
8756        var.name == name && state.var_block.get(index).copied() == Some(PARAM_SCOPE)
8757    }) {
8758        return index as u32;
8759    }
8760    state.var_block.push(PARAM_SCOPE);
8761    state.vars.push(VarDef::var(name));
8762    state.vars.len() as u32 - 1
8763}
8764
8765/// The name a parameter binds straight from its argument slot, if it has one.
8766///
8767/// A plain name does — with or without a default, and with or without `...`. Everything
8768/// else is a pattern, which takes an anonymous slot for the parameter list to unpick; the
8769/// reference names the argument in the first case and leaves it `<null>` in the second,
8770/// so both the dump and the closures that capture the argument depend on this.
8771fn simple_parameter(param: &Pattern) -> Option<&Ident> {
8772    match &param.kind {
8773        PatternKind::Ident(name) => Some(name),
8774        PatternKind::Assign { target, .. } => match &target.kind {
8775            PatternKind::Ident(name) => Some(name),
8776            _ => None,
8777        },
8778        PatternKind::Rest(inner) => match &inner.kind {
8779            PatternKind::Ident(name) => Some(name),
8780            _ => None,
8781        },
8782        _ => None,
8783    }
8784}
8785
8786/// The pattern a parameter list has to unpick, if `index` is one of them.
8787fn prologue_pattern(prologue: &[(usize, Pattern)], index: usize) -> Option<&Pattern> {
8788    prologue
8789        .iter()
8790        .find(|(at, _)| *at == index)
8791        .map(|(_, pattern)| pattern)
8792}
8793
8794fn pattern_has_default(pattern: &Pattern) -> bool {
8795    match &pattern.kind {
8796        PatternKind::Assign { .. } => true,
8797        PatternKind::Rest(inner) => pattern_has_default(inner),
8798        PatternKind::Array { elements, rest } => {
8799            elements.iter().flatten().any(element_has_default)
8800                || rest.as_deref().is_some_and(rest_has_default)
8801        }
8802        PatternKind::Object { properties, rest } => {
8803            properties.iter().flatten().any(element_has_default)
8804                || rest.as_deref().is_some_and(rest_has_default)
8805        }
8806        _ => false,
8807    }
8808}
8809
8810fn element_has_default(element: &PatternElement) -> bool {
8811    match element {
8812        PatternElement::Pattern(pattern) => pattern_has_default(pattern),
8813        PatternElement::Property { value, .. } => pattern_has_default(value),
8814    }
8815}
8816
8817fn rest_has_default(rest: &RestElement) -> bool {
8818    match rest {
8819        RestElement::Pattern(pattern) => pattern_has_default(pattern),
8820        RestElement::Member(_) => false,
8821    }
8822}
8823
8824/// Whether a function-scope binding is visible to the parameter list.
8825///
8826/// The parameter list runs before the body, so the body's `var`s and function
8827/// declarations do not exist yet — a name that only the body declares has to resolve
8828/// outward instead. What *does* exist by then is the compiler's own prologue: the
8829/// self-name of a named function expression (bound by `special_object 2` before anything
8830/// else), `this` and `new.target`. Those stay visible, which is what makes
8831/// `function f(a = this)` and `var f = function f(a = f)` work.
8832///
8833/// `arguments` is handled separately, as a binding of the parameter scope itself: with
8834/// parameter expressions the reference creates two of them, and the one the parameter
8835/// list sees is not the one the body sees (`function f(a = eval("var arguments = 1"))`).
8836fn visible_in_params(var: &VarDef) -> bool {
8837    var.kind == VarKind::FunctionName || var.name == "this" || var.name == "new.target"
8838}
8839
8840fn resolve_slot(
8841    stack: &mut [FnState],
8842    current: usize,
8843    name: &str,
8844    block: u64,
8845    in_params: bool,
8846) -> Slot {
8847    // The parameter list's own bindings. They are consulted first because they shadow
8848    // the argument slots they were copied from: `function f(a = 1, p = () => a)` keeps
8849    // `a` in the parameter scope, so a closure made there reads the parameter even after
8850    // the body assigns to its own `a`.
8851    if in_params
8852        && let Some(index) = stack[current]
8853            .vars
8854            .iter()
8855            .enumerate()
8856            .position(|(index, var)| {
8857                var.name == name
8858                    && stack[current].var_block.get(index).copied() == Some(PARAM_SCOPE)
8859            })
8860    {
8861        return Slot::Loc(index as u32);
8862    }
8863    // A name can be bound more than once: two `catch` parameters in nested
8864    // handlers are two slots. The binding that wins is the one whose scope encloses
8865    // the access, and among those the innermost — so the blocks are walked outward
8866    // and the first binding found on the way is the one that counts. A binding in
8867    // no block (`var`) is reachable from anywhere, which is why the function scope
8868    // is the end of the walk.
8869    //
8870    // The block walk comes *before* the argument slots, because a block may shadow a
8871    // parameter: `function f(a){ { let a = 2 } }` writes the inner `a`, and the argument
8872    // slot is only the answer once nothing nearer claims the name.
8873    let chain = block_chain(&stack[current], block);
8874    for scope in &chain {
8875        let found = stack[current]
8876            .vars
8877            .iter()
8878            .enumerate()
8879            .find(|(index, var)| {
8880                var.name == name && stack[current].var_block.get(*index).copied() == Some(*scope)
8881            })
8882            .map(|(index, _)| index);
8883        if let Some(index) = found {
8884            return Slot::Loc(index as u32);
8885        }
8886    }
8887    // A parameter, which is neither block-scoped nor a plain function-scope `var`: it has
8888    // its own slot, and `var` of the same name in the body is the same binding.
8889    if let Some(index) = stack[current].args.iter().position(|a| a.name == name) {
8890        return Slot::Arg(index as u32);
8891    }
8892    // Function-scope bindings — `var` and function declarations — are recorded with
8893    // the sentinel block `0`, which no real scope uses, so the walk above cannot see
8894    // them. They are reachable from anywhere in the function, which is exactly what
8895    // the sentinel means.
8896    //
8897    // This pass is *only* for those. A lexical binding has to be found through the
8898    // chain or not at all, and looking a name up without its block is precisely how
8899    // `var x = 1; { let x = 2; } x` used to see the inner `x`, and how a `let` in a
8900    // block leaked out of it.
8901    let function_scoped = stack[current]
8902        .vars
8903        .iter()
8904        .enumerate()
8905        .find(|(index, var)| {
8906            var.name == name
8907                && stack[current].var_block.get(*index).copied() == Some(FUNCTION_SCOPE)
8908                && (!in_params || visible_in_params(var))
8909        })
8910        .map(|(index, _)| index);
8911    if let Some(index) = function_scoped {
8912        return Slot::Loc(index as u32);
8913    }
8914    if let Some(index) = stack[current]
8915        .closure_vars
8916        .iter()
8917        .position(|c| c.name == name)
8918    {
8919        return slot_for_closure(&stack[current].closure_vars[index], index as u32);
8920    }
8921
8922    for owner in (0..current).rev() {
8923        // The nested function was created inside one of this frame's blocks, and the
8924        // outermost visible binding is the innermost block on that chain — not whatever
8925        // comes first in the variable table. `function f(){ class S{} }` has two `S`
8926        // bindings: the `let S` inside `f` and the `const S` inside the class body, and
8927        // the class body is the one a method may see.
8928        let entry = stack
8929            .get(owner + 1)
8930            .map(|s| s.created_in_block)
8931            .unwrap_or(0);
8932        let lexical = block_chain(&stack[owner], entry)
8933            .into_iter()
8934            .find_map(|scope| {
8935                stack[owner]
8936                    .vars
8937                    .iter()
8938                    .enumerate()
8939                    .find(|(index, var)| {
8940                        var.name == name
8941                            && stack[owner].var_block.get(*index).copied() == Some(scope)
8942                    })
8943                    .map(|(index, _)| index)
8944            });
8945        // A function born in a parameter list sees that list's bindings, not the body's:
8946        // the parameter scope is the environment it was created in.
8947        let in_param_scope = stack
8948            .get(owner + 1)
8949            .is_some_and(|child| child.created_in_params)
8950            .then(|| {
8951                stack[owner]
8952                    .vars
8953                    .iter()
8954                    .enumerate()
8955                    .position(|(index, var)| {
8956                        var.name == name
8957                            && stack[owner].var_block.get(index).copied() == Some(PARAM_SCOPE)
8958                    })
8959            })
8960            .flatten();
8961        let found = if let Some(index) = in_param_scope {
8962            let var = &stack[owner].vars[index];
8963            Some(Found::Local(
8964                ClosureType::Local,
8965                index as u32,
8966                var.is_const,
8967                var.needs_check(),
8968            ))
8969        } else if let Some(index) = stack[owner].args.iter().position(|a| a.name == name) {
8970            Some(Found::Local(ClosureType::Arg, index as u32, false, false))
8971        } else if let Some(index) = lexical {
8972            let var = &stack[owner].vars[index];
8973            Some(Found::Local(
8974                ClosureType::Local,
8975                index as u32,
8976                var.is_const,
8977                var.needs_check(),
8978            ))
8979        } else if let Some(index) = stack[owner]
8980            .vars
8981            .iter()
8982            .enumerate()
8983            .find_map(|(index, var)| {
8984                // A function created inside a parameter list must not see the body of the
8985                // function it was born in; see [`FnState::created_in_params`].
8986                let hidden = stack
8987                    .get(owner + 1)
8988                    .is_some_and(|child| child.created_in_params);
8989                (var.name == name && (!hidden || visible_in_params(var))).then_some(index)
8990            })
8991        {
8992            let var = &stack[owner].vars[index];
8993            Some(Found::Local(
8994                ClosureType::Local,
8995                index as u32,
8996                var.is_const,
8997                var.needs_check(),
8998            ))
8999        } else if stack[owner].self_name.as_deref() == Some(name) {
9000            // A named function expression's own name. The reference declares it here,
9001            // on the first lookup that fails, rather than up front — and that is what
9002            // makes it reachable from a *nested* function: the nested lookup is what
9003            // walks out and creates the binding. A direct reference in the body is
9004            // caught the same way, which is why `provide_self_name` only has to add
9005            // the prologue.
9006            let strict = stack[owner].strict;
9007            stack[owner].var_block.push(FUNCTION_SCOPE);
9008            stack[owner].vars.push(VarDef {
9009                kind: VarKind::FunctionName,
9010                // In strict mode the name is immutable, so a store raises; sloppy
9011                // mode drops the store instead (see `variable_instruction`).
9012                is_const: strict,
9013                ..VarDef::var(name)
9014            });
9015            let index = stack[owner].vars.len() as u32 - 1;
9016            Some(Found::Local(ClosureType::Local, index, strict, false))
9017        } else if let Some(index) = stack[owner]
9018            .closure_vars
9019            .iter()
9020            .position(|c| c.name == name)
9021        {
9022            let closure = &stack[owner].closure_vars[index];
9023            Some(match closure.closure_type {
9024                // `GlobalRef` belongs here too: it is a *global* reached through this
9025                // frame's reference table, so treating it as a `Ref` to a local cell makes
9026                // the reader look for a cell no frame ever fills. That is how a second
9027                // function using `eval` in its parameter list read `undefined` after a
9028                // sibling had already made `eval` a closure entry.
9029                ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef => {
9030                    Found::Global(index as u32)
9031                }
9032                // A module variable is a cell in the *module's* environment, which is
9033                // the module body's parent as far as a nested function is concerned — so
9034                // it is captured as a plain reference, not looked up as a global.
9035                ClosureType::ModuleDecl | ClosureType::ModuleImport => Found::Local(
9036                    ClosureType::Ref,
9037                    index as u32,
9038                    closure.is_const,
9039                    closure.is_lexical,
9040                ),
9041                _ => Found::Local(
9042                    ClosureType::Ref,
9043                    index as u32,
9044                    closure.is_const,
9045                    closure.is_lexical,
9046                ),
9047            })
9048        } else {
9049            None
9050        };
9051        let Some(found) = found else { continue };
9052
9053        let (is_const, is_lexical) = match found {
9054            Found::Local(_, _, is_const, is_lexical) => (is_const, is_lexical),
9055            Found::Global(_) => (false, false),
9056        };
9057        // Mark the owner's binding as captured so it moves into a reference cell.
9058        if let Found::Local(ClosureType::Arg | ClosureType::Local, index, _, _) = found {
9059            let slot = match found {
9060                Found::Local(ClosureType::Arg, _, _, _) => &mut stack[owner].args[index as usize],
9061                _ => &mut stack[owner].vars[index as usize],
9062            };
9063            slot.is_captured = true;
9064        }
9065        // Forward the reference through every function in between.
9066        let mut previous = match found {
9067            Found::Local(kind, index, _, _) => (kind, index),
9068            Found::Global(index) => (ClosureType::Global, index),
9069        };
9070        for level in owner + 1..=current {
9071            let kind = match (previous.0, level) {
9072                // A global stays a global at *every* level. Without `GlobalRef` in
9073                // this arm the second nested function over the same global got a
9074                // `Ref` to a cell no frame ever held, so the innermost closure read
9075                // `undefined` — which is how a two-deep getter lost its outer
9076                // variable.
9077                (ClosureType::Global | ClosureType::GlobalDecl | ClosureType::GlobalRef, _) => {
9078                    ClosureType::GlobalRef
9079                }
9080                (ClosureType::Arg | ClosureType::Local, level) if level == owner + 1 => previous.0,
9081                _ => ClosureType::Ref,
9082            };
9083            let index = ensure_closure(stack, level, name, is_const, is_lexical, kind, previous.1);
9084            previous = (kind, index);
9085        }
9086        let index = previous.1;
9087        return slot_for_closure(&stack[current].closure_vars[index as usize], index);
9088    }
9089
9090    // Declared nowhere: a dynamic global lookup, which sloppy mode may satisfy by
9091    // creating a property. The top-level function holds the entry.
9092    let mut previous = (
9093        ClosureType::Global,
9094        ensure_closure(stack, 0, name, false, false, ClosureType::Global, 0),
9095    );
9096    for level in 1..=current {
9097        let index = ensure_closure(
9098            stack,
9099            level,
9100            name,
9101            false,
9102            false,
9103            ClosureType::GlobalRef,
9104            previous.1,
9105        );
9106        previous = (ClosureType::GlobalRef, index);
9107    }
9108    Slot::Global(previous.1)
9109}
9110
9111/// What an outward search turned up.
9112#[derive(Debug, Clone, Copy)]
9113enum Found {
9114    /// A binding in an enclosing function, reachable through a closure of this
9115    /// type, with its const/lexical flags.
9116    Local(ClosureType, u32, bool, bool),
9117    /// A global, reached through the enclosing function's closure entry.
9118    Global(u32),
9119}
9120
9121/// Add a closure entry to `level` if it is not there yet.
9122fn ensure_closure(
9123    stack: &mut [FnState],
9124    level: usize,
9125    name: &str,
9126    is_const: bool,
9127    is_lexical: bool,
9128    closure_type: ClosureType,
9129    var_idx: u32,
9130) -> u32 {
9131    if let Some(index) = stack[level]
9132        .closure_vars
9133        .iter()
9134        .position(|c| c.name == name)
9135    {
9136        return index as u32;
9137    }
9138    stack[level].closure_vars.push(ClosureVar {
9139        name: name.to_string(),
9140        is_const,
9141        is_lexical,
9142        closure_type,
9143        var_idx: var_idx as u16,
9144    });
9145    stack[level].closure_vars.len() as u32 - 1
9146}
9147
9148fn slot_for_closure(closure: &ClosureVar, index: u32) -> Slot {
9149    match closure.closure_type {
9150        // A `global_ref` only says *how* the binding is found (through the
9151        // parent's closure table); the access itself is an ordinary global one.
9152        ClosureType::Global | ClosureType::GlobalRef => Slot::Global(index),
9153        ClosureType::GlobalDecl => Slot::GlobalDecl(index),
9154        // A module variable is a real cell in the module's environment, so it is reached
9155        // exactly like a captured local — the host, not the global object, is what fills
9156        // the slot.
9157        ClosureType::ModuleDecl | ClosureType::ModuleImport => Slot::VarRef(index),
9158        _ => Slot::VarRef(index),
9159    }
9160}
9161
9162/// Pick the opcode for one variable access.
9163///
9164/// The `_check` variants are what enforce the temporal dead zone. They are used
9165/// for every access to a `let`/`const` binding except its own initialisation —
9166/// which is exactly the operation that takes the binding out of the dead zone.
9167fn variable_instruction(
9168    stack: &[FnState],
9169    current: usize,
9170    action: VarAction,
9171    slot: Slot,
9172) -> (Opcode, Vec<Op>) {
9173    let lexical = match slot {
9174        Slot::Loc(index) => stack[current]
9175            .vars
9176            .get(index as usize)
9177            .is_some_and(|v| v.needs_check()),
9178        Slot::VarRef(index) => stack[current]
9179            .closure_vars
9180            .get(index as usize)
9181            .is_some_and(|c| c.is_lexical),
9182        _ => false,
9183    };
9184    let operand = vec![Op::Slot(slot)];
9185    match (action, slot) {
9186        (VarAction::Get, Slot::Loc(index)) => (
9187            if lexical {
9188                Opcode::GetLocCheck
9189            } else {
9190                Opcode::GetLoc
9191            },
9192            vec![Op::Slot(Slot::Loc(index))],
9193        ),
9194        (VarAction::Get, Slot::Arg(index)) => (Opcode::GetArg, vec![Op::Slot(Slot::Arg(index))]),
9195        (VarAction::Get, Slot::VarRef(index)) => (
9196            if lexical {
9197                Opcode::GetVarRefCheck
9198            } else {
9199                Opcode::GetVarRef
9200            },
9201            vec![Op::Slot(Slot::VarRef(index))],
9202        ),
9203        (VarAction::Get, Slot::Global(_)) => (Opcode::GetVar, operand),
9204        (VarAction::Get, Slot::GlobalDecl(_)) => (Opcode::GetVar, operand),
9205        // `typeof x` is a *reading* of `x` (§13.5.3 evaluates the operand as a Reference and
9206        // then `GetValue`s it), so a lexical binding still has its dead zone checked. Only
9207        // the *unresolvable* case is different: `typeof undeclared` answers `"undefined"`
9208        // instead of throwing, and that is what `GetVarUndef` is for. Skipping the check for
9209        // every slot made `typeof x; let x;` print `"undefined"` where the spec requires a
9210        // `ReferenceError`.
9211        (VarAction::GetUndef, Slot::Loc(index)) => (
9212            if lexical {
9213                Opcode::GetLocCheck
9214            } else {
9215                Opcode::GetLoc
9216            },
9217            vec![Op::Slot(Slot::Loc(index))],
9218        ),
9219        (VarAction::GetUndef, Slot::Arg(_)) => (Opcode::GetArg, operand),
9220        (VarAction::GetUndef, Slot::VarRef(index)) => (
9221            if lexical {
9222                Opcode::GetVarRefCheck
9223            } else {
9224                Opcode::GetVarRef
9225            },
9226            vec![Op::Slot(Slot::VarRef(index))],
9227        ),
9228        (VarAction::GetUndef, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9229            (Opcode::GetVarUndef, operand)
9230        }
9231
9232        (VarAction::Put, Slot::Loc(_)) => (
9233            if lexical {
9234                Opcode::PutLocCheck
9235            } else {
9236                Opcode::PutLoc
9237            },
9238            operand,
9239        ),
9240        (VarAction::Put, Slot::Arg(_)) => (Opcode::PutArg, operand),
9241        (VarAction::Put, Slot::VarRef(_)) => (
9242            if lexical {
9243                Opcode::PutVarRefCheck
9244            } else {
9245                Opcode::PutVarRef
9246            },
9247            operand,
9248        ),
9249        (VarAction::Put, Slot::Global(_)) => (Opcode::PutVar, operand),
9250        (VarAction::Put, Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9251        // Initialisation is what ends the dead zone, so it never checks.
9252        (VarAction::PutInit, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9253        (VarAction::PutInitChecked, Slot::Loc(_)) => (Opcode::PutLocCheckInit, operand),
9254        // `this` in a derived constructor is always a local, so these cannot happen;
9255        // routing them to the ordinary forms keeps the match total without inventing
9256        // opcodes the reference does not have.
9257        (VarAction::PutInitChecked, Slot::Arg(_)) => (Opcode::PutArg, operand),
9258        // The captured form of `PutLocCheckInit`: `super()` inside an arrow that closes over
9259        // the constructor's `this` still has to refuse a second initialisation, and the
9260        // plain store accepted it (`fields-run-once-on-double-super`).
9261        (VarAction::PutInitChecked, Slot::VarRef(_)) => (Opcode::PutVarRefCheckInit, operand),
9262        (VarAction::PutInitChecked, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9263            (Opcode::PutVarInit, operand)
9264        }
9265        (VarAction::PutInit, Slot::Arg(_)) => (Opcode::PutArg, operand),
9266        (VarAction::PutInit, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9267        (VarAction::PutInit, Slot::Global(_) | Slot::GlobalDecl(_)) => {
9268            (Opcode::PutVarInit, operand)
9269        }
9270        (VarAction::Set, Slot::Loc(_)) => (
9271            if lexical {
9272                Opcode::SetLocCheck
9273            } else {
9274                Opcode::SetLoc
9275            },
9276            operand,
9277        ),
9278        (VarAction::SetInit, Slot::Loc(_)) => (Opcode::SetLoc, operand),
9279        (VarAction::SetInit, Slot::Arg(_)) => (Opcode::SetArg, operand),
9280        (VarAction::SetInit, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9281        (VarAction::SetInit, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVar, operand),
9282        (VarAction::Set, Slot::Arg(_)) => (Opcode::SetArg, operand),
9283        (VarAction::Set, Slot::VarRef(_)) => (Opcode::SetVarRef, operand),
9284        (VarAction::Set, Slot::Global(_)) => (Opcode::PutVar, operand),
9285        (VarAction::Set, Slot::GlobalDecl(_)) => (Opcode::SetVarRef, operand),
9286        (VarAction::PutRef, Slot::Loc(_)) => (Opcode::PutLoc, operand),
9287        (VarAction::PutRef, Slot::Arg(_)) => (Opcode::PutArg, operand),
9288        (VarAction::PutRef, Slot::VarRef(_)) => (Opcode::PutVarRef, operand),
9289        (VarAction::PutRef, Slot::Global(_) | Slot::GlobalDecl(_)) => (Opcode::PutVarRef, operand),
9290    }
9291}
9292
9293/// The instruction-rewriting pass.
9294///
9295/// These are the reference implementation's patterns, restricted to the ones the
9296/// constructs this compiler supports can produce. Each entry is a comment on the
9297/// bytecode it removes, because the whole point is that the result is one
9298/// instruction shorter than the literal translation of the AST.
9299fn peephole(
9300    insns: &mut [Option<(Opcode, Vec<Op>)>],
9301    label_at: &[Option<u32>],
9302    placed: &[Option<usize>],
9303) {
9304    fold_dup_patterns(insns, label_at);
9305
9306    // `drop` before `return_undef` is dead: the return discards the whole frame
9307    // anyway. This runs *after* the `dup` folds, because a `dup; put; drop` there
9308    // consumes its own `drop`; removing the drop first would leave the `dup` and
9309    // produce a `set_` where the reference has a `put_`.
9310    for index in 0..insns.len() {
9311        if opcode_at(insns, index) != Some(Opcode::Drop) {
9312            continue;
9313        }
9314        // Skip over a run of drops, but stop at a jump target: removing code on
9315        // one side of a label would silently retarget the jump.
9316        let mut next = index + 1;
9317        while opcode_at(insns, next) == Some(Opcode::Drop) && !is_label_at(label_at, next) {
9318            next += 1;
9319        }
9320        if is_label_at(label_at, next) {
9321            continue;
9322        }
9323        if opcode_at(insns, next) == Some(Opcode::ReturnUndef) {
9324            for entry in &mut insns[index..next] {
9325                *entry = None;
9326            }
9327        }
9328    }
9329
9330    // The rewrites below all decide against one fixed snapshot, which is what the
9331    // reference sees: `code_match` reads the bytecode buffer as it was on entry to
9332    // the pass, so a rule never observes what an earlier rule removed. Gathering
9333    // every deletion first and applying them together reproduces that.
9334    let snapshot: Vec<Option<Opcode>> = insns
9335        .iter()
9336        .map(|entry| entry.as_ref().map(|(op, _)| *op))
9337        .collect();
9338    // The next instruction that is still there. Holes left by dead-code
9339    // elimination are not instructions, so a rule looks past them.
9340    let next_op = |index: usize| -> Option<usize> {
9341        (index + 1..snapshot.len()).find(|position| snapshot[*position].is_some())
9342    };
9343
9344    let mut doomed = vec![false; insns.len()];
9345    for index in 0..insns.len() {
9346        // A constant pushed only to be dropped does nothing at all. This is what a
9347        // comma expression with a literal left operand compiles to — `(0, f)()` — and
9348        // the reference removes the pair rather than making the reader step over it.
9349        let constant = matches!(
9350            snapshot[index],
9351            Some(
9352                Opcode::Undefined
9353                    | Opcode::Null
9354                    | Opcode::PushMinus1
9355                    | Opcode::Push0
9356                    | Opcode::Push1
9357                    | Opcode::Push2
9358                    | Opcode::Push3
9359                    | Opcode::Push4
9360                    | Opcode::Push5
9361                    | Opcode::Push6
9362                    | Opcode::Push7
9363                    | Opcode::PushTrue
9364                    | Opcode::PushFalse
9365                    | Opcode::PushI32
9366            )
9367        );
9368        if constant
9369            && let Some(next) = next_op(index)
9370            && snapshot[next] == Some(Opcode::Drop)
9371        {
9372            doomed[index] = true;
9373            doomed[next] = true;
9374        }
9375    }
9376    for (index, entry) in insns.iter_mut().enumerate() {
9377        if doomed[index] {
9378            *entry = None;
9379        }
9380    }
9381
9382    // A conditional whose destination is the very next instruction just pops its
9383    // condition, so it becomes a plain `drop`. This is what an empty `case` clause
9384    // compiles to.
9385    //
9386    // Order matters, and it is the reference's order: this runs *before* the
9387    // folding below, on the instruction the conditional originally had. Folding
9388    // moves a conditional's destination, and the reference never re-examines it
9389    // afterwards — which is why `if (c) continue;` at the end of a `do` body stays
9390    // a conditional even though folding leaves it pointing at the next
9391    // instruction.
9392    for (index, entry) in insns.iter_mut().enumerate() {
9393        let Some((op, operands)) = entry.clone() else {
9394            continue;
9395        };
9396        if !matches!(op, Opcode::IfTrue | Opcode::IfFalse) {
9397            continue;
9398        }
9399        let Some(id) = label_id(&operands) else {
9400            continue;
9401        };
9402        if placed.get(id as usize).copied().flatten() == Some(index + 1) {
9403            *entry = Some((Opcode::Drop, Vec::new()));
9404        }
9405    }
9406
9407    // A constant condition is decided here rather than at run time.
9408    fold_constant_conditions(insns, label_at);
9409    // The conditional folding below is about pairs of *real* branches, so it runs
9410    // before a jump to the next instruction is dropped: `do { … if (c) continue }
9411    // while (t)` puts `continue` exactly on the condition, and the reference inverts
9412    // the branch first and only then notices the jump goes nowhere.
9413    fold_conditional_jumps(insns, label_at, placed);
9414
9415    // A jump whose destination is the very next instruction does nothing, which is
9416    // what constant folding leaves behind for `while (1) { … }`.
9417    remove_jump_to_next(insns, placed);
9418
9419    // `put_x(n) get_x(n)` -> `set_x(n)`, which is what a declaration followed by
9420    // a use of the same variable boils down to.
9421    for index in 0..insns.len() {
9422        let Some((put_op, _)) = insns[index].clone() else {
9423            continue;
9424        };
9425        if !is_foldable_put(put_op) {
9426            continue;
9427        }
9428        if is_label_at(label_at, index + 1) {
9429            continue;
9430        }
9431        let Some((get_op, get_operands)) = insns.get(index + 1).cloned().flatten() else {
9432            continue;
9433        };
9434        if get_op != get_form_of(put_op) {
9435            continue;
9436        }
9437        let put_slot = insns[index].as_ref().and_then(|(_, o)| o.first().cloned());
9438        if put_slot.is_none() || put_slot != get_operands.first().cloned() {
9439            continue;
9440        }
9441        insns[index] = Some((set_form_of(put_op), get_operands));
9442        insns[index + 1] = None;
9443    }
9444}
9445
9446/// Drop `gosub`s that call an empty subroutine.
9447///
9448/// A `gosub` whose target starts with `ret` returns immediately, so the reference
9449/// drops the call. This is how `try`/`catch` without a `finally` loses its
9450/// finalizer plumbing: the finalizer block is empty, its first instruction is
9451/// `ret`, and every `gosub` to it disappears — leaving the `ret` unreachable, which
9452/// [`eliminate_dead_code`] then removes.
9453fn strip_empty_gosubs(stack: &mut [FnState], current: usize) {
9454    let state = &stack[current];
9455    let mut targets = Vec::new();
9456    for insn in &state.insns {
9457        if let Insn::Fixed { op, operands } = insn
9458            && *op == Opcode::Gosub
9459            && let Some(id) = label_id(operands)
9460            && let Some(target) = state.labels.get(id as usize).copied().flatten()
9461        {
9462            targets.push(target);
9463        }
9464    }
9465    let empty: Vec<usize> = targets
9466        .into_iter()
9467        .filter(|target| {
9468            stack[current]
9469                .insns
9470                .get(*target)
9471                .map(|insn| {
9472                    matches!(
9473                        insn,
9474                        Insn::Fixed {
9475                            op: Opcode::Ret,
9476                            ..
9477                        }
9478                    )
9479                })
9480                .unwrap_or(false)
9481        })
9482        .collect();
9483    if empty.is_empty() {
9484        return;
9485    }
9486    for insn in stack[current].insns.iter_mut() {
9487        if let Insn::Fixed { op, operands } = insn
9488            && *op == Opcode::Gosub
9489            && let Some(id) = label_id(operands)
9490            && let Some(target) = stack[current].labels.get(id as usize).copied().flatten()
9491            && empty.contains(&target)
9492        {
9493            *insn = Insn::Dead;
9494        }
9495    }
9496}
9497
9498/// Replace unreachable instructions with [`Insn::Dead`].
9499fn eliminate_dead_code(stack: &mut [FnState], current: usize) {
9500    let reachable = reachable_instructions(&stack[current], stack[current].insns.len());
9501    for (index, insn) in stack[current].insns.iter_mut().enumerate() {
9502        if !reachable[index] {
9503            *insn = Insn::Dead;
9504        }
9505    }
9506}
9507
9508/// Mark every instruction index reachable from the entry, plus the index one past
9509/// the last instruction.
9510///
9511/// `seen[len]` answers "can control reach the end of this function", and the
9512/// entries before it identify dead code. Both DCE and the implicit-return decision
9513/// read the same result, which keeps them from disagreeing.
9514fn reachable_instructions(state: &FnState, count: usize) -> Vec<bool> {
9515    let mut seen = vec![false; count + 1];
9516    let mut worklist = vec![0usize];
9517    while let Some(index) = worklist.pop() {
9518        if index > count || seen[index] {
9519            continue;
9520        }
9521        seen[index] = true;
9522        if index == count {
9523            continue;
9524        }
9525        let (op, operands) = match &state.insns[index] {
9526            Insn::Fixed { op, operands } => (*op, operands.as_slice()),
9527            // A variable access never transfers control, and a removed
9528            // instruction is only reachable if it is already marked.
9529            Insn::Var { .. } | Insn::CloseCaptured { .. } | Insn::DeleteVar { .. } | Insn::Dead => {
9530                worklist.push(index + 1);
9531                continue;
9532            }
9533        };
9534        match op {
9535            // A return, a throw and a `ret` all leave this instruction stream: the
9536            // first two give control to the caller or the handler, and `ret`
9537            // returns to a `gosub` elsewhere.
9538            // A tail call leaves the function too: the callee's result becomes this
9539            // function's result, so nothing after it runs.
9540            Opcode::Return
9541            | Opcode::ReturnUndef
9542            | Opcode::ReturnAsync
9543            | Opcode::TailCall
9544            | Opcode::TailCallMethod
9545            | Opcode::Throw
9546            | Opcode::ThrowError
9547            | Opcode::Ret => {}
9548            // A `catch` records where exceptions from the code that follows go.
9549            // That code is not reachable through normal control flow, but it is
9550            // reachable — through the exception edge — so the walk has to follow
9551            // it, or dead-code elimination would delete every handler.
9552            Opcode::Catch => {
9553                if let Some(target) = placed_label(state, operands) {
9554                    worklist.push(target);
9555                }
9556                worklist.push(index + 1);
9557            }
9558            // A `gosub` calls a subroutine and then continues, so both edges count.
9559            Opcode::Gosub => {
9560                if let Some(target) = placed_label(state, operands) {
9561                    worklist.push(target);
9562                }
9563                worklist.push(index + 1);
9564            }
9565            Opcode::Goto => {
9566                if let Some(target) = placed_label(state, operands) {
9567                    worklist.push(target);
9568                }
9569            }
9570            Opcode::IfTrue | Opcode::IfFalse => {
9571                if let Some(target) = placed_label(state, operands) {
9572                    worklist.push(target);
9573                }
9574                worklist.push(index + 1);
9575            }
9576            _ => worklist.push(index + 1),
9577        }
9578    }
9579    seen
9580}
9581
9582/// The instruction index a jump operand points at, resolved through the label
9583/// placement table.
9584fn placed_label(state: &FnState, operands: &[Op]) -> Option<usize> {
9585    let id = label_id(operands)?;
9586    state.labels.get(id as usize).copied().flatten()
9587}
9588
9589/// The label an instruction refers to.
9590fn label_id(operands: &[Op]) -> Option<u32> {
9591    operands.iter().find_map(|operand| match operand {
9592        Op::Label(label) => Some(label.0),
9593        _ => None,
9594    })
9595}
9596
9597/// Turn `if_false L; goto M; L:` into `if_true M`.
9598///
9599/// A conditional whose alternate branch is an unconditional jump needs one jump,
9600/// not two. This is the shape `if (c) break;` produces, so folding it removes an
9601/// instruction and a label from every conditional `break`.
9602/// The boolean a constant-push instruction produces, or `None` if it is not one.
9603///
9604/// Only the operators whose truthiness is decided by the opcode are covered; a
9605/// constant that needs the constant pool (a string) is left alone, because reading it
9606/// would mean threading the pool through the peephole for a case the reference also
9607/// skips.
9608fn constant_truth(op: Opcode, operands: &[Op]) -> Option<bool> {
9609    match op {
9610        // `push_0` returns -1 for zero, `push_1` 1, and so on.
9611        Opcode::PushMinus1 => Some(true),
9612        Opcode::Push0 => Some(false),
9613        Opcode::Push1
9614        | Opcode::Push2
9615        | Opcode::Push3
9616        | Opcode::Push4
9617        | Opcode::Push5
9618        | Opcode::Push6
9619        | Opcode::Push7 => Some(true),
9620        Opcode::PushTrue => Some(true),
9621        Opcode::PushFalse => Some(false),
9622        Opcode::Undefined | Opcode::Null => Some(false),
9623        Opcode::PushI32 => match operands.first() {
9624            Some(Op::Int(value)) => Some(*value != 0),
9625            _ => None,
9626        },
9627        _ => None,
9628    }
9629}
9630
9631/// Fold a branch on a constant condition.
9632///
9633/// `if (0) a() else b()` must not test anything at run time, and the reference
9634/// compiles it to a plain `goto`. Removing the test also removes the unreachable arm,
9635/// which is why the bytecode for a `while (1)` loop has no condition at all.
9636///
9637/// Two instructions become one, so the slot the test occupied is left empty rather
9638/// than shifting everything after it: labels have already been resolved to indices.
9639fn fold_constant_conditions(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
9640    for index in 0..insns.len() {
9641        let Some((push_op, push_operands)) = insns[index].clone() else {
9642            continue;
9643        };
9644        let Some(truth) = constant_truth(push_op, &push_operands) else {
9645            continue;
9646        };
9647        let Some((branch_op, branch_operands)) = insns.get(index + 1).cloned().flatten() else {
9648            continue;
9649        };
9650        // A label on the branch means something else jumps *here* — the value is on the
9651        // stack and the conditional is what pops it. Deleting the branch would leave that
9652        // jump with no instruction, and a label whose slot is empty resolves to the next
9653        // one that is not, i.e. to the far side of the branch. That is how
9654        // `if (a && false) then else` jumped to `then`: `&&` ends its chain on a label, and
9655        // the constant `false` sits directly in front of the statement's own conditional.
9656        if is_label_at(label_at, index + 1) {
9657            continue;
9658        }
9659        let (destination, taken) = match branch_op {
9660            Opcode::IfTrue => (branch_operands.first().cloned(), truth),
9661            Opcode::IfFalse => (branch_operands.first().cloned(), !truth),
9662            _ => continue,
9663        };
9664        let Some(destination) = destination else {
9665            continue;
9666        };
9667        insns[index] = if taken {
9668            // The branch is always taken, so it becomes an unconditional jump.
9669            Some((Opcode::Goto, vec![destination]))
9670        } else {
9671            // The branch never runs: both instructions disappear and control falls
9672            // through to what came after.
9673            None
9674        };
9675        insns[index + 1] = None;
9676    }
9677}
9678
9679/// Remove a jump whose destination is the instruction right after it.
9680///
9681/// Folding a constant condition leaves these behind often: `while (1) { ... }` turns
9682/// its test into nothing, and the loop-end jump then points at the following
9683/// instruction. The reference drops them, so `stack_size` and the listing agree.
9684fn remove_jump_to_next(insns: &mut [Option<(Opcode, Vec<Op>)>], placed: &[Option<usize>]) {
9685    for index in 0..insns.len() {
9686        let Some((op, operands)) = insns[index].clone() else {
9687            continue;
9688        };
9689        if !is_goto(op) {
9690            continue;
9691        }
9692        let Some(id) = label_id(&operands) else {
9693            continue;
9694        };
9695        // The next instruction that still exists, which is what "the instruction
9696        // after this jump" means once earlier folds have punched holes.
9697        let next = (index + 1..insns.len()).find(|position| insns[*position].is_some());
9698        if placed.get(id as usize).copied().flatten() == next {
9699            insns[index] = None;
9700        }
9701    }
9702}
9703
9704fn fold_conditional_jumps(
9705    insns: &mut [Option<(Opcode, Vec<Op>)>],
9706    label_at: &[Option<u32>],
9707    placed: &[Option<usize>],
9708) {
9709    for index in 0..insns.len() {
9710        let Some((op, operands)) = insns[index].clone() else {
9711            continue;
9712        };
9713        let inverted = match op {
9714            Opcode::IfFalse => Opcode::IfTrue,
9715            Opcode::IfTrue => Opcode::IfFalse,
9716            _ => continue,
9717        };
9718        // Next must be an unconditional jump that is not itself a target, and the
9719        // instruction after it must be exactly where the conditional goes.
9720        let Some((next_op, next_operands)) = insns.get(index + 1).cloned().flatten() else {
9721            continue;
9722        };
9723        if !is_goto(next_op) || is_label_at(label_at, index + 1) {
9724            continue;
9725        }
9726        // The conditional must land on the instruction *after* the jump. Several
9727        // labels can share a position, so this asks where *this* label was put
9728        // rather than what label happens to sit there.
9729        let Some(taken) = label_id(&operands) else {
9730            continue;
9731        };
9732        if placed.get(taken as usize).copied().flatten() != Some(index + 2) {
9733            continue;
9734        }
9735        let Some(destination) = next_operands.first().cloned() else {
9736            continue;
9737        };
9738        insns[index] = Some((inverted, vec![destination]));
9739        insns[index + 1] = None;
9740    }
9741}
9742
9743/// Whether a jump target is placed at this instruction index.
9744fn is_label_at(label_at: &[Option<u32>], index: usize) -> bool {
9745    label_at.get(index).copied().flatten().is_some()
9746}
9747
9748fn fold_dup_patterns(insns: &mut [Option<(Opcode, Vec<Op>)>], label_at: &[Option<u32>]) {
9749    // `dup put_x(n)` -> `set_x(n)`
9750    // `dup put_x(n) drop` -> `put_x(n)`
9751    // `dup put_x(n) drop get_x(n)` -> `set_x(n)`
9752    for index in 0..insns.len() {
9753        if opcode_at(insns, index) != Some(Opcode::Dup) {
9754            continue;
9755        }
9756        if is_label_at(label_at, index + 1) {
9757            continue;
9758        }
9759        let Some((put_op, put_operands)) = insns[index + 1].clone() else {
9760            continue;
9761        };
9762        if !is_foldable_put(put_op) {
9763            continue;
9764        }
9765        let Some(Op::Slot(slot)) = put_operands.first().cloned() else {
9766            continue;
9767        };
9768        let mut new_op = set_form_of(put_op);
9769        let mut end = index + 2;
9770        if is_label_at(label_at, end) {
9771            // The `put` has to stay as it is; only the `dup` can be folded.
9772            insns[index] = Some((set_form_of(put_op), vec![Op::Slot(slot)]));
9773            insns[index + 1] = None;
9774            continue;
9775        }
9776        // A `drop` or a `get` that is the target of a jump must stay exactly where it is.
9777        // Deleting it moves the label's target onto whatever follows, and the code that
9778        // jumps there arrives with a different stack than the fall-through path: that is
9779        // how `p = "x"; if (c) { p = "a"; } return p;` came to return `undefined` — the
9780        // `get_x` the `if` jumped to was folded away, so the jump landed on `return` with
9781        // an empty stack. The store had already consumed the value it was supposed to
9782        // leave behind.
9783        if opcode_at(insns, end) == Some(Opcode::Drop) && !is_label_at(label_at, end) {
9784            new_op = put_op;
9785            end += 1;
9786            if opcode_at(insns, end) == Some(get_form_of(put_op))
9787                && !is_label_at(label_at, end)
9788                && insns[end]
9789                    .as_ref()
9790                    .is_some_and(|(_, operands)| operands.first() == Some(&Op::Slot(slot)))
9791            {
9792                new_op = set_form_of(put_op);
9793                end += 1;
9794            }
9795        }
9796        insns[index] = Some((new_op, vec![Op::Slot(slot)]));
9797        for entry in &mut insns[index + 1..end] {
9798            *entry = None;
9799        }
9800    }
9801}
9802
9803fn opcode_at(insns: &[Option<(Opcode, Vec<Op>)>], index: usize) -> Option<Opcode> {
9804    insns
9805        .get(index)
9806        .and_then(|entry| entry.as_ref())
9807        .map(|(op, _)| *op)
9808}
9809
9810/// The four `put_` families that have a `set_` twin. Deliberately not including
9811/// the global forms or `put_var_ref_check`: the reference's peephole lists exactly
9812/// these, and folding the others would produce instructions that do not exist.
9813fn is_foldable_put(op: Opcode) -> bool {
9814    matches!(
9815        op,
9816        Opcode::PutLoc | Opcode::PutLocCheck | Opcode::PutArg | Opcode::PutVarRef
9817    )
9818}
9819
9820fn set_form_of(op: Opcode) -> Opcode {
9821    match op {
9822        Opcode::PutLoc => Opcode::SetLoc,
9823        Opcode::PutLocCheck => Opcode::SetLocCheck,
9824        Opcode::PutArg => Opcode::SetArg,
9825        Opcode::PutVarRef => Opcode::SetVarRef,
9826        other => other,
9827    }
9828}
9829
9830fn get_form_of(op: Opcode) -> Opcode {
9831    match op {
9832        Opcode::PutLoc => Opcode::GetLoc,
9833        Opcode::PutLocCheck => Opcode::GetLocCheck,
9834        Opcode::PutArg => Opcode::GetArg,
9835        Opcode::PutVarRef => Opcode::GetVarRef,
9836        other => other,
9837    }
9838}
9839
9840/// Atom interning, per function.
9841///
9842/// Everything the reference interns goes through `JS_NewAtomStr`, including plain
9843/// identifiers, so the array-index rule applies here rather than at the handful of
9844/// call sites that build property keys.
9845fn intern_atom(state: &mut FnState, name: &str) -> u32 {
9846    intern_atom_value(state, Atom::from_text(name))
9847}
9848
9849/// [`intern_atom`] for an operand that is already an [`Atom`].
9850///
9851/// Separate because `Atom::Null` has no text form: going through `Display` turned it into
9852/// the *string* `"null"`, which is what `throw_error` printed and what a `delete super.x`
9853/// would have looked up.
9854fn intern_atom_value(state: &mut FnState, atom: Atom) -> u32 {
9855    if let Some(index) = state.atoms.iter().position(|a| *a == atom) {
9856        return index as u32;
9857    }
9858    state.atoms.push(atom);
9859    state.atoms.len() as u32 - 1
9860}
9861
9862fn binary_opcode(op: BinaryOp) -> Opcode {
9863    match op {
9864        BinaryOp::Add => Opcode::Add,
9865        BinaryOp::Sub => Opcode::Sub,
9866        BinaryOp::Mul => Opcode::Mul,
9867        BinaryOp::Div => Opcode::Div,
9868        BinaryOp::Mod => Opcode::Mod,
9869        BinaryOp::Pow => Opcode::Pow,
9870        BinaryOp::BitOr => Opcode::Or,
9871        BinaryOp::BitXor => Opcode::Xor,
9872        BinaryOp::BitAnd => Opcode::And,
9873        BinaryOp::Shl => Opcode::Shl,
9874        BinaryOp::Shr => Opcode::Sar,
9875        BinaryOp::UShr => Opcode::Shr,
9876        BinaryOp::Lt => Opcode::Lt,
9877        BinaryOp::LtEq => Opcode::Lte,
9878        BinaryOp::Gt => Opcode::Gt,
9879        BinaryOp::GtEq => Opcode::Gte,
9880        BinaryOp::Eq => Opcode::Eq,
9881        BinaryOp::NotEq => Opcode::Neq,
9882        BinaryOp::StrictEq => Opcode::StrictEq,
9883        BinaryOp::StrictNotEq => Opcode::StrictNeq,
9884        BinaryOp::In => Opcode::In,
9885        BinaryOp::Instanceof => Opcode::Instanceof,
9886    }
9887}
9888
9889fn compound_opcode(op: AssignOp) -> Opcode {
9890    match op {
9891        AssignOp::Add => Opcode::Add,
9892        AssignOp::Sub => Opcode::Sub,
9893        AssignOp::Mul => Opcode::Mul,
9894        AssignOp::Div => Opcode::Div,
9895        AssignOp::Mod => Opcode::Mod,
9896        AssignOp::Pow => Opcode::Pow,
9897        AssignOp::Shl => Opcode::Shl,
9898        AssignOp::Shr => Opcode::Sar,
9899        AssignOp::UShr => Opcode::Shr,
9900        AssignOp::BitOr => Opcode::Or,
9901        AssignOp::BitXor => Opcode::Xor,
9902        AssignOp::BitAnd => Opcode::And,
9903        AssignOp::Assign | AssignOp::And | AssignOp::Or | AssignOp::Coalesce => Opcode::Nop,
9904    }
9905}
9906
9907/// Encode the resolved instruction stream, choosing short forms where possible.
9908///
9909/// The peephole pass leaves holes in the instruction list so that label indices
9910/// stay valid. A label names an *instruction index*, and an index that was
9911/// deleted has to resolve to the next surviving instruction, which is what
9912/// [`resolve_label`] does before the byte offsets are known.
9913fn assemble(
9914    insns: &mut [Option<(Opcode, Vec<Op>)>],
9915    insn_pos: &[Option<Position>],
9916    state: &mut FnState,
9917) -> (Vec<u8>, u32, Vec<LineCol>) {
9918    // Compaction: surviving instructions in order, plus the index mapping.
9919    //
9920    // `spans` runs parallel to `kept` and is compacted in lock step with it, at every
9921    // point below where instructions are removed — otherwise a stack trace would point
9922    // at the wrong source line as soon as dead-code elimination kicked in.
9923    let mut kept: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(insns.len());
9924    let mut spans: Vec<Option<Position>> = Vec::with_capacity(insns.len());
9925    let mut original_to_kept: Vec<Option<usize>> = vec![None; insns.len()];
9926    for (original, entry) in insns.iter_mut().enumerate() {
9927        if let Some((op, operands)) = entry.take() {
9928            original_to_kept[original] = Some(kept.len());
9929            kept.push((op, operands));
9930            spans.push(insn_pos.get(original).copied().flatten());
9931        }
9932    }
9933
9934    if std::env::var_os("QJS_DEBUG").is_some() {
9935        eprintln!("--- assemble entry --- {kept:?}");
9936    }
9937    // How many labels are real, as opposed to the per-instruction ones allocated
9938    // just below. Only a real label marks a spot in the source program.
9939    let real_labels = state.labels.len();
9940
9941    // Give every surviving instruction a label of its own. Jump cleanup below
9942    // redirects jumps to arbitrary instructions, and a jump target has to be a
9943    // label; pre-allocating one per index means a redirect never has to invent
9944    // anything.
9945    let existing = state.labels.len();
9946    let base = kept.len();
9947    let mut index_label: Vec<Label> = Vec::with_capacity(kept.len() + 1);
9948    for offset in 0..=kept.len() {
9949        state.labels.push(Some(0));
9950        index_label.push(Label((existing + offset) as u32));
9951    }
9952    // Point each pre-allocated label at its instruction, reusing the count from
9953    // `original_to_kept` so the mapping survives compaction.
9954    let place_index_labels = |state: &mut FnState,
9955                              original_to_kept: &[Option<usize>],
9956                              kept_len: usize,
9957                              index_label: &[Label]| {
9958        for (original, mapped) in original_to_kept.iter().enumerate() {
9959            if let Some(kept_index) = mapped {
9960                let label = index_label[*kept_index].0 as usize;
9961                state.labels[label] = Some(original);
9962            }
9963        }
9964        state.labels[index_label[kept_len].0 as usize] = Some(usize::MAX);
9965    };
9966    place_index_labels(state, &original_to_kept, base, &index_label);
9967
9968    // Resolve every label to a kept index once; the placement table maps labels
9969    // to original indices, so a second hop lands in kept space.
9970    let mut label_kept: Vec<Option<usize>> = vec![None; state.labels.len()];
9971    for (id, placed) in state.labels.iter().enumerate() {
9972        let Some(original) = placed else { continue };
9973        label_kept[id] = if *original == usize::MAX {
9974            Some(base)
9975        } else {
9976            (*original..original_to_kept.len()).find_map(|i| original_to_kept[i])
9977        };
9978    }
9979
9980    // Code after an unconditional transfer is unreachable, and the reference drops it
9981    // as it walks past the transfer — the `skip_dead_code` in its first pass. It
9982    // scans forward until it finds a label something still jumps to, so a run of
9983    // dead instructions between a `throw` and the next live target disappears.
9984    //
9985    // The scan repeats because dropping a jump lowers the reference count of the
9986    // label it pointed at, which can strand what follows. Only a real label keeps an
9987    // instruction alive here; the per-instruction labels allocated above belong to
9988    // this pass, not to the program.
9989    loop {
9990        let mut references = vec![false; kept.len() + 1];
9991        for (_, operands) in &kept {
9992            if let Some(target) = target_kept_index(operands, &label_kept)
9993                && target < references.len()
9994            {
9995                references[target] = true;
9996            }
9997        }
9998        let mut doomed = vec![false; kept.len()];
9999        let mut any = false;
10000        for (index, (op, _)) in kept.iter().enumerate() {
10001            if !is_transfer(*op) {
10002                continue;
10003            }
10004            for next in index + 1..kept.len() {
10005                if references[next] {
10006                    break;
10007                }
10008                doomed[next] = true;
10009                any = true;
10010            }
10011        }
10012        if !any {
10013            break;
10014        }
10015        (kept, spans) = drop_instructions(kept, spans, &mut label_kept, &doomed);
10016    }
10017
10018    // A label that lands on an unconditional jump stands for wherever that jump
10019    // goes, so retarget it once and every jump to the label follows for free.
10020    // This is what makes `continue` in a `for` head reach the loop top instead of
10021    // stopping at the update's trailing jump.
10022    let folded: Vec<Option<usize>> = label_kept
10023        .iter()
10024        .map(|slot| slot.map(|target| follow_jump_chain(&kept, &label_kept, target)))
10025        .collect();
10026    label_kept = folded;
10027
10028    // Jump cleanup, in compacted index space. Two rewrites the reference also
10029    // applies while it resolves labels:
10030    //   * a jump whose destination is the very next instruction does nothing;
10031    //   * a jump to a jump is redirected to its final destination.
10032    // The second can expose the first, so this repeats until it settles.
10033    loop {
10034        let mut delete = vec![false; kept.len()];
10035        let mut changed = false;
10036        for index in 0..kept.len() {
10037            let (op, operands) = &kept[index];
10038            if !is_goto(*op) {
10039                continue;
10040            }
10041            let Some(immediate) = target_kept_index(operands, &label_kept) else {
10042                continue;
10043            };
10044            let target = follow_jump_chain(&kept, &label_kept, immediate);
10045            if target == index + 1 {
10046                delete[index] = true;
10047                changed = true;
10048            } else if matches!(
10049                kept.get(target).map(|(op, _)| *op),
10050                Some(Opcode::Return | Opcode::ReturnUndef | Opcode::Throw)
10051            ) {
10052                // Jumping straight to a return or throw is the same as doing it
10053                // here, so the jump becomes that instruction.
10054                kept[index] = (kept[target].0, Vec::new());
10055                changed = true;
10056            } else if target != immediate {
10057                // Redirect to the end of the chain.
10058                let label = index_label[target];
10059                kept[index].1 = vec![Op::Label(label)];
10060                changed = true;
10061            }
10062        }
10063        if !changed {
10064            break;
10065        }
10066        if !delete.iter().any(|deleted| *deleted) {
10067            break;
10068        }
10069        // Drop the deleted instructions and renumber everything.
10070        let mut next: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
10071        let mut next_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
10072        let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
10073        for (old, entry) in kept.into_iter().enumerate() {
10074            if delete[old] {
10075                continue;
10076            }
10077            moved[old] = Some(next.len());
10078            next.push(entry);
10079            next_spans.push(spans[old]);
10080        }
10081        for (id, slot) in label_kept.iter_mut().enumerate() {
10082            let Some(old) = *slot else { continue };
10083            *slot = match moved.get(old).copied().flatten() {
10084                Some(new) => Some(new),
10085                // The target was deleted: the jump now lands on whatever follows.
10086                None => (old..moved.len())
10087                    .find_map(|i| moved[i])
10088                    .or(Some(next.len())),
10089            };
10090            let _ = id;
10091        }
10092        kept = next;
10093        spans = next_spans;
10094    }
10095
10096    // The same walk at the end of the function: `try`/`catch`'s `goto end` becomes a
10097    // jump to the next instruction and is deleted, leaving the label at the end with
10098    // nothing pointing at it. If that also strands the last instruction, it goes
10099    // too — which is how a `try` whose body always returns ends on its `ret` rather
10100    // than an implicit `return_undef`.
10101    // Which instructions something still jumps to. Reading the surviving jumps is
10102    // what the reference's reference counts amount to: once a jump has been folded
10103    // away the label it named is unreferenced, even though the program still has a
10104    // label there.
10105    let mut references = vec![false; kept.len() + 1];
10106    let _ = real_labels;
10107    for (_, operands) in &kept {
10108        if let Some(target) = target_kept_index(operands, &label_kept)
10109            && target < references.len()
10110        {
10111            references[target] = true;
10112        }
10113    }
10114    let mut end = kept.len();
10115    while end > 0 {
10116        let last = end - 1;
10117        let reachable = references[last] || end < kept.len();
10118        if reachable {
10119            break;
10120        }
10121        let after_transfer = last
10122            .checked_sub(1)
10123            .map(|previous| {
10124                matches!(
10125                    kept[previous].0,
10126                    Opcode::Goto | Opcode::Return | Opcode::ReturnUndef | Opcode::Throw
10127                )
10128            })
10129            .unwrap_or(false);
10130        if !after_transfer {
10131            break;
10132        }
10133        end = last;
10134    }
10135    kept.truncate(end);
10136    spans.truncate(end);
10137
10138    // Choose an opcode for each instruction and its size, so label offsets can be
10139    // computed.
10140    let chosen = choose_opcodes(&kept, &label_kept);
10141    let offsets = instruction_offsets(&chosen);
10142    let offset = *offsets.last().unwrap_or(&0);
10143
10144    let mut code = Vec::with_capacity(offset);
10145    for (position, (_, operands)) in kept.iter().enumerate() {
10146        let op = chosen[position];
10147        code.push(op as u8);
10148        let operands = retarget_labels(operands, &label_kept, kept.len());
10149        encode_operands(&mut code, op, &operands, offsets[position], &offsets);
10150    }
10151    let stack_size = compute_stack_size(&code);
10152    // Keep only the offsets where the position actually changes: a run of
10153    // instructions on one line is one table entry, and the runtime binary searches
10154    // the table for the frame's pc.
10155    //
10156    // The table always starts at pc 0 with the *function's own* position, because the
10157    // reference's `compute_pc2line_info` seeds it that way: `dbuf_put_leb128(&s->pc2line,
10158    // last_line_num)` from `fd->source_pos`, the token the function definition starts at
10159    // (`function`, `async`, a method's property name). An instruction before the first
10160    // recorded operator therefore reports the function's own start, which is what makes a
10161    // `using` epilogue with a plain initialiser report `1:2` rather than nothing at all.
10162    let mut positions: Vec<LineCol> = vec![LineCol {
10163        pc: 0,
10164        line: state.line,
10165        column: state.column,
10166    }];
10167    let mut last: Option<Position> = None;
10168    for (index, span) in spans.iter().enumerate() {
10169        let Some(pos) = *span else { continue };
10170        if last == Some(pos) {
10171            continue;
10172        }
10173        last = Some(pos);
10174        if pos.line == state.line && pos.column == state.column {
10175            // Already the seed entry above.
10176            continue;
10177        }
10178        positions.push(LineCol {
10179            pc: offsets[index] as u32,
10180            line: pos.line,
10181            column: pos.column,
10182        });
10183    }
10184    (code, stack_size, positions)
10185}
10186
10187/// Whether an instruction always transfers control away, so anything after it in the
10188/// same stream is unreachable.
10189fn is_transfer(op: Opcode) -> bool {
10190    matches!(
10191        op,
10192        Opcode::Goto
10193            | Opcode::Goto8
10194            | Opcode::Goto16
10195            | Opcode::Return
10196            | Opcode::ReturnUndef
10197            | Opcode::Throw
10198            | Opcode::ThrowError
10199            | Opcode::Ret
10200    )
10201}
10202
10203/// Remove the marked instructions and renumber the label table so it keeps pointing
10204/// at the same instructions. A label whose instruction went away moves to whatever
10205/// follows it, since a jump is never left with nowhere to land.
10206fn drop_instructions(
10207    kept: Vec<(Opcode, Vec<Op>)>,
10208    spans: Vec<Option<Position>>,
10209    label_kept: &mut [Option<usize>],
10210    doomed: &[bool],
10211) -> (Vec<PositionedInsn>, Vec<Option<Position>>) {
10212    let mut result: Vec<(Opcode, Vec<Op>)> = Vec::with_capacity(kept.len());
10213    let mut result_spans: Vec<Option<Position>> = Vec::with_capacity(kept.len());
10214    let mut moved: Vec<Option<usize>> = vec![None; kept.len()];
10215    for (old, entry) in kept.into_iter().enumerate() {
10216        if doomed.get(old).copied().unwrap_or(false) {
10217            continue;
10218        }
10219        moved[old] = Some(result.len());
10220        result.push(entry);
10221        result_spans.push(spans[old]);
10222    }
10223    for slot in label_kept.iter_mut() {
10224        let Some(old) = *slot else { continue };
10225        *slot = match moved.get(old).copied().flatten() {
10226            Some(new) => Some(new),
10227            None => (old..moved.len())
10228                .find_map(|i| moved[i])
10229                .or(Some(result.len())),
10230        };
10231    }
10232    (result, result_spans)
10233}
10234
10235fn is_goto(op: Opcode) -> bool {
10236    matches!(op, Opcode::Goto | Opcode::Goto8 | Opcode::Goto16)
10237}
10238
10239/// The kept index a jump operand points at.
10240fn target_kept_index(operands: &[Op], label_kept: &[Option<usize>]) -> Option<usize> {
10241    let id = label_id(operands)?;
10242    label_kept.get(id as usize).copied().flatten()
10243}
10244
10245/// Follow a chain of unconditional jumps to its first real destination.
10246fn follow_jump_chain(
10247    kept: &[(Opcode, Vec<Op>)],
10248    label_kept: &[Option<usize>],
10249    start: usize,
10250) -> usize {
10251    let mut current = start;
10252    // `for(;;)` jumps to itself, so the walk has to be bounded.
10253    for _ in 0..kept.len() {
10254        let Some((op, operands)) = kept.get(current) else {
10255            return current;
10256        };
10257        if !is_goto(*op) {
10258            return current;
10259        }
10260        let Some(next) = target_kept_index(operands, label_kept) else {
10261            return current;
10262        };
10263        if next == current {
10264            return current;
10265        }
10266        current = next;
10267    }
10268    current
10269}
10270
10271/// Rewrite label operands from label ids to kept instruction indices.
10272fn retarget_labels(operands: &[Op], label_kept: &[Option<usize>], kept_len: usize) -> Vec<Op> {
10273    operands
10274        .iter()
10275        .map(|operand| match operand {
10276            Op::Label(label) => {
10277                let target = label_kept
10278                    .get(label.0 as usize)
10279                    .copied()
10280                    .flatten()
10281                    .unwrap_or(kept_len);
10282                Op::Label(Label(target as u32))
10283            }
10284            other => other.clone(),
10285        })
10286        .collect()
10287}
10288
10289/// Encode the resolved instruction stream, choosing short forms where possible.
10290///
10291/// Compute the maximum value-stack depth by exploring the control-flow graph.
10292///
10293/// This is a breadth-first walk from the first instruction, tracking the stack
10294/// depth on entry to each instruction. Every instruction has at most two
10295/// successors (fall through, and a jump target), so a worklist over byte offsets
10296/// is enough. The reference does the same thing in `compute_stack_size`, which is
10297/// why the resulting numbers match exactly.
10298///
10299/// Instructions that pop a variable number of values (`call`, `array_from`, …)
10300/// encode that count in their operand, which is added to the static `n_pop`.
10301fn compute_stack_size(code: &[u8]) -> u32 {
10302    let mut depth_at = vec![u16::MAX; code.len()];
10303    // Each entry carries the enclosing `catch` levels, innermost last, because
10304    // `nip_catch` needs them: it rewinds the stack to just above the innermost catch
10305    // offset and forgets that level.
10306    let mut worklist: Vec<(usize, u32, Vec<u32>)> = vec![(0, 0, Vec::new())];
10307    let mut max_depth = 0u32;
10308
10309    while let Some((pc, depth, catch_levels)) = worklist.pop() {
10310        if pc >= code.len() {
10311            continue;
10312        }
10313        if depth_at[pc] != u16::MAX {
10314            continue;
10315        }
10316        force_depth(&mut depth_at, pc, depth);
10317
10318        let Some(op) = Opcode::from_u8(code[pc]) else {
10319            break;
10320        };
10321        let info = op.info();
10322        let next = pc + info.size as usize;
10323        if next > code.len() {
10324            break;
10325        }
10326        let mut n_pop = info.n_pop as u32;
10327        let mut n_push = info.n_push as u32;
10328        // Variable-length forms carry their count in the operand.
10329        match info.format {
10330            crate::opcode::OpFormat::Npop | crate::opcode::OpFormat::NpopU16 => {
10331                n_pop += read_u16(code, pc + 1) as u32;
10332            }
10333            crate::opcode::OpFormat::Npopx => {
10334                n_pop += op.specialised_index().unwrap_or(0).max(0) as u32;
10335            }
10336            _ => {}
10337        }
10338        // `put_loc`/`put_arg`/`put_var_ref` keep the value on the stack when they
10339        // are the `set_` variant; the table already records that, so nothing to
10340        // adjust here.
10341        let _ = &mut n_push;
10342
10343        // The depth before this instruction's own push, which is what a `catch`
10344        // records as its level.
10345        let depth_before = depth;
10346        let mut depth = depth.saturating_sub(n_pop) + n_push;
10347        let mut catch_levels = catch_levels;
10348        if op == Opcode::NipCatch {
10349            // Discard everything above the innermost catch offset, keeping the value
10350            // on top: the frame the code after this sees is the same shape it would
10351            // have had if the `try` were not there.
10352            if let Some(base) = catch_levels.pop() {
10353                depth = base + 1;
10354            }
10355        }
10356        max_depth = max_depth.max(depth);
10357
10358        // Successors.
10359        let target = jump_target_of(code, pc, op);
10360        match op {
10361            Opcode::Goto | Opcode::Goto8 | Opcode::Goto16 => {
10362                if let Some(target) = target {
10363                    worklist.push((target, depth, catch_levels));
10364                }
10365            }
10366            Opcode::IfFalse | Opcode::IfFalse8 | Opcode::IfTrue | Opcode::IfTrue8 => {
10367                if let Some(target) = target {
10368                    worklist.push((target, depth, catch_levels.clone()));
10369                }
10370                worklist.push((next, depth, catch_levels));
10371            }
10372            // A `catch` records an exception edge to the handler. The handler is
10373            // entered with the thrown value on top of the stack, in the slot the
10374            // catch offset occupies on the normal path — which is why the handler's
10375            // first instruction can `put_loc` the exception away, and why the depth
10376            // is the same on both paths.
10377            Opcode::Catch => {
10378                if let Some(target) = target {
10379                    // The handler is protected by the *enclosing* catch, not by this
10380                    // one: an error raised inside it is what the handler's own
10381                    // `catch` catches.
10382                    worklist.push((target, depth, catch_levels.clone()));
10383                }
10384                catch_levels.push(depth_before);
10385                worklist.push((next, depth, catch_levels));
10386            }
10387            // A `for`/`of` loop keeps its own catch offset, and `nip_catch` has to
10388            // rewind past it too. Its level sits one slot higher than a `catch`'s:
10389            // the iterator and next-method slots occupy the offset's place.
10390            Opcode::ForOfStart | Opcode::ForAwaitOfStart => {
10391                if let Some(target) = target {
10392                    worklist.push((target, depth, catch_levels.clone()));
10393                }
10394                catch_levels.push(depth_before + 1);
10395                worklist.push((next, depth, catch_levels));
10396            }
10397            // `gosub` calls a subroutine with the return address on top. The opcode
10398            // table records no push for it — `ret` is what pops the slot — so the
10399            // extra one is added here, where the depth of the subroutine's first
10400            // instruction is being computed.
10401            Opcode::Gosub => {
10402                if let Some(target) = target {
10403                    worklist.push((target, depth + 1, catch_levels.clone()));
10404                }
10405                worklist.push((next, depth, catch_levels));
10406            }
10407            // `ret` goes back to a `gosub`; nothing here follows it.
10408            Opcode::Ret
10409            | Opcode::Return
10410            | Opcode::ReturnUndef
10411            | Opcode::Throw
10412            | Opcode::ThrowError => {}
10413            _ => worklist.push((next, depth, catch_levels)),
10414        }
10415    }
10416    max_depth
10417}
10418
10419/// Record the stack depth on entry to `pc`, keeping the deeper value if the
10420/// instruction is reachable more than once.
10421fn force_depth(depth_at: &mut [u16], pc: usize, depth: u32) {
10422    let clamped = depth.min(u16::MAX as u32 - 1) as u16;
10423    if depth_at[pc] == u16::MAX || depth_at[pc] < clamped {
10424        depth_at[pc] = clamped;
10425    }
10426}
10427
10428fn read_u16(code: &[u8], at: usize) -> u16 {
10429    let mut value = 0u16;
10430    for i in 0..2 {
10431        value = (value << 8) | code.get(at + i).copied().unwrap_or(0) as u16;
10432    }
10433    value
10434}
10435
10436/// The absolute target of a jump instruction, if it has one.
10437fn jump_target_of(code: &[u8], pc: usize, op: Opcode) -> Option<usize> {
10438    let info = op.info();
10439    let position = pc + 1;
10440    match info.format {
10441        crate::opcode::OpFormat::Label8 => {
10442            let offset = *code.get(position)? as i8 as i64;
10443            Some((position as i64 + offset) as usize)
10444        }
10445        crate::opcode::OpFormat::Label16 => {
10446            let offset = read_u16(code, position) as i16 as i64;
10447            Some((position as i64 + offset) as usize)
10448        }
10449        crate::opcode::OpFormat::Label => {
10450            let mut offset = 0i32;
10451            for i in 0..4 {
10452                offset = (offset << 8) | *code.get(position + i).unwrap_or(&0) as i32;
10453            }
10454            Some((position as i64 + offset as i64) as usize)
10455        }
10456        _ => None,
10457    }
10458}
10459
10460fn choose_short_form(op: Opcode, operands: &[Op]) -> Opcode {
10461    use Opcode::*;
10462    match (op, operands.first()) {
10463        (PushI32, Some(Op::Int(value))) if (-1..=7).contains(value) => {
10464            op.short_form(*value as u32).unwrap_or(op)
10465        }
10466        (PushConst, Some(Op::Const(index))) if *index < 256 => Opcode::PushConst8,
10467        (Fclosure, Some(Op::Const(index))) if *index < 256 => Opcode::Fclosure8,
10468        (GetLoc | PutLoc | SetLoc, Some(Op::Slot(Slot::Loc(index))))
10469        | (GetArg | PutArg | SetArg, Some(Op::Slot(Slot::Arg(index))))
10470        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::VarRef(index))))
10471        // A declared global is reached through its reference cell, so it shares
10472        // the `var_ref` encodings, short forms included.
10473        | (GetVarRef | PutVarRef | SetVarRef, Some(Op::Slot(Slot::GlobalDecl(index)))) => {
10474            op.short_form(*index).unwrap_or(op)
10475        }
10476        (Call, Some(Op::Int(count))) if (0..=3).contains(count) => {
10477            op.short_form(*count as u32).unwrap_or(op)
10478        }
10479        _ => op,
10480    }
10481}
10482
10483/// The byte offset each instruction will start at, plus the total code size.
10484fn instruction_offsets(chosen: &[Opcode]) -> Vec<usize> {
10485    let mut offsets = Vec::with_capacity(chosen.len() + 1);
10486    let mut offset = 0usize;
10487    for op in chosen {
10488        offsets.push(offset);
10489        offset += op.size() as usize;
10490    }
10491    offsets.push(offset);
10492    offsets
10493}
10494
10495/// Pick an encoding for every instruction, shrinking a jump to its 8-bit form only when
10496/// the offset actually fits.
10497///
10498/// The choice is circular: an instruction's size decides the offsets of everything after
10499/// it, and the offsets decide whether a jump may be short. So this starts with every jump
10500/// in its widest form and shrinks what fits, repeating until a pass changes nothing.
10501/// Shrinking only ever *shortens* distances, so the loop converges.
10502///
10503/// Doing it in one pass instead — which is what this used to do — silently truncated any
10504/// jump further than 127 bytes: `goto8` with a mangled offset lands in the middle of the
10505/// bytecode, and the VM treats running off the end as a return. That is how a nested loop
10506/// with four closures in its body simply stopped, with no error and no output past the
10507/// first iteration.
10508fn choose_opcodes(kept: &[(Opcode, Vec<Op>)], label_kept: &[Option<usize>]) -> Vec<Opcode> {
10509    let mut chosen: Vec<Opcode> = kept
10510        .iter()
10511        .map(|(op, operands)| choose_short_form(*op, operands))
10512        .collect();
10513    // A jump the compiler emitted in its widest form, and the forms it may shrink to.
10514    let candidates = |op: Opcode| match op {
10515        Opcode::Goto => Some((Opcode::Goto8, Opcode::Goto16, true)),
10516        Opcode::IfFalse => Some((Opcode::IfFalse8, Opcode::IfFalse, false)),
10517        Opcode::IfTrue => Some((Opcode::IfTrue8, Opcode::IfTrue, false)),
10518        _ => None,
10519    };
10520    loop {
10521        let offsets = instruction_offsets(&chosen);
10522        let mut changed = false;
10523        for index in 0..kept.len() {
10524            let (op, operands) = &kept[index];
10525            let Some((short, medium, has_medium)) = candidates(*op) else {
10526                continue;
10527            };
10528            if chosen[index] == short {
10529                continue;
10530            }
10531            let Some(target) = target_kept_index(operands, label_kept) else {
10532                continue;
10533            };
10534            let Some(&target_offset) = offsets.get(target) else {
10535                continue;
10536            };
10537            // A jump is relative to the byte after its opcode, which is the convention
10538            // `jump_target_of` decodes with.
10539            let relative = target_offset as i64 - (offsets[index] as i64 + 1);
10540            if (-128..=127).contains(&relative) {
10541                chosen[index] = short;
10542                changed = true;
10543            } else if has_medium
10544                && chosen[index] == Opcode::Goto
10545                && (-32_768..=32_767).contains(&relative)
10546            {
10547                // Too far for 8 bits and close enough for 16. Only `goto` has a medium
10548                // form: `if_false`/`if_true` jump straight from 8 to 32 bits, exactly as
10549                // the reference encodes them.
10550                chosen[index] = medium;
10551                changed = true;
10552            }
10553        }
10554        if !changed {
10555            return chosen;
10556        }
10557    }
10558}
10559
10560fn encode_operands(
10561    code: &mut Vec<u8>,
10562    op: Opcode,
10563    operands: &[Op],
10564    position: usize,
10565    offsets: &[usize],
10566) {
10567    use crate::opcode::OpFormat::*;
10568    let info = op.info();
10569    let write_slot = |code: &mut Vec<u8>, slot: Slot| {
10570        let index = match slot {
10571            Slot::Arg(i)
10572            | Slot::Loc(i)
10573            | Slot::VarRef(i)
10574            | Slot::Global(i)
10575            | Slot::GlobalDecl(i) => i,
10576        };
10577        code.extend_from_slice(&(index as u16).to_be_bytes());
10578    };
10579    match info.format {
10580        None | NoneInt | NoneLoc | NoneArg | NoneVarRef | Npopx => {}
10581        U8 | Const8 => {
10582            if let Some(value) = operands.first().and_then(operand_uint) {
10583                code.push(value as u8);
10584            }
10585        }
10586        // The narrow slot forms (`inc_loc8` and friends) take a slot operand just
10587        // like their wide counterparts, only one byte wide.
10588        Loc8 => {
10589            if let Some(Op::Slot(slot)) = operands.first() {
10590                let index = match slot {
10591                    Slot::Arg(i)
10592                    | Slot::Loc(i)
10593                    | Slot::VarRef(i)
10594                    | Slot::Global(i)
10595                    | Slot::GlobalDecl(i) => *i,
10596                };
10597                code.push(index as u8);
10598            }
10599        }
10600        I8 => {
10601            if let Some(value) = operands.first().and_then(operand_int) {
10602                code.push(value as i8 as u8);
10603            }
10604        }
10605        U16 | Npop => {
10606            if let Some(value) = operands.first().and_then(operand_int) {
10607                code.extend_from_slice(&(value as u16).to_be_bytes());
10608            }
10609        }
10610        I16 => {
10611            if let Some(value) = operands.first().and_then(operand_int) {
10612                code.extend_from_slice(&(value as i16 as u16).to_be_bytes());
10613            }
10614        }
10615        I32 => {
10616            if let Some(value) = operands.first().and_then(operand_int) {
10617                code.extend_from_slice(&value.to_be_bytes());
10618            }
10619        }
10620        U32 | Const => {
10621            if let Some(value) = operands.first().and_then(operand_uint) {
10622                code.extend_from_slice(&value.to_be_bytes());
10623            }
10624        }
10625        Loc | Arg | VarRef => {
10626            if let Some(Op::Slot(slot)) = operands.first() {
10627                write_slot(code, *slot);
10628            }
10629        }
10630        Atom | AtomU8 | AtomU16 | AtomLabelU8 | AtomLabelU16 => {
10631            if let Some(Op::AtomId(index)) = operands.first() {
10632                code.extend_from_slice(&index.to_be_bytes());
10633            }
10634            // The trailing immediate means different things per format, and the
10635            // atom forms that carry a *label* have to resolve it like any other
10636            // jump, so they cannot share the `U8`/`U16` arms above.
10637            match info.format {
10638                AtomU8 | AtomLabelU8 => {
10639                    if let Some(value) = operands.get(1).and_then(operand_uint) {
10640                        code.push(value as u8);
10641                    }
10642                }
10643                AtomU16 | AtomLabelU16 => {
10644                    if let Some(value) = operands.get(1).and_then(operand_uint) {
10645                        code.extend_from_slice(&(value as u16).to_be_bytes());
10646                    }
10647                }
10648                _ => {}
10649            }
10650        }
10651        NpopU16 => {
10652            for operand in operands.iter().take(2) {
10653                if let Some(value) = operand_uint(operand) {
10654                    code.extend_from_slice(&(value as u16).to_be_bytes());
10655                }
10656            }
10657        }
10658        Label | Label8 | Label16 | LabelU16 => {
10659            if let Some(Op::Label(label)) = operands.first() {
10660                // Labels were already remapped to kept-instruction indices.
10661                let Some(&target) = offsets.get(label.0 as usize) else {
10662                    debug_assert!(false, "label {} is past the end", label.0);
10663                    return;
10664                };
10665                let relative = target as i64 - (position as i64 + 1);
10666                match info.format {
10667                    Label8 => code.push(relative as i8 as u8),
10668                    Label16 => code.extend_from_slice(&(relative as i16 as u16).to_be_bytes()),
10669                    // `label_u16` stores the target followed by an unrelated u16.
10670                    LabelU16 => {
10671                        code.extend_from_slice(&(relative as i32).to_be_bytes());
10672                        if let Some(value) = operands.get(1).and_then(operand_uint) {
10673                            code.extend_from_slice(&(value as u16).to_be_bytes());
10674                        }
10675                    }
10676                    _ => code.extend_from_slice(&(relative as i32).to_be_bytes()),
10677                }
10678            }
10679        }
10680    }
10681}
10682
10683fn operand_int(op: &Op) -> Option<i32> {
10684    match op {
10685        Op::Int(value) => Some(*value),
10686        _ => None,
10687    }
10688}
10689
10690fn operand_uint(op: &Op) -> Option<u32> {
10691    match op {
10692        Op::Const(value) | Op::AtomId(value) => Some(*value),
10693        Op::Int(value) => Some(*value as u32),
10694        _ => None,
10695    }
10696}
10697
10698/// Disassemble a compiled function.
10699pub fn disassemble(function: &CompiledFunction) -> String {
10700    disasm::disassemble_program(function)
10701}
10702
10703/// How many of an object pattern's keys are computed.
10704///
10705/// Only the count matters: a rest element needs a run-time key log exactly when at least one
10706/// key is not a literal, and the log is sized by walking the pattern anyway.
10707fn computed_key_count(properties: &[Option<PatternElement>]) -> usize {
10708    properties
10709        .iter()
10710        .flatten()
10711        .filter(|element| {
10712            matches!(
10713                element,
10714                PatternElement::Property {
10715                    key: PropName::Computed(_),
10716                    ..
10717                }
10718            )
10719        })
10720        .count()
10721}